python_code
stringlengths
0
4.04M
repo_name
stringlengths
7
58
file_path
stringlengths
5
147
"""Type symbols class.""" import copy import os from typing import Dict, List, Optional, Set, Union from tqdm.auto import tqdm from bootleg.symbols.constants import edit_op from bootleg.utils import utils from bootleg.utils.classes.nested_vocab_tries import TwoLayerVocabularyScoreTrie def _convert_to_trie(qid2type...
bootleg-master
bootleg/symbols/type_symbols.py
"""Constants.""" import logging import os from distutils.util import strtobool from functools import wraps from bootleg import log_rank_0_info logger = logging.getLogger(__name__) USE_STRIP = strtobool(os.environ.get("BOOTLEG_STRIP", "true")) USE_LOWER = strtobool(os.environ.get("BOOTLEG_LOWER", "true")) LANG_CODE ...
bootleg-master
bootleg/symbols/constants.py
"""Symbols init."""
bootleg-master
bootleg/symbols/__init__.py
"""Entity symbols.""" import copy import logging import os from typing import Callable, Dict, Optional, Union from tqdm.auto import tqdm import bootleg.utils.utils as utils from bootleg.symbols.constants import edit_op from bootleg.utils.classes.nested_vocab_tries import ( TwoLayerVocabularyScoreTrie, Vocabul...
bootleg-master
bootleg/symbols/entity_symbols.py
"""Bootleg slice dataset.""" import hashlib import logging import multiprocessing import os import shutil import time import traceback from collections import defaultdict import numpy as np import ujson from tqdm.auto import tqdm from bootleg import log_rank_0_debug, log_rank_0_info from bootleg.symbols.constants imp...
bootleg-master
bootleg/slicing/slice_dataset.py
"""Slicing initializer."""
bootleg-master
bootleg/slicing/__init__.py
import re import tempfile from pathlib import Path from subprocess import call import argh from rich.console import Console from bootleg.utils.utils import load_yaml_file console = Console(soft_wrap=True) bert_dir = tempfile.TemporaryDirectory().name checkpoint_regex = re.compile(r"checkpoint_(\d+\.{0,1}\d*).model....
bootleg-master
configs/gcp/launch_gcp.py
import os import jsonlines import numpy as np import pandas as pd import requests import tagme import ujson from tqdm.auto import tqdm from bootleg.symbols.entity_profile import EntityProfile pd.options.display.max_colwidth = 500 def load_train_data(train_file, title_map, entity_profile=None): """Loads a jsonl...
bootleg-master
tutorials/utils.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import argparse from monodepth.depth_model_registry import get_depth_model, get_depth_model_list from depth_fine_tuning import DepthFineTuningParams from scale_calibration import ScaleCalibrationParams from utils import frame_sampling, frame_r...
consistent_depth-main
params.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import cv2 import numpy as np import os from os.path import join as pjoin import logging from typing import Optional, Set import torch from utils.helpers import SuppressedStdout from loaders.video_dataset import _dtype, load_color from tools.c...
consistent_depth-main
scale_calibration.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import argparse import copy import cv2 import numpy as np import os import torch from third_party.flownet2.models import FlowNet2 from third_party.OpticalFlowToolkit.lib.flowlib import flow_to_image from utils.image_io import save_raw_float32_i...
consistent_depth-main
optical_flow_flownet2_homography.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import cv2 import itertools import json import math import os from os.path import join as pjoin import time import torch from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter import torchvision.utils as vutils...
consistent_depth-main
depth_fine_tuning.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import cv2 import json import numpy as np import os from os.path import join as pjoin import torch from third_party.OpticalFlowToolkit.lib import flowlib from utils.url_helpers import get_model_from_url import optical_flow_flownet2_homography...
consistent_depth-main
flow.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import logging import os from os.path import join as pjoin import shutil from depth_fine_tuning import DepthFineTuner from flow import Flow from scale_calibration import calibrate_scale from tools import make_video as mkvid from utils.frame_ran...
consistent_depth-main
process.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. from params import Video3dParamsParser from process import DatasetProcessor if __name__ == "__main__": parser = Video3dParamsParser() params = parser.parse() dp = DatasetProcessor() dp.process(params)
consistent_depth-main
main.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import cv2 import logging import os from os.path import join as pjoin import sys import tempfile from utils import (frame_sampling, image_io) from utils.helpers import mkdir_ifnotexists ffmpeg = "ffmpeg" ffprobe = "ffprobe" def sample_pairs(...
consistent_depth-main
video.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import argparse import logging import sys import os from os.path import join as pjoin import shutil import subprocess from typing import Tuple, Optional, List import cv2 LOG = logging.getLogger() LOG.setLevel("INFO") formatter = logging.Forma...
consistent_depth-main
tools/make_video.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import argparse import logging import os from os.path import join as pjoin import subprocess import sys import numpy as np class COLMAPParams: def __init__(self): self.parser = argparse.ArgumentParser() self.parser.add_arg...
consistent_depth-main
tools/colmap_processor.py
#!/usr/bin/env python3 from torch.optim.optimizer import Optimizer from torch.optim import Adam OPTIMIZER_MAP = { "Adam": Adam, } OPTIMIZER_NAMES = OPTIMIZER_MAP.keys() OPTIMIZER_CLASSES = OPTIMIZER_MAP.values() def create(optimizer_name: str, *args, **kwargs) -> Optimizer: return OPTIMIZER_MAP[optimizer...
consistent_depth-main
optimizer/__init__.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import torch import torch.nn as nn from utils.torch_helpers import _device from utils.geometry import ( pixel_grid, focal_length, project, pixels_to_points, reproject_points, sample, ) def select_tensors(x): """ ...
consistent_depth-main
loss/consistency_loss.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. class LossParams: """ Loss related parameters """ @staticmethod def add_arguments(parser): parser.add_argument( "--lambda_view_baseline", type=float, default=-1, help=...
consistent_depth-main
loss/loss_params.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import torch class ParameterLoss(torch.nn.Module): def __init__(self, parameters_init, opt): self.parameters_init = parameters_init self.opt = opt assert opt.lambda_parameter > 0 def __call__(self, parameters):...
consistent_depth-main
loss/parameter_loss.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. from typing import List, Optional import torch from torch.nn import Parameter from .parameter_loss import ParameterLoss from .consistency_loss import ConsistencyLoss from utils.torch_helpers import _device from loaders.video_dataset import _dt...
consistent_depth-main
loss/joint_loss.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. from collections import namedtuple from enum import Enum, unique, auto from typing import Iterable, NamedTuple, Dict, Any, Set import numpy as np from .frame_range import FrameRange @unique class SamplePairsMode(Enum): EXHAUSTED = 0 C...
consistent_depth-main
utils/frame_sampling.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. from typing import Set, Optional from collections import namedtuple # set is an OptionalSet as below NamedOptionalSet = namedtuple("NamedOptionalSet", ["name", "set"]) class OptionalSet: def __init__(self, set: Optional[Set] = None): ...
consistent_depth-main
utils/frame_range.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import argparse import numpy as np import os from PIL import Image import cv2 import struct from subprocess import call import warnings import six if six.PY2: class ResourceWarning(RuntimeWarning): pass # Needed to suppress Resou...
consistent_depth-main
utils/image_io.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np from third_party.colmap.scripts.python.read_write_model import ( CAMERA_MODELS, rotmat2qvec, Camera, BaseImage, write_mode...
consistent_depth-main
utils/load_colmap.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import numpy as np import torch.nn def sample(data, uv): """Sample data (H, W, <C>) by uv (H, W, 2) (in pixels). """ shape = data.shape # data from (H, W, <C>) to (1, C, H, W) data = data.reshape(data.shape[:2] + (-1,)) dat...
consistent_depth-main
utils/consistency.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import os from os.path import join as pjoin import wget from zipfile import ZipFile def get_model_from_url( url: str, local_path: str, is_zip: bool = False, path_root: str = "checkpoints" ) -> str: local_path = pjoin(path_root, local_p...
consistent_depth-main
utils/url_helpers.py
consistent_depth-main
utils/__init__.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import cv2 import numpy import os import subprocess import sys import logging from matplotlib.cm import get_cmap from . import image_io CM_MAGMA = (numpy.array([get_cmap('magma').colors]). transpose([1, 0, 2]) * 255)[..., ::-1].a...
consistent_depth-main
utils/visualization.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import numpy as np from typing import Tuple def reproject(pts3d: np.ndarray, extr: np.ndarray) -> np.ndarray: assert pts3d.shape[0] == extr.shape[0] and pts3d.shape[0] == 3 p_dim, _ = pts3d.shape R, t = extr[:, :p_dim], extr[:, -1:...
consistent_depth-main
utils/geometry_np.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import torch _device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") def to_device(data): if isinstance(data, torch.Tensor): data = data.to(_device, non_blocking=True) return data if isin...
consistent_depth-main
utils/torch_helpers.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import torch from .torch_helpers import _device from typing import List def pixel_grid(batch_size, shape): """Returns pixel grid of size (batch_size, 2, H, W). pixel positions (x, y) are in range [0, W-1] x [0, H-1] top left is (0,...
consistent_depth-main
utils/geometry.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import numpy as np from numpy.linalg import inv import cv2 from sklearn import linear_model def resize_small(gt, x, interp=cv2.INTER_NEAREST): """ Resize to match the smaller image. """ def size(x): return x.shape[:2][:...
consistent_depth-main
utils/calibrate.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import os import sys class dotdict(dict): """dot.notation access to dictionary attributes""" __getattr__ = dict.get __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ def mkdir_ifnotexists(dir): if os.path.exis...
consistent_depth-main
utils/helpers.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import os from os.path import join as pjoin from typing import Dict, Tuple import numpy as np from . import load_colmap, image_io as tr from .geometry_np import reproject, project, sample def store_visible_points_per_image( points3D: Dict[...
consistent_depth-main
utils/calibration.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import os import cv2 from os.path import join as pjoin import json import math import numpy as np import torch.utils.data as data import torch from typing import Optional from utils import image_io, frame_sampling as sampling _dtype = torch.f...
consistent_depth-main
loaders/video_dataset.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import torch from utils.url_helpers import get_model_from_url from .midas_v2.midas_net import MidasNet from .depth_model import DepthModel class MidasV2Model(DepthModel): # Requirements and default settings align = 32 learning_ra...
consistent_depth-main
monodepth/midas_v2_model.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import torch import torch.autograd as autograd from utils.helpers import SuppressedStdout from utils.url_helpers import get_model_from_url from .mannequin_challenge.models import pix2pix_model from .mannequin_challenge.options.train_options im...
consistent_depth-main
monodepth/mannequin_challenge_model.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. from os.path import join as pjoin import torch from utils.url_helpers import get_model_from_url from .depth_model import DepthModel from .monodepth2.networks.resnet_encoder import ResnetEncoder from .monodepth2.networks.depth_decoder import D...
consistent_depth-main
monodepth/monodepth2_model.py
consistent_depth-main
monodepth/__init__.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. from abc import abstractmethod import torch class DepthModel(torch.nn.Module): def __init__(self): super().__init__() def forward(self, images, metadata=None): """ Images should be feed in the format (N, C, H, ...
consistent_depth-main
monodepth/depth_model.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. from .depth_model import DepthModel from .mannequin_challenge_model import MannequinChallengeModel from .midas_v2_model import MidasV2Model from .monodepth2_model import Monodepth2Model from typing import List def get_depth_model_list() -> Li...
consistent_depth-main
monodepth/depth_model_registry.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os.path as osp import setuptools cur_dir = osp.dirname(osp.realpath(__file__)) requirementPath = osp.join(cur_di...
bc-irl-main
setup.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import os.path as osp from collections import defaultdict from typing import Dict, Optional import gym.spaces ...
bc-irl-main
imitation_learning/run.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree.
bc-irl-main
imitation_learning/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import hydra from omegaconf import OmegaConf from imitation_learning.run import main @hydra.main(config_path="config",...
bc-irl-main
imitation_learning/eval.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import itertools from collections import defaultdict from functools import partial import numpy as np import torch impor...
bc-irl-main
imitation_learning/gail/updater.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from enum import Enum, auto from typing import Tuple import torch import torch.nn as nn from rl_utils.common import make...
bc-irl-main
imitation_learning/gail/discriminator.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from functools import partial import numpy as np import torch import torch.nn as nn from rl_utils.models import (FixedCa...
bc-irl-main
imitation_learning/policy_opt/policy.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree.
bc-irl-main
imitation_learning/policy_opt/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from collections import defaultdict from typing import Dict, Optional import torch def _flatten_helper(T, N, _tensor):...
bc-irl-main
imitation_learning/policy_opt/storage.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Any, Dict import torch import torch.nn as nn from hydra.utils import instantiate as hydra_instantiate...
bc-irl-main
imitation_learning/policy_opt/ppo.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from higher.optim import DifferentiableOptimizer from hydra.utils import instantiate f...
bc-irl-main
imitation_learning/bc_irl/differentiable_ppo.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree.
bc-irl-main
imitation_learning/bc_irl/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Callable import higher import torch import torch.nn as nn from hydra.utils import call, instantiate f...
bc-irl-main
imitation_learning/bc_irl/updater.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from enum import Enum, auto import torch import torch.nn as nn from hydra.utils import instantiate from rl_utils.common ...
bc-irl-main
imitation_learning/bc_irl/rewards.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import itertools from collections import defaultdict import numpy as np import torch import torch.nn as nn import torch....
bc-irl-main
imitation_learning/f_irl/updater.py
bc-irl-main
imitation_learning/config/logger/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch import torch.nn as nn from hydra.utils import call, instantiate from omegaconf import Dic...
bc-irl-main
imitation_learning/maxent/updater.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Tuple import torch import torch.nn as nn from rl_utils.common import make_mlp_layers class AirlDisc...
bc-irl-main
imitation_learning/airl/discriminator.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from hydra.utils import call, instantiate from omegaconf import DictConfig from rl_uti...
bc-irl-main
imitation_learning/gcl/updater.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os.path as osp import matplotlib.pyplot as plt import matplotlib.ticker as ticker import numpy as np import seabo...
bc-irl-main
imitation_learning/common/pointmass_utils.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os.path as osp import matplotlib.pyplot as plt import numpy as np def plot_actions(pred_actions, gt_actions, n_...
bc-irl-main
imitation_learning/common/plotting.py
from enum import Enum, auto import torch import torch.nn as nn from rl_utils.common import make_mlp_layers class RewardInputType(Enum): ACTION = auto() NEXT_STATE = auto() CUR_NEXT_STATE = auto() class NeuralReward(nn.Module): def __init__( self, obs_shape, action_dim, ...
bc-irl-main
imitation_learning/common/net.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree.
bc-irl-main
imitation_learning/common/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Dict, List, Tuple import torch from rl_utils.common import DictDataset def log_finished_rewards( ...
bc-irl-main
imitation_learning/common/utils.py
from setuptools import setup, find_packages setup( name='treedlib', version='0.1.3', description='Library of tree features.', packages=find_packages(), install_requires=[ 'lxml', ], classifiers=[ "License :: OSI Approved :: MIT License", ], url='https://github.com/Ha...
treedlib-master
setup.py
from feature_template import * from itertools import chain def get_mention_templates(cid, d): """ Generate the DDLib mention features as per http://deepdive.stanford.edu/doc/basics/gen_feats.html """ return [ # The set of POS tags comprising the mention Indicator(Mention(cid), 'pos'), # The...
treedlib-master
archive/basic_features.py
from itertools import chain import re # op_0 : X -> p(T) # op_1 : p(T) -> p(T) # ind : p(T) -> {0,1}^F class FeatureTemplate: """Base feature template class""" def __init__(self): self.label = None self.xpaths = set(['//node']) self.subsets = None # subtrees / p(T) def apply(self, root): """ ...
treedlib-master
archive/feature_template.py
from collections import namedtuple import re import sys def print_gen(gen): """Print the results of a generator one-per-line""" for e in gen: print(e) def print_error(err_string): """Function to write to stderr""" sys.stderr.write("ERROR[UDF]: " + str(err_string) + "\n") BOOL_PARSER = { 't' : True, ...
treedlib-master
treedlib/util.py
import os # Set TREEDLIB_APP env var, for use in libs we load os.environ["TREEDLIB_LIB"] = os.path.dirname(os.path.realpath(__file__)) # Load treedlib libs from treedlib.util import * from treedlib.structs import * from treedlib.templates import * from treedlib.features import *
treedlib-master
treedlib/__init__.py
from treedlib.templates import * import lxml.etree as et def compile_relation_feature_generator(dictionaries=None, opts={}, is_multary=False): """ Given optional arguments, returns a generator function which accepts an xml root and two lists of mention indexes, and will generate relation features for this relati...
treedlib-master
treedlib/features.py
from itertools import chain import re import lxml.etree as et from collections import defaultdict # NODESET: # =========== class NodeSet: """ NodeSet objects are functions f : 2^T -> 2^T --------------- They are applied compositionally and lazily, by constructing an xpath query We use these to get the *sub...
treedlib-master
treedlib/templates.py
import json import os import re import lxml.etree as et import sys # This should be set by the lib wrapper __init__.py file APP_HOME = os.environ["TREEDLIB_LIB"] # Load IPython display functionality libs if possible i.e. if in IPython try: from IPython.core.display import display_html, HTML, display_javascript, Jav...
treedlib-master
treedlib/structs.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from distutils.core import setup setup( name="bela", version="0.1", packages=["bela"], )
BELA-main
setup.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # HACK: Need to import protobuf before pytorch_lightning to prevent Segmentation Fault: https://github.com/protocolbuffers/protobuf/issues/11...
BELA-main
bela/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import hydra from bela.conf.config import MainConfig from omegaconf import OmegaConf from pytorch_lightning.trainer import Trainer...
BELA-main
bela/main.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import logging import mmap from typing import List, Optional import torch from pytorch_lightning import LightningDataModule fro...
BELA-main
bela/datamodule/joint_el_datamodule.py
BELA-main
bela/tests/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest import os import torch import torch from bela.transforms.joint_el_transform import JointELTransform from bela.datamodule.joi...
BELA-main
bela/tests/test_datamodules.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest import torch from bela.models.hf_encoder import HFEncoder from bela.transforms.joint_el_transform import JointELTransform c...
BELA-main
bela/tests/test_models.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest import torch from bela.transforms.joint_el_transform import JointELTransform, JointELXlmrRawTextTransform class TestJointE...
BELA-main
bela/tests/test_transforms.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from collections import defaultdict from functools import lru_cache from bela.evaluation.model_eval import ModelEval from bela.transforms.sp...
BELA-main
bela/utils/prediction_utils.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. class DummyPathManager: def get_local_path(self, path, *args, **kwargs): return path def open(self, path, *args, **kwargs): ...
BELA-main
bela/utils/utils.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass from typing import Any, Dict, Optional, List @dataclass class Entity: entity_id: str # E.g. "Q331212...
BELA-main
bela/utils/analysis_utils.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Optional import torch.nn as nn from transformers import AutoModel, AutoConfig class HFEncoder(nn.Module): def __ini...
BELA-main
bela/models/hf_encoder.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch.nn as nn from transformers import AutoTokenizer class HFTransform(nn.Module): def __init__( self, model_pa...
BELA-main
bela/transforms/hf_transform.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: sentencepiece.proto """Generated protocol buffer...
BELA-main
bela/transforms/sentencepiece_pb2.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Optional import os import torch.nn as nn import sentencepiece as spm from .sentencepiece_pb2 import SentencePieceText cl...
BELA-main
bela/transforms/spm_transform.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from enum import Enum from typing import Any, Dict, List, Optional, Tuple import torch import torch.nn as nn from torch.nn.utils.rnn import ...
BELA-main
bela/transforms/joint_el_transform.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from collections import OrderedDict from typing import Any, Dict, NamedTuple, Optional, Tuple, Union import faiss import fais...
BELA-main
bela/task/joint_el_task.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from pathlib import Path import yaml from hydra.experimental import compose, initialize_config_module import hydra import torch from tqdm imp...
BELA-main
bela/evaluation/model_eval.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass, field from typing import List, Any # @manual "//github/facebookresearch/hydra:hydra" from hydra.core.conf...
BELA-main
bela/conf/config.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass, field from . import config @dataclass class TransformConf: pass @dataclass class DataModuleConf: ...
BELA-main
bela/conf/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from pathlib import Path from itertools import product from tqdm import tqdm import numpy as np from bela.evaluation.model_eval import Mode...
BELA-main
scripts/grid_search_thresholds.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import warnings warnings.filterwarnings('ignore') import yaml from hydra.experimental import compose, initialize_config_module import hydra ...
BELA-main
scripts/evaluate.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import logging import os import pickle import re import pandas import jsonlines from mgenre.utils import chunk_it, get_wiki...
BELA-main
preprocessing_scripts/preprocess_TR2016.py
BELA-main
mblink/__init__.py