python_code
stringlengths
0
4.04M
repo_name
stringlengths
7
58
file_path
stringlengths
5
147
import torch import meerkat as mk from itertools import product import numpy as np from typing import List import pandas as pd PAD_TOKEN_ID = 103 def generate_candidate_descriptions( templates: List[str], device: int = 0, k: int = 2, bert_size: str = "base", num_candidates: str = 30_000, num...
domino-main
domino/_describe/generate.py
from typing import Union import meerkat as mk import numpy as np from scipy.stats import mode from domino.utils import unpack_args def describe( data: mk.DataPanel = None, embeddings: Union[str, np.ndarray] = "embedding", targets: Union[str, np.ndarray] = "target", slices: Union[str, np.ndarray] = "s...
domino-main
domino/_describe/__init__.py
from typing import Union import meerkat as mk import numpy as np from scipy.stats import mode, pearsonr from .abstract import Describer from ..utils import unpack_args class MeanDescriber(Describer): """ Args: text (str, optional): A `Meerkat DataPanel` with columns for text phrases and ...
domino-main
domino/_describe/mean.py
from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Any, Dict, Union import meerkat as mk import numpy as np import torch.nn as nn from sklearn.base import BaseEstimator @dataclass class Config: pass class Slicer(ABC, BaseEstimator): ...
domino-main
domino/_slice/abstract.py
from typing import Union import meerkat as mk import numpy as np import torch import torch.optim as optim from torch.nn.functional import cross_entropy from tqdm import tqdm from domino.utils import unpack_args from .abstract import Slicer class SpotlightSlicer(Slicer): r""" Slice a dataset with The Spotl...
domino-main
domino/_slice/spotlight.py
from __future__ import annotations import warnings from functools import wraps from typing import Union import meerkat as mk import numpy as np import sklearn.cluster as cluster from scipy import linalg from scipy.special import logsumexp from sklearn.decomposition import PCA from sklearn.exceptions import Convergenc...
domino-main
domino/_slice/mixture.py
from __future__ import annotations from typing import Union from domino._slice.abstract import Slicer from torch import nn from torch.nn import functional as F from torch.nn.functional import cross_entropy import torch from sklearn.linear_model import LinearRegression, LogisticRegression, Ridge, Lasso from sklearn.prep...
domino-main
domino/_slice/fused.py
domino-main
domino/_slice/__init__.py
from typing import Union import meerkat as mk import numpy as np import torch import torch.optim as optim from torch.nn.functional import cross_entropy from tqdm import tqdm from domino.utils import unpack_args from abstract import Slicer ## PlaneSpot imports from sklearn import mixture import glob from collections...
domino-main
domino/_slice/planespot.py
from __future__ import annotations from typing import Union from domino._slice.abstract import Slicer from torch import nn from torch.nn import functional as F from torch.nn.functional import cross_entropy import torch from tqdm import tqdm import numpy as np import meerkat as mk from ..utils import convert_to_torch, ...
domino-main
domino/_slice/mlp.py
from __future__ import annotations import datetime from dataclasses import dataclass from typing import Union import meerkat as mk import numpy as np import torch import torch.nn as nn import torch.optim as optim from meerkat.columns.tensor_column import TensorColumn from sklearn.linear_model import Ridge from sklea...
domino-main
domino/_slice/multiaccuracy.py
from __future__ import annotations from collections import defaultdict from multiprocessing.sharedctypes import Value from typing import Union import meerkat as mk import numpy as np from sklearn.tree import DecisionTreeClassifier from domino.utils import convert_to_numpy, unpack_args from .abstract import Slicer c...
domino-main
domino/_slice/barlow.py
from sklearn.decomposition import FactorAnalysis """Factor Analysis. A latent linear variable model. FactorAnalysis is similar to probabilistic PCA implemented by PCA.score While PCA assumes Gaussian noise with the same variance for each feature, the FactorAnalysis model assumes different variances for each of them....
domino-main
domino/_slice/factor.py
from dataclasses import dataclass import meerkat as mk import numpy as np import torch import torch.nn as nn import umap from sklearn.decomposition import PCA #from stratification.cluster.models.cluster import AutoKMixtureModel from torch.nn.functional import cross_entropy from umap import UMAP from domino.utils impo...
domino-main
domino/_slice/george.py
from typing import Dict, Union from .encoder import Encoder def transformers( variant: str = "bert-large-cased", device: Union[int, str] = "cpu" ) -> Dict[str, Encoder]: """Contrastive Language-Image Pre-training (CLIP) encoders [radford_2021]_. Includes encoders for the following modalities: - "tex...
domino-main
domino/_embed/gpt_j.py
from typing import Union, List, Dict import torch from .encoder import Encoder def transformers( variant: str = "bert-large-cased", device: Union[int, str] = "cpu" ) -> Dict[str, Encoder]: """Transformer encoders - "text" Encoders will map these different modalities to the same embedding space. ...
domino-main
domino/_embed/transformers.py
import os from typing import Callable, Union import meerkat as mk import torch from domino._embed.encoder import Encoder from ..registry import Registry from .bit import bit from .clip import clip from .robust import robust from .transformers import transformers __all__ = ["clip", "bit"] encoders = Registry(name="...
domino-main
domino/_embed/__init__.py
from dataclasses import dataclass @dataclass class Encoder: encode: callable preprocess: callable = None collate: callable = None
domino-main
domino/_embed/encoder.py
from functools import partial import torch def _get_reduction_fn(reduction_name): if reduction_name == "max": reduction_fn = partial(torch.mean, dim=[-1, -2]) elif reduction_name == "mean": reduction_fn = partial(torch.mean, dim=[-1, -2]) else: raise ValueError(f"reduction_fn {red...
domino-main
domino/_embed/utils.py
import io from collections import OrderedDict from typing import Dict, Union import numpy as np import PIL import requests import torch import torch.nn as nn import torch.nn.functional as F from ..utils import nested_getattr from .encoder import Encoder from .utils import ActivationExtractor, _get_reduction_fn # thi...
domino-main
domino/_embed/bit.py
from ast import Import import subprocess from typing import Dict, Union import os from .encoder import Encoder VARIANTS = { "imagenet_l2_3_0": "https://www.dropbox.com/s/knf4uimlqsi1yz8/imagenet_l2_3_0.pt?dl=0", "cifar_l2_1_0": "https://www.dropbox.com/s/s2x7thisiqxz095/cifar_l2_1_0.pt?dl=0", "imagenet_li...
domino-main
domino/_embed/robust.py
from typing import Dict, Union from .encoder import Encoder def clip( variant: str = "ViT-B/32", device: Union[int, str] = "cpu" ) -> Dict[str, Encoder]: """Contrastive Language-Image Pre-training (CLIP) encoders [radford_2021]_. Includes encoders for the following modalities: - "text" - "image"...
domino-main
domino/_embed/clip.py
from typing import List, Tuple from dcbench import SliceDiscoveryProblem, SliceDiscoverySolution import meerkat as mk import numpy as np import sklearn.metrics as skmetrics from domino.utils import unpack_args from scipy.stats import rankdata import pandas as pd from tqdm import tqdm def compute_metrics( solution...
domino-main
domino/eval/metrics.py
from __future__ import annotations from contextlib import redirect_stdout import dataclasses from gettext import dpgettext import io import itertools from random import choice, sample from typing import Collection, Dict, Iterable, List, Tuple, Union from dataclasses import dataclass from sklearn.linear_model import Li...
domino-main
domino/eval/run.py
domino-main
domino/eval/__init__.py
from typing import Union import meerkat as mk import numpy as np import pandas as pd class CorrelationImpossibleError(ValueError): def __init__( self, corr: float, n: int, attr_a: str, attr_b: str, mu_a: float, mu_b: float, msg: str, ): ...
domino-main
domino/eval/utils.py
from __future__ import annotations import meerkat as mk import torch import PIL from torchvision.models import ResNet as _ResNet from torchvision.models.resnet import BasicBlock, Bottleneck from torchvision.models.resnet import model_urls as resnet_model_urls from torch.hub import load_state_dict_from_url from torchvi...
domino-main
domino/eval/train.py
domino-main
tests/__init__.py
import os import meerkat as mk import numpy as np from PIL import Image from sklearn.datasets import make_blobs import torch class ImageColumnTestBed: def __init__( self, tmpdir: str, length: int = 16, ): self.image_paths = [] self.image_arrays = [] self.ims = ...
domino-main
tests/testbeds.py
domino-main
tests/_describe/__init__.py
from sklearn import metrics import pytest from itertools import product from domino import DominoSlicer from ..testbeds import SliceTestBed @pytest.mark.parametrize( "init_params,type", product(["random", "confusion"], ["numpy", "torch"]) ) def test_domino_results(init_params: str, type: str): testbed = Sl...
domino-main
tests/_slice/test_domino.py
domino-main
tests/_slice/__init__.py
from sklearn import metrics import pytest import numpy as np from domino import SpotlightSlicer from ..testbeds import SliceTestBed @pytest.mark.parametrize("pass_losses", [True, False]) def test_domino_results(pass_losses): testbed = SliceTestBed(length=9) method = SpotlightSlicer(n_slices=2, n_steps=3)...
domino-main
tests/_slice/test_spotlight.py
import meerkat as mk import PIL import pytest import torch import hashlib import numpy as np import domino from domino import embed, encoders from domino._embed.encoder import Encoder from domino.registry import Registry from ..testbeds import ImageColumnTestBed, TextColumnTestBed EMB_SIZE = 4 def simple_encode(ba...
domino-main
tests/_embed/test__init__.py
domino-main
tests/_embed/__init__.py
domino-main
tests/_embed/test_clip.py
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
domino-main
docs/source/conf.py
# Copyright (c) Meta Platforms, Inc. and affiliates. import subprocess from subprocess import check_output import os import embeddings class VecMap: """ wrapper for vecmap https://github.com/artetxem/vecmap assumes vecmap is in the directory ./vecmap """ def __init__(self, srcvec, tgtvec, dictpath,...
coocmap-main
baselines.py
# Copyright (c) Meta Platforms, Inc. and affiliates. from typing import Optional import collections import numpy as np import pandas as pd from tokenizers import Tokenizer # faithfully recreate the protocol of vecmap with minimal code modifications def vecmap_evaluate(sim: np.ndarray, tokenizer1: Tokenizer, tokeniz...
coocmap-main
evaluation.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # Copyright (C) 2016-2018 Mikel Artetxe <artetxem@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Licen...
coocmap-main
embeddings.py
# Copyright (c) Meta Platforms, Inc. and affiliates. import os from dataclasses import dataclass import wandb import shutil import pandas as pd import numpy as np import data import match import evaluation import embeddings # experimental parameters defaults = dict( lan1='./europarl-v7.hu-en.en', lan2='./eur...
coocmap-main
test_coocmap.py
# Copyright (c) Meta Platforms, Inc. and affiliates. import itertools import os import sys import subprocess import time # import lzma # needed for BUCC20Corpus import numpy as np from tokenizers import Token, Tokenizer from tokenizers.models import BPE, WordLevel from tokenizers.trainers import BpeTrainer, WordLevel...
coocmap-main
data.py
# Copyright (c) Meta Platforms, Inc. and affiliates. from collections import Counter import numpy as np import embeddings np.set_printoptions(formatter={'float': lambda x: "{0:0.3f}".format(x)}) MAX_SVD_DIM = 5000 # maximum SVD to avoid long compute time ### initialization methods ### def vecmap_unsup(x, z, norm_proc...
coocmap-main
match.py
import os import subprocess from dataclasses import dataclass import lzma import wandb import argparse import shutil import pandas as pd import numpy as np import data import match import evaluation import embeddings # from baselines import VecMap os.environ['WANDB_IGNORE_GLOBS'] = 'lan1/*,lan2/*' os.environ["OMP_NU...
coocmap-main
experiments/test_accvsize_cooc.py
import os import subprocess from dataclasses import dataclass import lzma import wandb import argparse import shutil import pandas as pd import numpy as np import data import match import evaluation import embeddings # from baselines import VecMap os.environ['WANDB_IGNORE_GLOBS'] = 'lan1/*,lan2/*' os.environ["OMP_NU...
coocmap-main
experiments/test_accvsize.py
import os import subprocess from dataclasses import dataclass import lzma import wandb import argparse import shutil import pandas as pd import numpy as np import data import match import evaluation import embeddings # from baselines import VecMap os.environ['WANDB_IGNORE_GLOBS'] = 'lan1/*,lan2/*' os.environ["OMP_NU...
coocmap-main
experiments/test_dropclip.py
import os import subprocess from dataclasses import dataclass import lzma import wandb import argparse import shutil import pandas as pd import numpy as np import data import match import evaluation import embeddings # from baselines import VecMap os.environ['WANDB_IGNORE_GLOBS'] = 'lan1/*,lan2/*' os.environ["OMP_NU...
coocmap-main
experiments/test_accvdim.py
import os from dataclasses import dataclass import wandb import shutil import pandas as pd import numpy as np import data import match import evaluation import embeddings # experimental parameters defaults = dict( lan1='./europarl-v7.hu-en.en', lan2='./europarl-v7.hu-en.hu', eval='en-hu', size1=20, ...
coocmap-main
experiments/test_coocmap.py
import os import subprocess from dataclasses import dataclass import lzma import wandb import argparse import shutil import pandas as pd import numpy as np import data import match import evaluation import embeddings # from baselines import VecMap os.environ['WANDB_IGNORE_GLOBS'] = 'lan1/*,lan2/*' os.environ["OMP_NU...
coocmap-main
experiments/test_matching.py
from setuptools import setup from Cython.Build import cythonize import numpy # python setup.py build_ext --inplace setup( ext_modules=cythonize( ['cooc_count.pyx'], annotate=True), include_dirs=[numpy.get_include()] )
coocmap-main
fast/setup.py
#!/usr/bin/env python3 # # Copyright (c) Meta Platforms, Inc. and 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 argparse import math import torch import random import numpy as np from tqdm import tqdm ...
bounding_data_reconstruction-main
mnist_logistic_reconstruction.py
#!/usr/bin/env python3 # # Copyright (c) Meta Platforms, Inc. and 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 array import gzip import logging import os from os import path import struct import math ...
bounding_data_reconstruction-main
datasets.py
#!/usr/bin/env python3 # # Copyright (c) Meta Platforms, Inc. and 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 argparse import math import torch import numpy as np import os import matplotlib.pyplot a...
bounding_data_reconstruction-main
mnist_logistic_regression.py
#!/usr/bin/env python3 # # Copyright (c) Meta Platforms, Inc. and 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 jax import jax.numpy as jnp from jax.experimental import stax DTYPE_MAPPING = { "flo...
bounding_data_reconstruction-main
utils.py
#!/usr/bin/env python3 # # Copyright (c) Meta Platforms, Inc. and 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 jax.numpy as jnp import jax.random as jnr from jax import jit, grad, vmap, nn from jax.tr...
bounding_data_reconstruction-main
trainer.py
#!/usr/bin/env python3 # # Copyright (c) Meta Platforms, Inc. and 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 itertools import logging import jax import jax.numpy as jnp import jax.random as jnr imp...
bounding_data_reconstruction-main
train_classifier.py
#!/usr/bin/env python3 # # Copyright (c) Meta Platforms, Inc. and 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 jax.numpy as jnp import jax.random as jnr from jax import jit, jvp, vjp, jacrev, vmap, n...
bounding_data_reconstruction-main
accountant.py
import numpy as np from utils.constant import NEGATIVE, POSITIVE from utils.utils import mean_to_canonical import networkx as nx from collections import Counter from sklearn.linear_model import LinearRegression, LogisticRegression import random from utils.utils import numberToBase from utils.utils import multi_index_to...
ivy-tutorial-master
methods/ivy.py
from __future__ import division, print_function import numpy as np try: from pylab import plt except ImportError: print('Unable to import pylab. R_pca.plot_fit() will not work.') try: # Python 2: 'xrange' is the iterative version range = xrange except NameError: # Python 3: 'range' is iterative -...
ivy-tutorial-master
utils/r_pca.py
import numpy as np from .constant import NEGATIVE, POSITIVE import pandas as pd from collections import Counter from pgmpy.models import MarkovModel from pgmpy.factors.discrete import DiscreteFactor from pgmpy.inference import BeliefPropagation import itertools as it import random from statsmodels import robust class...
ivy-tutorial-master
utils/utils.py
POSITIVE = 1 NEGATIVE = -1
ivy-tutorial-master
utils/constant.py
import numpy as np import networkx as nx import itertools as it import pandas as pd from pgmpy.models import MarkovModel from pgmpy.factors.discrete import DiscreteFactor import pylab as plt from utils.utils import IsingModel, factor2Df, sampling from collections import Counter from pgmpy.models import BayesianModel fr...
ivy-tutorial-master
utils/data_simulator.py
import numpy as np from sklearn.linear_model import LinearRegression, LogisticRegression from utils.constant import NEGATIVE, POSITIVE def ProbWaldEstimator(X, Y, Zprob, mode="bxby", **kwargs): if set(Zprob)=={-1,1}: Zprob = (Zprob+1)/2 sample_weight_ZX = np.array([[sum(Zprob[X==x]), sum(1-Zprob[...
ivy-tutorial-master
estimators/prob_wald_estimator.py
from sklearn.linear_model import LinearRegression, LogisticRegression import numpy as np from sklearn.metrics import r2_score def WaldEstimator(X, Y, Z, mode="bxby",return_predictive_score=False): # # adjust the probability range of Z to real # # if Z is a probability not binary label # # this will avoid...
ivy-tutorial-master
estimators/wald_estimator.py
import multiprocessing import numpy as np from joblib import Parallel, delayed from sklearn import preprocessing from tqdm import tqdm from methods.ivy import Ivy def ComputeCausalitySingle( X, Y, IVs, IV_Model_list, estimator_list, is_soft_label=True, ablation_train=1, ablation_t...
ivy-tutorial-master
estimators/compute_causality.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. import os import argparse import csv import logging import pickle import numpy as np import torch import transformers i...
contriever-main
generate_passage_embeddings.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. import sys import argparse import torch import logging import json import numpy as np import os import src.slurm import sr...
contriever-main
eval_beir.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import argparse import torch import transformers from src.normalize_text import normalize def save(tensor, split_path): if not os.path.exists(os.path.dirname(split_path)): os.makedirs(os.path.dirname(split_path)) with o...
contriever-main
preprocess.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. import argparse import json import logging import glob import numpy as np import torch import src.utils from src.evaluat...
contriever-main
evaluate_retrieved_passages.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import pdb import os import time import sys import torch from torch.utils.tensorboard import SummaryWriter import logging import json import numpy as np import torch.distributed as dist from torch.utils.data import DataLoader, RandomSampler, Sequen...
contriever-main
finetuning.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import time import sys import torch import logging import json import numpy as np import random import pickle import torch.distributed as dist from torch.utils.data import DataLoader, RandomSampler from src.options import Options from s...
contriever-main
train.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. import os import argparse import csv import json import logging import pickle import time import glob from pathlib import P...
contriever-main
passage_retrieval.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import sys import os import csv import json def convert2beir(data_path, output_path): splits = ['test', 'dev', 'train'] queries_path = os.path.join(output_path, "queries.jsonl") corpus_path = os.path.join(output_path, "corpus.jsonl") ...
contriever-main
data_scripts/convertmrtydi2beir.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import sys import os import json from collections import defaultdict def preprocess_xmkqa(input_path, output_dir): os.makedirs(output_dir, exist_ok=True) mkqa = [] with open(input_path, 'r') as fin: for line in fin: ...
contriever-main
data_scripts/preprocess_xmkqa.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import torch import transformers from transformers import BertModel, XLMRobertaModel from src import utils class Contriever(BertModel): def __init__(self, config, pooling="average", **kwargs): super().__init__(config, add_p...
contriever-main
src/contriever.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import argparse import os class Options: def __init__(self): self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) self.initialize() def initialize(self): # basic parameters...
contriever-main
src/options.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch import torch.nn as nn import numpy as np import math import random import transformers import logging import torch.distributed as dist from src import contriever, dist_utils, utils logger = logging.getLogger(__name__) class InBatch...
contriever-main
src/inbatch.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. import os import pickle from typing import List, Tuple import faiss import numpy as np from tqdm import tqdm class Index...
contriever-main
src/index.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 logging import getLogger import os import sys import torch import socket import signal import subprocess logger = ge...
contriever-main
src/slurm.py
#!/usr/bin/env python3 # 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 collections import logging import regex import string import unicodedata from functools impor...
contriever-main
src/evaluation.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch import random import json import sys import numpy as np from src import normalize_text class Dataset(torch.utils.data.Dataset): def __init__( self, datapaths, negative_ctxs=1, negative_hard_ratio=0...
contriever-main
src/finetuning_data.py
contriever-main
src/__init__.py
""" adapted from chemdataextractor.text.normalize ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tools for normalizing text. https://github.com/mcs07/ChemDataExtractor :copyright: Copyright 2016 by Matt Swain. :license: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated ...
contriever-main
src/normalize_text.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import sys import logging import torch import errno from typing import Union, Tuple, List, Dict from collections import defaultdict from src import dist_utils Number = Union[float, int] logger = logging.getLogger(__name__) def init_l...
contriever-main
src/utils.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch import torch.nn as nn import logging import copy import transformers from src import contriever, dist_utils, utils logger = logging.getLogger(__name__) class MoCo(nn.Module): def __init__(self, opt): super(MoCo, self)._...
contriever-main
src/moco.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import glob import torch import random import json import csv import numpy as np import numpy.random import logging from collections import defaultdict import torch.distributed as dist from src import dist_utils logger = logging.getLogg...
contriever-main
src/data.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch import torch.distributed as dist class Gather(torch.autograd.Function): @staticmethod def forward(ctx, x: torch.tensor): output = [torch.zeros_like(x) for _ in range(dist.get_world_size())] dist.all_gather(out...
contriever-main
src/dist_utils.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os from collections import defaultdict from typing import List, Dict import numpy as np import torch import torch.distributed as dist import beir.util from beir.datasets.data_loader import GenericDataLoader from beir.retrieval.evaluation im...
contriever-main
src/beir_utils.py
# Copyright (c) Meta Platforms, Inc. and 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 os import cv2 import numpy as np from utils.meshutils import read_mesh, process_head_model from utils.strandsuti...
CT2Hair-main
CT2Hair/interp.py
# Copyright (c) Meta Platforms, Inc. and 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 os from utils.pcutils import load_pc from utils.strandsutils import strandspc2strands, smooth_strands from datau...
CT2Hair-main
CT2Hair/optim.py
# Copyright (c) Meta Platforms, Inc. and 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 import numpy as np import torch.utils.data as th_data from utils.strandsutils import spline_strand, pad_st...
CT2Hair-main
CT2Hair/datautils/dataloaders.py
# Copyright (c) Meta Platforms, Inc. and 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 time import pathlib import struct import numpy as np from utils.pcutils import pc_voxelization, save_pc def loa...
CT2Hair-main
CT2Hair/datautils/datautils.py
# Copyright (c) Meta Platforms, Inc. and 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 math import splines import torch import numpy as np from tqdm import tqdm from scipy.sparse import coo_matrix fr...
CT2Hair-main
CT2Hair/utils/strandsutils.py
# Copyright (c) Meta Platforms, Inc. and 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 math import copy import igl import trimesh import numpy as np from scipy.spatial.transform import Rotation as R ...
CT2Hair-main
CT2Hair/utils/meshutils.py
# Copyright (c) Meta Platforms, Inc. and 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 time import numpy as np import open3d as o3d from copy import deepcopy from matplotlib import cm def volume2pc(v...
CT2Hair-main
CT2Hair/utils/pcutils.py
# Copyright (c) Meta Platforms, Inc. and 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 cv2 import math import torch import torch.nn as nn import numpy as np from matplotlib import cm def polar2vector...
CT2Hair-main
CT2Hair/utils/utils.py
# Copyright (c) Meta Platforms, Inc. and 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 math import torch import torch.nn as nn import torch.nn.functional as F class Conv3dGaussian(nn.Module): '''...
CT2Hair-main
CT2Hair/utils/kernels.py
from .chamfer_distance import ChamferDistance
CT2Hair-main
CT2Hair/libs/chamfer_distance/__init__.py
# Copyright (c) Meta Platforms, Inc. and 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. # https://github.com/chrdiller/pyTorchChamferDistance/tree/master import torch from torch.utils.cpp_extension import l...
CT2Hair-main
CT2Hair/libs/chamfer_distance/chamfer_distance.py
# Copyright (c) Meta Platforms, Inc. and 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 copy import math import torch import numpy as np from tqdm import tqdm from sklearn.cluster import MeanShift fro...
CT2Hair-main
CT2Hair/modules/neural_strands.py