python_code stringlengths 0 4.04M | repo_name stringlengths 7 58 | file_path stringlengths 5 147 |
|---|---|---|
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torchvision.models.resnet import resnet50 as _resnet50
dependencies = ['torch', 'torchvision']
def res... | barlowtwins-main | hubconf.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from pathlib import Path
import argparse
import json
import math
import os
import random
import signal
import subprocess
im... | barlowtwins-main | main.py |
TART-main | src/__init__.py | |
import math
class Curriculum:
def __init__(self, args):
# args.dims and args.points each contain start, end, inc, interval attributes
# inc denotes the change in n_dims,
# this change is done every interval,
# and start/end are the limits of the parameter
self.n_dims_trunca... | TART-main | src/reasoning_module/curriculum.py |
import torch
from torch.nn import CrossEntropyLoss
from transformers import AutoTokenizer
from typing import List
def squared_error(ys_pred, ys):
return (ys - ys_pred).square()
def mean_squared_error(ys_pred, ys):
return (ys - ys_pred).square().mean()
def accuracy(ys_pred, ys):
return (ys == ys_pred.s... | TART-main | src/reasoning_module/tasks.py |
import numpy as np
import torch
import torch.nn as nn
from tqdm import tqdm
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
GPT2Config,
GPT2Model,
GPTNeoForCausalLM,
)
def build_model(conf):
if conf.family == "gpt2":
model = TransformerModel(
n_dims=conf.n_d... | TART-main | src/reasoning_module/models.py |
TART-main | src/reasoning_module/__init__.py | |
import os
from random import randint
import uuid
from quinine import QuinineArgumentParser
from tqdm import tqdm
import torch
import yaml
from tasks import get_task_sampler
from samplers import get_data_sampler
from curriculum import Curriculum
from schema import schema
from models import build_model
import wandb
... | TART-main | src/reasoning_module/train.py |
import math
import numpy as np
import torch
class DataSampler:
def __init__(self, n_dims: int):
self.n_dims = n_dims
def sample_xs(self):
raise NotImplementedError
def get_data_sampler(data_name: str, n_dims: int, **kwargs):
names_to_classes = {
"gaussian": GaussianSampler,
... | TART-main | src/reasoning_module/samplers.py |
from quinine import (
tstring,
tinteger,
tfloat,
tboolean,
stdict,
tdict,
default,
required,
allowed,
nullable,
)
from funcy import merge
model_schema = {
"family": merge(tstring, allowed(["gpt2", "gpt-neo"])),
"n_positions": merge(tinteger, required), # maximum contex... | TART-main | src/reasoning_module/schema.py |
import sklearn.metrics as metrics
import pandas as pd
import torch
from sklearn.metrics import confusion_matrix
from typing import List, Dict
import numpy as np
from matplotlib import pyplot as plt
import argparse
import os
from typing import Tuple
import pickle
def compute_accuracy(data: Dict) -> torch.Tensor:
e... | TART-main | src/eval/compute_accuracy.py |
import numpy as np
import torch
import torch.nn as nn
from tqdm import tqdm
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
GPT2Config,
GPT2Model,
GPTNeoForCausalLM,
)
def build_model(conf):
if conf.family == "gpt2":
model = TransformerModel(
n_dims=conf.n_d... | TART-main | src/eval/models.py |
import torch
from torch import nn
class NeuralNetwork(nn.Module):
def __init__(self, in_size=50, hidden_size=1000, out_size=1):
super(NeuralNetwork, self).__init__()
self.net = nn.Sequential(
nn.Linear(in_size, hidden_size),
nn.ReLU(),
nn.Linear(hidden_size, ou... | TART-main | src/eval/base_models.py |
import argparse
import logging
import os
import pickle
import warnings
from typing import List
import torch
from eval_utils import generate_in_context_example, get_template, load_data, load_model
from tokenizers import Tokenizer
from tqdm import tqdm
logging.getLogger("transformers").setLevel(logging.CRITICAL)
warn... | TART-main | src/eval/eval_base.py |
TART-main | src/eval/__init__.py | |
import argparse
import logging
import os
import pickle
import sys
import warnings
from typing import List
import torch
from eval_utils import load_data, load_model
from models import TransformerModel
from tqdm import tqdm
from transformers import AutoModelForCausalLM, AutoTokenizer
sys.path.append(f"{os.path.dirname(... | TART-main | src/eval/eval_text.py |
from datasets import load_dataset
from sklearn.model_selection import train_test_split
import os
import pandas as pd
from abc import ABC, abstractmethod
def prep_train_split(train_df, total_train_samples, seed, k_range=None):
# sample a class balanced set of train samples from train_df
my_list = train_df["la... | TART-main | src/eval/data_utils.py |
import random
import numpy as np
import torch
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from tqdm import tqdm
from models import TransformerModel
sigmoid = torch.nn.Sigmoid()
from transformers.utils import logging
logging.s... | TART-main | src/eval/reasoning_utils.py |
import sklearn.metrics as metrics
import pandas as pd
import torch
from sklearn.metrics import confusion_matrix
from typing import List, Dict
import numpy as np
def compute_accuracy(data: Dict) -> torch.Tensor:
epoch_keys = sorted(list(data[list(data.keys())[0]].keys()))
seed_keys = sorted(list(data.keys())... | TART-main | src/eval/metrics_utils.py |
import os
import numpy as np
import pandas as pd
import torch
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
from datasets import load_dataset
def load_model(model_name, path_to_finetuned_model=None, cache_dir=None):
config = AutoConfig.from_pretrained(model_name)
tokenizer = AutoTo... | TART-main | src/eval/eval_utils.py |
import argparse
import logging
import os
import pickle
import sys
import warnings
from typing import List
import torch
from eval_utils import load_data_mm, load_model
from models import TransformerModel
sys.path.append(f"{os.path.dirname(os.getcwd())}/src")
from tokenizers import Tokenizer
from tqdm import tqdm
from... | TART-main | src/eval/eval_speech_image.py |
import os
import sys
from datasets import concatenate_datasets, load_dataset
sys.path.append(f"{os.path.dirname(os.getcwd())}/")
from abc import ABC, abstractmethod
import pandas as pd
from sklearn.model_selection import train_test_split
from typing import List
class TartDataset(ABC):
_domain: str
_hf_da... | TART-main | src/tart/tart_datasets.py |
import random
import numpy as np
import torch
import sys
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from tqdm import tqdm
sys.path.append("../")
from reasoning_module.models import TransformerModel
sigmoid = torch.nn.Sigmoid()
from transformers.utils import logging
... | TART-main | src/tart/embed_utils.py |
import random
import numpy as np
import torch
from .embed_utils import (
get_embeds_vanilla,
get_embeds_loo,
get_embeds_stream,
get_embeds_stream_audio,
get_embeds_stream_image,
)
from .tart_modules import TartEmbeddingLayerAC
from tqdm import tqdm
from transformers import (
AutoFeatureExtrac... | TART-main | src/tart/embed_layers.py |
from .embed_layers import (
LOOEmbeddingCausalLM,
VanillaEmbeddingCausalLM,
StreamEmbeddingCausalLM,
StreamEmbeddingWhisper,
StreamEmbeddingViT,
)
from .tart_datasets import (
HateSpeech,
SpeechCommands,
SMSSpam,
MNIST,
AGNews,
DBPedia14,
CIFAR10,
YelpPolarity,
)
#... | TART-main | src/tart/registry.py |
TART-main | src/tart/__init__.py | |
from reasoning_module.models import TransformerModel
import torch
from tqdm import tqdm
from typing import List, Dict, Tuple
import numpy as np
from sklearn.decomposition import PCA
from abc import ABC, abstractmethod
class TartReasoningHead:
def __init__(
self,
n_dims: int,
n_positions:... | TART-main | src/tart/tart_modules.py |
TreeStructure-master | table-extraction/__init__.py | |
'''
Created on Oct 14, 2016
@author: xiao
'''
from parse import process_pdf, parse_args
from argparse import Namespace
from pdfminer.layout import LTTextLine
import codecs
import csv
import os
extractions = []
def get_gold_dict(filename, doc_on=True, part_on=True, val_on=True, attrib=None, docs=None):
with codec... | TreeStructure-master | table-extraction/experiment.py |
'''
Created on Oct 11, 2015
@author: xiao
'''
import os
from sys import platform as _platform
import numpy as np
from PIL import ImageFont, Image, ImageDraw
from pdf.vector_utils import center
from pdfminer.layout import LTAnno
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (... | TreeStructure-master | table-extraction/img_utils.py |
'''
Created on Jan 25, 2016
@author: xiao
'''
from vector_utils import *
import collections
from pdfminer.layout import LTTextLine, LTChar, LTAnno, LTCurve, LTComponent, LTLine
from itertools import chain
import numpy as np
def traverse_layout(root, callback):
'''
Tree walker and invokes the callback as it
... | TreeStructure-master | table-extraction/pdf/layout_utils.py |
'''
Created on Dec 2, 2015
@author: xiao
'''
import numpy as np
import bisect
from pdfminer.utils import Plane
import pandas as pd
from pdf.vector_utils import inside, reading_order
from pdf.layout_utils import project_onto
from collections import defaultdict
from pprint import pprint
class Cell(object):
'''Repre... | TreeStructure-master | table-extraction/pdf/grid.py |
'''
Handles abstract rendering of the layout
in order to extract local visual features
Created on Jan 28, 2016
@author: xiao
'''
import numpy as np
from vector_utils import *
class Renderer(object):
'''
enumeration objects to be placed into the
rendered image
'''
empty = 0
horizontal_line = -... | TreeStructure-master | table-extraction/pdf/render.py |
'''
Created on Oct 12, 2015
Various routines to work with pdf objects
extracted with PDFminer
@author: xiao
'''
import re
import string
import traceback
from collections import Counter
from img_utils import *
from pdf.vector_utils import *
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import L... | TreeStructure-master | table-extraction/pdf/pdf_utils.py |
'''
Created on Oct 26, 2015
Parsing raw PDF data into python data structures
@author: xiao
'''
from collections import defaultdict
from pdfminer.utils import Plane
from layout_utils import *
from node import Node
def parse_layout(elems, font_stat, combine=False):
'''
Parses pdf texts into a hypergraph grou... | TreeStructure-master | table-extraction/pdf/pdf_parsers.py |
TreeStructure-master | table-extraction/pdf/__init__.py | |
'''
Created on Oct 21, 2015
@author: xiao
'''
from collections import namedtuple
from itertools import izip
import numpy as np
# bbox indices
x0 = 0
y0 = 1
x1 = 2
y1 = 3
class Segment(namedtuple('Segment', ['e','vector'])):
__slots__ = ()
@property
def length(self):
return self.vector[x0] if se... | TreeStructure-master | table-extraction/pdf/vector_utils.py |
'''
Created on Jun 10, 2016
@author: xiao
'''
import numbers
from collections import Counter
from pdf.grid import Grid
from pdf.layout_utils import is_vline, is_same_row
from pdf.vector_utils import bound_elems, bound_bboxes
from pdfminer.layout import LTLine, LTTextLine, LTCurve, LTFigure, LTComponent
def elem_typ... | TreeStructure-master | table-extraction/pdf/node.py |
TOLERANCE = 5
def reorder_lines(lines, tol=TOLERANCE):
"""
Changes the line coordinates to be given as (top, left, bottom, right)
:param lines: list of lines coordinates
:return: reordered list of lines coordinates
"""
reordered_lines = []
for line in lines:
# we divide by tol and ... | TreeStructure-master | table-extraction/utils/lines_utils.py |
import numpy as np
from wand.color import Color
from wand.display import display
from wand.drawing import Drawing
from wand.image import Image
def display_bounding_boxes(img, blocks, alternatecolors=False, color=Color('blue')):
"""
Displays each of the bounding boxes passed in 'boxes' on an image of the pdf
... | TreeStructure-master | table-extraction/utils/display_utils.py |
TreeStructure-master | table-extraction/utils/__init__.py | |
TOLERANCE = 5
def doOverlap(bbox1, bbox2):
"""
:param bbox1: bounding box of the first rectangle
:param bbox2: bounding box of the second rectangle
:return: 1 if the two rectangles overlap
"""
if bbox1[2] < bbox2[0] or bbox2[2] < bbox1[0]:
return False
if bbox1[3] < bbox2[1] or bbo... | TreeStructure-master | table-extraction/utils/bbox_utils.py |
#!/usr/bin/env python
import zlib
from lzw import lzwdecode
from ascii85 import ascii85decode, asciihexdecode
from runlength import rldecode
from ccitt import ccittfaxdecode
from psparser import PSException, PSObject
from psparser import LIT, STRICT
from utils import apply_png_predictor, isnumber
LITERAL_CRYPT = LIT('... | TreeStructure-master | table-extraction/pdfminer/pdftypes.py |
#!/usr/bin/env python
import sys
import re
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from cmapdb import CMapDB, CMap
from psparser import PSTypeError, PSEOF
from psparser import PSKeyword, literal_name, keyword_name
from psparser import PSStackParser
from psparser imp... | TreeStructure-master | table-extraction/pdfminer/pdfinterp.py |
#!/usr/bin/env python
import sys
from psparser import LIT
from pdftypes import PDFObjectNotFound
from pdftypes import resolve1
from pdftypes import int_value, list_value, dict_value
from pdfparser import PDFParser
from pdfdocument import PDFDocument
from pdfdocument import PDFEncryptionError
from pdfdocument import PDF... | TreeStructure-master | table-extraction/pdfminer/pdfpage.py |
#!/usr/bin/env python
import sys
import struct
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from cmapdb import CMapDB, CMapParser, FileUnicodeMap, CMap
from encodingdb import EncodingDB, name2unicode
from psparser import PSStackParser
from psparser import PSEOF
from pspa... | TreeStructure-master | table-extraction/pdfminer/pdffont.py |
#!/usr/bin/env python
import sys
import re
from utils import choplist
STRICT = 0
## PS Exceptions
##
class PSException(Exception):
pass
class PSEOF(PSException):
pass
class PSSyntaxError(PSException):
pass
class PSTypeError(PSException):
pass
class PSValueError(PSException):
pass
## B... | TreeStructure-master | table-extraction/pdfminer/psparser.py |
#!/usr/bin/env python
from utils import INF, Plane, get_bound, uniq, csort, fsplit
from utils import bbox2str, matrix2str, apply_matrix_pt, is_diagonal
## IndexAssigner
##
class IndexAssigner(object):
def __init__(self, index=0):
self.index = index
return
def run(self, obj):
if isin... | TreeStructure-master | table-extraction/pdfminer/layout.py |
#!/usr/bin/env python
import sys
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from psparser import PSStackParser
from psparser import PSSyntaxError, PSEOF
from psparser import KWD, STRICT
from pdftypes import PDFException
from pdftypes import PDFStream, PDFObjRef
from pd... | TreeStructure-master | table-extraction/pdfminer/pdfparser.py |
#!/usr/bin/env python
# CCITT Fax decoder
#
# Bugs: uncompressed mode untested.
#
# cf.
# ITU-T Recommendation T.4
# "Standardization of Group 3 facsimile terminals for document transmission"
# ITU-T Recommendation T.6
# "FACSIMILE CODING SCHEMES AND CODING CONTROL FUNCTIONS FOR GROUP 4 FACSIMILE APPARATUS... | TreeStructure-master | table-extraction/pdfminer/ccitt.py |
#!/usr/bin/env python
from psparser import LIT
## PDFColorSpace
##
LITERAL_DEVICE_GRAY = LIT('DeviceGray')
LITERAL_DEVICE_RGB = LIT('DeviceRGB')
LITERAL_DEVICE_CMYK = LIT('DeviceCMYK')
class PDFColorSpace(object):
def __init__(self, name, ncomponents):
self.name = name
self.ncomponents = ncomp... | TreeStructure-master | table-extraction/pdfminer/pdfcolor.py |
#!/usr/bin/env python
""" Python implementation of Rijndael encryption algorithm.
This code is in the public domain.
This code is based on a public domain C implementation
by Philip J. Erdelsky:
http://www.efgh.com/software/rijndael.htm
"""
import struct
def KEYLENGTH(keybits):
return (keybits)//8
def RK... | TreeStructure-master | table-extraction/pdfminer/rijndael.py |
#!/usr/bin/env python
import sys
from pdfdevice import PDFTextDevice
from pdffont import PDFUnicodeNotDefined
from layout import LTContainer, LTPage, LTText, LTLine, LTRect, LTCurve
from layout import LTFigure, LTImage, LTChar, LTTextLine
from layout import LTTextBox, LTTextBoxVertical, LTTextGroup
from utils import ap... | TreeStructure-master | table-extraction/pdfminer/converter.py |
#!/usr/bin/env python
__version__ = '20151115'
if __name__ == '__main__':
print __version__
| TreeStructure-master | table-extraction/pdfminer/__init__.py |
#!/usr/bin/env python
""" Python implementation of Arcfour encryption algorithm.
This code is in the public domain.
"""
## Arcfour
##
class Arcfour(object):
"""
>>> Arcfour('Key').process('Plaintext').encode('hex')
'bbf316e8d940af0ad3'
>>> Arcfour('Wiki').process('pedia').encode('hex')
'1021b... | TreeStructure-master | table-extraction/pdfminer/arcfour.py |
#!/usr/bin/env python
""" Adobe character mapping (CMap) support.
CMaps provide the mapping between character codes and Unicode
code-points to character ids (CIDs).
More information is available on the Adobe website:
http://opensource.adobe.com/wiki/display/cmap/CMap+Resources
"""
import sys
import os
import os... | TreeStructure-master | table-extraction/pdfminer/cmapdb.py |
#!/usr/bin/env python
from utils import mult_matrix, translate_matrix
from utils import enc, bbox2str, isnumber
from pdffont import PDFUnicodeNotDefined
## PDFDevice
##
class PDFDevice(object):
debug = 0
def __init__(self, rsrcmgr):
self.rsrcmgr = rsrcmgr
self.ctm = None
return
... | TreeStructure-master | table-extraction/pdfminer/pdfdevice.py |
#!/usr/bin/env python
""" Font metrics for the Adobe core 14 fonts.
Font metrics are used to compute the boundary of each character
written with a proportional font.
The following data were extracted from the AFM files:
http://www.ctan.org/tex-archive/fonts/adobe/afm/
"""
### BEGIN Verbatim copy of the license... | TreeStructure-master | table-extraction/pdfminer/fontmetrics.py |
#!/usr/bin/env python
import sys
import re
import struct
try:
import hashlib as md5
except ImportError:
import md5
from psparser import PSEOF
from psparser import literal_name
from psparser import LIT, KWD, STRICT
from pdftypes import PDFException, PDFTypeError, PDFNotImplementedError
from pdftypes import PDFOb... | TreeStructure-master | table-extraction/pdfminer/pdfdocument.py |
#!/usr/bin/env python
"""
Miscellaneous Routines.
"""
import struct
from sys import maxint as INF
## PNG Predictor
##
def apply_png_predictor(pred, colors, columns, bitspercomponent, data):
if bitspercomponent != 8:
# unsupported
raise ValueError(bitspercomponent)
nbytes = colors*columns*bits... | TreeStructure-master | table-extraction/pdfminer/utils.py |
#!/usr/bin/env python
""" Mappings from Adobe glyph names to Unicode characters.
In some CMap tables, Adobe glyph names are used for specifying
Unicode characters instead of using decimal/hex character code.
The following data was taken by
$ wget http://www.adobe.com/devnet/opentype/archives/glyphlist.txt
$ pyt... | TreeStructure-master | table-extraction/pdfminer/glyphlist.py |
#!/usr/bin/env python
import sys
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
class CorruptDataError(Exception):
pass
## LZWDecoder
##
class LZWDecoder(object):
debug = 0
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.b... | TreeStructure-master | table-extraction/pdfminer/lzw.py |
#!/usr/bin/env python
#
# RunLength decoder (Adobe version) implementation based on PDF Reference
# version 1.4 section 3.3.4.
#
# * public domain *
#
def rldecode(data):
"""
RunLength decoder (Adobe version) implementation based on PDF Reference
version 1.4 section 3.3.4:
The RunLengthDecode filt... | TreeStructure-master | table-extraction/pdfminer/runlength.py |
#!/usr/bin/env python
""" Python implementation of ASCII85/ASCIIHex decoder (Adobe version).
This code is in the public domain.
"""
import re
import struct
# ascii85decode(data)
def ascii85decode(data):
"""
In ASCII85 encoding, every four bytes are encoded with five ASCII
letters, using 85 different t... | TreeStructure-master | table-extraction/pdfminer/ascii85.py |
#!/usr/bin/env python
import re
from psparser import PSLiteral
from glyphlist import glyphname2unicode
from latin_enc import ENCODING
STRIP_NAME = re.compile(r'[0-9]+')
## name2unicode
##
def name2unicode(name):
"""Converts Adobe glyph names to Unicode numbers."""
if name in glyphname2unicode:
ret... | TreeStructure-master | table-extraction/pdfminer/encodingdb.py |
#!/usr/bin/env python
""" Standard encoding tables used in PDF.
This table is extracted from PDF Reference Manual 1.6, pp.925
"D.1 Latin Character Set and Encodings"
"""
ENCODING = [
# (name, std, mac, win, pdf)
('A', 65, 65, 65, 65),
('AE', 225, 174, 198, 198),
('Aacute', None, 231, 193, 193),
('Acircu... | TreeStructure-master | table-extraction/pdfminer/latin_enc.py |
#!/usr/bin/env python
import cStringIO
import struct
import os, os.path
from pdftypes import LITERALS_DCT_DECODE
from pdfcolor import LITERAL_DEVICE_GRAY, LITERAL_DEVICE_RGB, LITERAL_DEVICE_CMYK
def align32(x):
return ((x+3)//4)*4
## BMPWriter
##
class BMPWriter(object):
def __init__(self, fp, bits, width... | TreeStructure-master | table-extraction/pdfminer/image.py |
TreeStructure-master | table-extraction/ml/__init__.py | |
import string
from pdf.pdf_parsers import *
from pdf.vector_utils import *
from utils.bbox_utils import isContained
# ******************* Table Coverage Features *************************************
def get_area_coverage(bbox):
b = bbox[-4:]
return ((b[2] - b[0]) * (b[3] - b[1])) / float(bbox[1] * bbox[2]... | TreeStructure-master | table-extraction/ml/features.py |
import argparse
import os
import pickle
import sys
import numpy as np
from ml.TableExtractML import TableExtractorML
from sklearn import linear_model, preprocessing, metrics
from utils.bbox_utils import doOverlap, compute_iou, isContained
def get_bboxes_from_line(line):
if line == "NO_TABLES":
return {}
... | TreeStructure-master | table-extraction/ml/extract_tables.py |
import numpy as np
from utils.bbox_utils import get_rectangles, compute_iou
from utils.lines_utils import reorder_lines, get_vertical_and_horizontal, extend_vertical_lines, \
merge_vertical_lines, merge_horizontal_lines, extend_horizontal_lines
from pdf.pdf_parsers import parse_layout
from pdf.pdf_utils import nor... | TreeStructure-master | table-extraction/ml/TableExtractML.py |
import argparse
import os
import numpy as np
from pdf.pdf_utils import normalize_pdf, analyze_pages
from utils.display_utils import display_bounding_boxes, pdf_to_img
from utils.bbox_utils import isContained
from wand.color import Color
DISPLAY_RESULTS = False
def get_words_in_bounding_boxes(extracted_bboxes, gt_b... | TreeStructure-master | table-extraction/evaluation/char_level_evaluation.py |
TreeStructure-master | table-extraction/evaluation/__init__.py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch
import datetime
import logging
import math
import time
import sys
from torch.distributed.distributed_c10d import reduce
from utils.ap_calculator import APCalculator
from utils.misc import SmoothedValue
from utils.dist import (
all_gather_dict,
all... | 3detr-main | engine.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch
def build_optimizer(args, model):
params_with_decay = []
params_without_decay = []
for name, param in model.named_parameters():
if param.requires_grad is False:
continue
if args.filter_biases_wd and (len(param.sha... | 3detr-main | optimizer.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from utils.box_util import generalized_box3d_iou
from utils.dist import all_reduce_average
from utils.misc import huber_loss
from scipy.optimize import linear_sum_assignment
class M... | 3detr-main | criterion.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import argparse
import os
import sys
import pickle
import numpy as np
import torch
from torch.multiprocessing import set_start_method
from torch.utils.data import DataLoader, DistributedSampler
# 3DETR codebase specific imports
from datasets import build_dataset
fro... | 3detr-main | main.py |
# Copyright (c) Facebook, Inc. and its affiliates.
"""
Modified from https://github.com/facebookresearch/votenet
Dataset for 3D object detection on SUN RGB-D (with support of vote supervision).
A sunrgbd oriented bounding box is parameterized by (cx,cy,cz), (l,w,h) -- (dx,dy,dz) in upright depth coord
(Z is up, Y i... | 3detr-main | datasets/sunrgbd.py |
# Copyright (c) Facebook, Inc. and its affiliates.
from .scannet import ScannetDetectionDataset, ScannetDatasetConfig
from .sunrgbd import SunrgbdDetectionDataset, SunrgbdDatasetConfig
DATASET_FUNCTIONS = {
"scannet": [ScannetDetectionDataset, ScannetDatasetConfig],
"sunrgbd": [SunrgbdDetectionDataset, Sunrgb... | 3detr-main | datasets/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
"""
Modified from https://github.com/facebookresearch/votenet
Dataset for object bounding box regression.
An axis aligned bounding box is parameterized by (cx,cy,cz) and (dx,dy,dz)
where (cx,cy,cz) is the center point of the box, dx is the x-axis length of the box.
"... | 3detr-main | datasets/scannet.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch
import numpy as np
from collections import deque
from typing import List
from utils.dist import is_distributed, barrier, all_reduce_sum
def my_worker_init_fn(worker_id):
np.random.seed(np.random.get_state()[1][0] + worker_id)
@torch.jit.ignore
def ... | 3detr-main | utils/misc.py |
# Copyright (c) Facebook, Inc. and its affiliates.
from setuptools import setup, Extension
from Cython.Build import cythonize
import numpy as np
# hacky way to find numpy include path
# replace with actual path if this does not work
np_include_path = np.__file__.replace("__init__.py", "core/include/")
INCLUDE_PATH =... | 3detr-main | utils/cython_compile.py |
# Copyright (c) Facebook, Inc. and its affiliates.
""" Generic Code for Object Detection Evaluation
Input:
For each class:
For each image:
Predictions: box, score
Groundtruths: box
Output:
For each class:
precision-recal and average precision
Autho... | 3detr-main | utils/eval_det.py |
# Copyright (c) Facebook, Inc. and its affiliates.
""" Utility functions for processing point clouds.
Author: Charles R. Qi and Or Litany
"""
import os
import sys
import torch
# Point cloud IO
import numpy as np
from plyfile import PlyData, PlyElement
# Mesh IO
import trimesh
# -----------------------------------... | 3detr-main | utils/pc_util.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch
import os
from utils.dist import is_primary
def save_checkpoint(
checkpoint_dir,
model_no_ddp,
optimizer,
epoch,
args,
best_val_metrics,
filename=None,
):
if not is_primary():
return
if filename is None:
... | 3detr-main | utils/io.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import os
from urllib import request
import torch
import pickle
## Define the weights you want and where to store them
dataset = "scannet"
encoder = "_masked" # or ""
epoch = 1080
base_url = "https://dl.fbaipublicfiles.com/3detr/checkpoints"
local_dir = "/tmp/"
###... | 3detr-main | utils/download_weights.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
# boxes are axis aigned 2D boxes of shape (n,5) in FLOAT numbers with (x1,y1,x2,y2,score)
""" Ref: https://www.pyimagesearch.com/2015/02/16/faster-non-maximum-suppression-python/
Ref: https://github.com/vickyboy47/nms-python/blob/master/nms.py
"""... | 3detr-main | utils/nms.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch
try:
from tensorboardX import SummaryWriter
except ImportError:
print("Cannot import tensorboard. Will log to txt files only.")
SummaryWriter = None
from utils.dist import is_primary
class Logger(object):
def __init__(self, log_dir=Non... | 3detr-main | utils/logger.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
def check_aspect(crop_range, aspect_min):
xy_aspect = np.min(crop_range[:2]) / np.max(crop_range[:2])
xz_aspect = np.min(crop_range[[0, 2]]) / np.max(crop_range[[0, 2]])
yz_aspect = np.min(crop_range[1:]) / np.max(crop_range[1:])
re... | 3detr-main | utils/random_cuboid.py |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Utilities for bounding box manipulation and GIoU.
"""
import torch
from torchvision.ops.boxes import box_area
from typing import List
try:
from box_intersection import batch_intersect
except ImportError:
print("Could not import cythonize... | 3detr-main | utils/box_ops3d.py |
# Copyright (c) Facebook, Inc. and its affiliates.
""" Helper functions for calculating 2D and 3D bounding box IoU.
Collected and written by Charles R. Qi
Last modified: Apr 2021 by Ishan Misra
"""
import torch
import numpy as np
from scipy.spatial import ConvexHull, Delaunay
from utils.misc import to_list_1d, to_lis... | 3detr-main | utils/box_util.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
""" Helper functions and class to calculate Average Precisions for 3D object detection.
"""
import logging
import os
import sys
from collectio... | 3detr-main | utils/ap_calculator.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import pickle
import torch
import torch.distributed as dist
def is_distributed():
if not dist.is_available() or not dist.is_initialized():
return False
return True
def get_rank():
if not is_distributed():
return 0
return dist.get_ra... | 3detr-main | utils/dist.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import math
from functools import partial
import numpy as np
import torch
import torch.nn as nn
from third_party.pointnet2.pointnet2_modules import PointnetSAModuleVotes
from third_party.pointnet2.pointnet2_utils import furthest_point_sample
from utils.pc_util import ... | 3detr-main | models/model_3detr.py |
# Copyright (c) Facebook, Inc. and its affiliates.
from .model_3detr import build_3detr
MODEL_FUNCS = {
"3detr": build_3detr,
}
def build_model(args, dataset_config):
model, processor = MODEL_FUNCS[args.model_name](args, dataset_config)
return model, processor | 3detr-main | models/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Modified from DETR Transformer class.
Copy-paste from torch.nn.Transformer with modifications:
* positional encodings are passed in MHattention
* extra LN at the end of encoder is removed
* decoder returns a stack of activations fro... | 3detr-main | models/transformer.py |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Various positional encodings for the transformer.
"""
import math
import torch
from torch import nn
import numpy as np
from utils.pc_util import shift_scale_points
class PositionEmbeddingCoordsSine(nn.Module):
def __init__(
self,
... | 3detr-main | models/position_embedding.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch.nn as nn
from functools import partial
import copy
class BatchNormDim1Swap(nn.BatchNorm1d):
"""
Used for nn.Transformer that uses a HW x N x C rep
"""
def forward(self, x):
"""
x: HW x N x C
permute to N x C x HW
... | 3detr-main | models/helpers.py |
# Copyright (c) Facebook, Inc. and its affiliates.
''' Modified based on Ref: https://github.com/erikwijmans/Pointnet2_PyTorch '''
import torch
import torch.nn as nn
from typing import List, Tuple
class SharedMLP(nn.Sequential):
def __init__(
self,
args: List[int],
*,
... | 3detr-main | third_party/pointnet2/pytorch_utils.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
import glob
import os.path as osp
this_dir ... | 3detr-main | third_party/pointnet2/setup.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.