repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/utils/llama_convert/fs_to_hf.py | from transformers.models.llama import LlamaForCausalLM, LlamaTokenizer, LlamaConfig
from fengshen.models.megatron import mpu
from fengshen.models.llama.modeling_llama import LlamaForCausalLM as FengshenLlama
from fengshen.models.llama.configuration_llama import LlamaConfig as FengshenConfig
import argparse
import torch... | 3,811 | 36.009709 | 110 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/utils/llama_convert/convert_fs_llama_tp.py | import argparse
import os
import json
import torch
from fengshen.models.llama.configuration_llama import LlamaConfig
__HF_NORM_PREFIX__ = "llama.final_layer_norm"
__HF_EMBED_IN_KEY__ = "llama.embed_in.word_embeddings.weight"
__HF_EMBED_OUT_KEY__ = "embed_out.final_linear.weight"
__HF_LAYER_PREFIX__ = "llama.layers"
_... | 6,643 | 34.72043 | 92 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/utils/llama_convert/hf_to_fs.py | from transformers.models.llama import LlamaForCausalLM, LlamaTokenizer, LlamaConfig
from fengshen.models.megatron import mpu
from fengshen.models.llama.modeling_llama import LlamaForCausalLM as FengshenLlama
from fengshen.models.llama.configuration_llama import LlamaConfig as FengshenConfig
import argparse
import torch... | 5,921 | 38.218543 | 109 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/utils/llama_convert/merge_lt_mp_to_hf.py | import argparse
import os
import json
import torch
from fengshen_inner.models.llama.configuration_llama import LlamaConfig as FengshenConfig
from fengshen_inner.models.llama.modeling_llama import LlamaForCausalLM as FengshenLlama
from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer
from fengshen_inner... | 6,335 | 37.4 | 125 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/universal_datamodule/universal_datamodule.py | from pytorch_lightning import LightningDataModule
from typing import Optional
from torch.utils.data import DataLoader, DistributedSampler
from fengshen.models.megatron import mpu
def get_consume_samples(data_model: LightningDataModule) -> int:
if hasattr(data_model.trainer.lightning_module, 'consumed_samples'):
... | 7,829 | 40.210526 | 112 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/universal_datamodule/universal_sampler.py | # coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | 5,181 | 40.126984 | 89 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/mmap_dataloader/mmap_index_dataset.py | import numpy as np
import torch
from typing import List
from torch.utils.data import Dataset
class MMapIndexDataset(Dataset):
# datapaths 是所有的内存映射文件的路径
# input_tensor_name 是输入的tensor的名字 例如 ['input_ids'] 会存储在对应的文件里面
def __init__(self, datapaths: List[str], input_tensor_name: List[str]):
dict_idx_fp... | 1,815 | 32.62963 | 81 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/mmap_dataloader/mmap_datamodule.py | from typing import Optional
from pytorch_lightning import LightningDataModule
from torch.utils.data import DataLoader
from fengshen.data.mmap_index_dataset import MMapIndexDataset
class MMapDataModule(LightningDataModule):
@ staticmethod
def add_data_specific_args(parent_args):
parser = parent_args.ad... | 2,461 | 34.681159 | 94 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/dreambooth_datasets/dreambooth_datasets.py | # -*- encoding: utf-8 -*-
'''
Copyright 2022 The International Digital Economy Academy (IDEA). CCNL team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.o... | 6,386 | 33.711957 | 118 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/t5_dataloader/t5_datasets.py | # coding=utf8
import json
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm
from transformers import BertTokenizer, MT5Config, MT5Tokenizer, BatchEncoding
import torch
import pytorch_lightning as pl
import numpy as np
from itertools import chain
import sys
sys.path.append('../../')
def compute_in... | 25,946 | 45.087034 | 127 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/t5_dataloader/t5_gen_datasets.py | # -*- encoding: utf-8 -*-
'''
@File : t5_gen_datasets.py
@Time : 2022/10/24 19:29
@Author : He Junqing
@Version : 1.0
@Contact : hejunqing@idea.edu.cn
@License : (C)Copyright 2022-2023, CCNL-IDEA
'''
from logging import exception
from transformers import (
BertTokenizer,
MT5Config,
MT5To... | 13,701 | 33.954082 | 101 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/taiyi_stable_diffusion_datasets/taiyi_datasets.py | from torch.utils.data import Dataset, ConcatDataset
import os
from concurrent.futures import ProcessPoolExecutor
import pandas as pd
def add_data_args(parent_args):
parser = parent_args.add_argument_group('taiyi stable diffusion data args')
# 支持传入多个路径,分别加载
parser.add_argument(
"--datasets_path", t... | 6,417 | 35.885057 | 117 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/task_dataloader/medicalQADataset.py | # coding=utf8
import os
import pytorch_lightning as pl
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
from transformers import AutoTokenizer
class GPT2QADataset(Dataset):
'''
Dataset Used for yuyuan medical qa task.
Just surpport small datasets, when deal with large datasets it may... | 5,285 | 37.304348 | 102 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/task_dataloader/task_datasets.py | # coding=utf8
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm
from transformers import AutoTokenizer
import json
import torch
import pytorch_lightning as pl
import os
class AbstractCollator:
"""
collector for summary task
"""
def __init__(self, tokenizer, max_enc_length, max_de... | 7,832 | 36.84058 | 114 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/hubert/hubert_dataset.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.
import itertools
import logging
import os
import sys
from typing import Any, List, Optional, Union
import numpy as np
import torch
import to... | 13,124 | 35.256906 | 86 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/clip_dataloader/flickr.py | from torch.utils.data import Dataset, DataLoader
from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \
CenterCrop
from transformers import BertTokenizer
import pytorch_lightning as pl
from PIL import Image
import os
class flickr30k_CNA(Dataset):
def _... | 3,812 | 34.971698 | 112 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/megatron_dataloader/bart_dataset.py | """BART Style dataset. Modified from fairseq."""
import numpy as np
import torch
import math
import re
from fengshen.data.megatron_dataloader.dataset_utils import (
get_samples_mapping
)
class BartDataset(torch.utils.data.Dataset):
def __init__(self, name, indexed_dataset, data_prefix,
num_... | 18,396 | 40.434685 | 103 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/megatron_dataloader/dataset_utils.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors, and NVIDIA.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | 30,965 | 38.247148 | 103 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/megatron_dataloader/utils.py | # coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | 903 | 35.16 | 74 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/megatron_dataloader/bert_dataset.py | # coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | 8,121 | 40.228426 | 94 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/megatron_dataloader/blendable_dataset.py | # coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | 2,208 | 32.984615 | 78 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/megatron_dataloader/indexed_dataset.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.
# copied from fairseq/fairseq/data/indexed_dataset.py
# Removed IndexedRawTextDataset since it relied on Fairseq dictionary
# other slight mo... | 18,859 | 31.1843 | 80 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/sequence_tagging_dataloader/sequence_tagging_collator.py | from dataclasses import dataclass
from torch.utils.data._utils.collate import default_collate
import copy
import torch
import numpy as np
@dataclass
class CollatorForLinear:
args = None
tokenizer = None
label2id = None
def __call__(self, samples):
cls_token = "[CLS]"
sep_token = "[SEP... | 10,403 | 36.970803 | 133 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/sequence_tagging_dataloader/sequence_tagging_datasets.py | from torch.utils.data import Dataset
from fengshen.metric.utils_ner import get_entities
import os
def get_datasets(args):
processor = DataProcessor(args.data_dir, args.decode_type)
train_data = TaskDataset(processor=processor, mode="train")
valid_data = TaskDataset(processor=processor, mode="dev")
te... | 4,409 | 37.017241 | 108 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/data/bert_dataloader/load.py | import os
import re
from pathlib import Path
import glob
from tqdm import tqdm
from contextlib import ExitStack
import datasets
import multiprocessing
from typing import cast, TextIO
from itertools import chain
import json
from concurrent.futures import ProcessPoolExecutor
from random import shuffle
from pytorch_lightn... | 6,756 | 32.616915 | 124 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/pipelines/sequence_tagging.py | import torch
import torch.nn.functional as F
from torch.utils.data._utils.collate import default_collate
from dataclasses import dataclass
from typing import Dict, List, Union
from fengshen.models.tagging_models.bert_for_tagging import BertLinear,BertCrf,BertSpan,BertBiaffine
from fengshen.data.sequence_tagging_datalo... | 12,608 | 39.156051 | 154 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/pipelines/text_classification.py | import torch
from torch.utils.data._utils.collate import default_collate
from dataclasses import dataclass
from typing import Dict, List
from .base import (
_CONFIG_MODEL_TYPE,
_CONFIG_TOKENIZER_TYPE)
from fengshen.models.roformer import RoFormerForSequenceClassification
from fengshen.models.longformer import L... | 9,274 | 38.468085 | 106 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/pipelines/tcbert.py | # coding=utf-8
# Copyright 2021 The IDEA Authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by a... | 5,390 | 38.350365 | 116 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/pipelines/multiplechoice.py | # coding=utf-8
# Copyright 2021 The IDEA Authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by a... | 7,967 | 39.653061 | 116 | py |
Fengshenbang-LM | Fengshenbang-LM-main/fengshen/pipelines/information_extraction.py | from logging import basicConfig
import torch
from torch import nn
import json
from tqdm import tqdm
import os
import numpy as np
from transformers import BertTokenizer
import pytorch_lightning as pl
from pytorch_lightning import trainer, loggers
from transformers import AlbertTokenizer
from transformers import AutoCon... | 4,151 | 36.071429 | 127 | py |
TFusion | TFusion-master/rank-reid/transfer/simple_rank_transfer.py | import os
import utils.cuda_util
import numpy as np
from keras import Input
from keras import backend as K
from keras.applications.resnet50 import preprocess_input, ResNet50
from keras.callbacks import EarlyStopping, ReduceLROnPlateau
from keras.engine import Model
from keras.layers import Flatten, Lambda, Dense, Conv2... | 11,654 | 43.484733 | 136 | py |
TFusion | TFusion-master/rank-reid/baseline/evaluate.py | from __future__ import division, print_function, absolute_import
import os
import numpy as np
import tensorflow as tf
from keras.applications.resnet50 import preprocess_input
from keras.backend.tensorflow_backend import set_session
from keras.models import Model
from keras.preprocessing import image
from utils.file_... | 7,555 | 31.568966 | 96 | py |
TFusion | TFusion-master/rank-reid/baseline/train.py | from __future__ import division, print_function, absolute_import
import os
from random import shuffle
import numpy as np
import tensorflow as tf
from keras.applications.resnet50 import ResNet50
from keras.applications.resnet50 import preprocess_input
from keras.backend.tensorflow_backend import set_session
from keras... | 5,745 | 33.407186 | 120 | py |
TFusion | TFusion-master/rank-reid/pretrain/pair_train.py | import os
import numpy as np
from keras import Input
from keras import backend as K
from keras.applications.resnet50 import preprocess_input
from keras.callbacks import EarlyStopping, ReduceLROnPlateau
from keras.engine import Model
from keras.layers import Lambda, Dense, Dropout, Flatten
from keras.models import load... | 10,663 | 40.173745 | 121 | py |
TFusion | TFusion-master/rank-reid/pretrain/eval.py | # coding=utf-8
import os
from keras import backend as K
from keras.engine import Model
from keras.models import load_model
from keras.preprocessing import image
from baseline.evaluate import train_predict, test_predict, grid_result_eval, market_result_eval
from transfer.simple_rank_transfer import cross_entropy_loss
... | 4,102 | 38.07619 | 108 | py |
TFusion | TFusion-master/rank-reid/utils/cuda_util.py | import os
from keras.backend import set_session
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.6
set_session(tf.Session(config=config)) | 302 | 26.545455 | 64 | py |
hyperopt | hyperopt-master/docs/autogen.py | # This file has been taken from Keras' `docs` module found here:
# https://github.com/keras-team/keras/blob/master/docs/autogen.py
#
import re
import inspect
import os
import shutil
EXCLUDE = {}
PAGES = [
# {
# 'page': 'target.md',
# 'classes': [
# ],
# 'functions': [
# ... | 12,407 | 32.994521 | 87 | py |
EZ-VSL | EZ-VSL-main/test.py | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import utils
import numpy as np
import argparse
from model import EZVSL
from datasets import get_test_dataset, inverse_normalize
import cv2
def get_arguments():
parser = argparse.ArgumentParser()
... | 8,390 | 42.252577 | 185 | py |
EZ-VSL | EZ-VSL-main/audio_io.py | import av
# import torchaudio
import numpy as np
from fractions import Fraction
# def load_audio_torchaudio(fn):
# data, sr = torchaudio.load(fn)
# return data, sr
def open_audio_av(path):
container = av.open(path)
for stream in container.streams.video:
stream.codec_context.thread_type = av.... | 3,295 | 31 | 105 | py |
EZ-VSL | EZ-VSL-main/utils.py | import os
import json
from torch.optim import *
import numpy as np
from sklearn import metrics
class Evaluator(object):
def __init__(self):
super(Evaluator, self).__init__()
self.ciou = []
def cal_CIOU(self, infer, gtmap, thres=0.01):
infer_map = np.zeros((224, 224))
infer_map... | 2,784 | 29.604396 | 90 | py |
EZ-VSL | EZ-VSL-main/model.py | import torch
from torch import nn
import torch.nn.functional as F
from torchvision.models import resnet18
class EZVSL(nn.Module):
def __init__(self, tau, dim):
super(EZVSL, self).__init__()
self.tau = tau
# Vision model
self.imgnet = resnet18(pretrained=True)
self.imgnet.a... | 2,348 | 35.138462 | 107 | py |
EZ-VSL | EZ-VSL-main/datasets.py | import os
import csv
import numpy as np
from torch.utils.data import Dataset
from torchvision import transforms
from PIL import Image
from scipy import signal
import random
import json
import xml.etree.ElementTree as ET
from audio_io import load_audio_av, open_audio_av
def load_image(path):
return Image.open(path... | 8,126 | 33.004184 | 170 | py |
EZ-VSL | EZ-VSL-main/train.py | import os
import argparse
import builtins
import time
import numpy as np
import torch
import torch.nn.functional as F
from torch import multiprocessing as mp
import torch.distributed as dist
import utils
from model import EZVSL
from datasets import get_train_dataset, get_test_dataset
def get_arguments():
parser... | 10,736 | 36.152249 | 138 | py |
CLNet | CLNet-main/main.py | import torch
import torch.nn as nn
from utils.parser import args
from utils import logger, Trainer, Tester
from utils import init_device, init_model, FakeLR, WarmUpCosineAnnealingLR
from dataset import Cost2100DataLoader
def main():
logger.info('=> PyTorch Version: {}'.format(torch.__version__))
# Environme... | 2,892 | 31.505618 | 91 | py |
CLNet | CLNet-main/dataset/cost2100.py | import os
import numpy as np
import scipy.io as sio
import torch
from torch.utils.data import DataLoader, TensorDataset
__all__ = ['Cost2100DataLoader', 'PreFetcher']
class PreFetcher:
r""" Data pre-fetcher to accelerate the data loading
"""
def __init__(self, loader):
self.ori_loader = loader
... | 4,282 | 35.922414 | 85 | py |
CLNet | CLNet-main/models/clnet.py | r""" The proposed CLNet
"""
import torch
import torch.nn as nn
from collections import OrderedDict
import torch.nn.functional as F
from utils import logger
__all__ = ["clnet"]
class ConvBN(nn.Sequential):
def __init__(self, in_planes, out_planes, kernel_size, stride=1, groups=1):
if not isinstance(kern... | 7,266 | 32.957944 | 154 | py |
CLNet | CLNet-main/.ipynb_checkpoints/main-checkpoint.py | import torch
import torch.nn as nn
from utils.parser import args
from utils import logger, Trainer, Tester
from utils import init_device, init_model, FakeLR, WarmUpCosineAnnealingLR
from dataset import Cost2100DataLoader
def main():
logger.info('=> PyTorch Version: {}'.format(torch.__version__))
# Environme... | 2,892 | 31.505618 | 91 | py |
CLNet | CLNet-main/utils/statics.py | import torch
from packaging import version
__all__ = ['AverageMeter', 'evaluator']
class AverageMeter(object):
r"""Computes and stores the average and current value
Imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262
"""
def __init__(self, name):
self.re... | 2,882 | 34.158537 | 111 | py |
CLNet | CLNet-main/utils/scheduler.py | import math
from torch.optim.lr_scheduler import _LRScheduler
__all__ = ['WarmUpCosineAnnealingLR', 'FakeLR']
class WarmUpCosineAnnealingLR(_LRScheduler):
def __init__(self, optimizer, T_max, T_warmup, eta_min=0, last_epoch=-1):
self.T_max = T_max
self.T_warmup = T_warmup
self.eta_min = e... | 955 | 33.142857 | 104 | py |
CLNet | CLNet-main/utils/init.py | import os
import random
import thop
import torch
from models import clnet
from utils import logger, line_seg
__all__ = ["init_device", "init_model"]
def init_device(seed=None, cpu=None, gpu=None, affinity=None):
# set the CPU affinity
if affinity is not None:
os.system(f'taskset -p {affinity} {os.ge... | 2,102 | 29.926471 | 79 | py |
CLNet | CLNet-main/utils/solver.py | import time
import os
import torch
from collections import namedtuple
from utils import logger
from utils.statics import AverageMeter, evaluator
__all__ = ['Trainer', 'Tester']
field = ('nmse', 'rho', 'epoch')
Result = namedtuple('Result', field, defaults=(None,) * len(field))
class Trainer:
r""" The training... | 9,472 | 34.215613 | 93 | py |
CLNet | CLNet-main/utils/.ipynb_checkpoints/solver-checkpoint.py | import time
import os
import torch
from collections import namedtuple
from utils import logger
from utils.statics import AverageMeter, evaluator
__all__ = ['Trainer', 'Tester']
field = ('nmse', 'rho', 'epoch')
Result = namedtuple('Result', field, defaults=(None,) * len(field))
class Trainer:
r""" The training... | 9,472 | 34.215613 | 93 | py |
CLNet | CLNet-main/utils/.ipynb_checkpoints/init-checkpoint.py | import os
import random
import thop
import torch
from models import clnet
from utils import logger, line_seg
__all__ = ["init_device", "init_model"]
def init_device(seed=None, cpu=None, gpu=None, affinity=None):
# set the CPU affinity
if affinity is not None:
os.system(f'taskset -p {affinity} {os.ge... | 2,102 | 29.926471 | 79 | py |
modir | modir-master/drivers/run_warmup.py | import sys
sys.path += ["../"]
import pandas as pd
from transformers import glue_compute_metrics as compute_metrics, glue_output_modes as output_modes, glue_processors as processors
from transformers import (
AdamW,
RobertaConfig,
RobertaForSequenceClassification,
RobertaTokenizer,
get_linear_schedu... | 44,416 | 36.045038 | 145 | py |
modir | modir-master/drivers/run_ann_data_gen.py | import sys
sys.path += ['../']
import torch
import os
from collections import defaultdict
import faiss
from utils.util import (
barrier_array_merge,
convert_to_string_id,
is_first_worker,
StreamingDataset,
EmbeddingCache,
get_checkpoint_no,
get_latest_ann_data
)
import csv
import copy
import... | 31,788 | 31.2077 | 121 | py |
modir | modir-master/drivers/run_ann.py | import sys
sys.path += ['../']
import os
import time
import torch
from data.msmarco_data import GetTrainingDataProcessingFn, GetTripletTrainingDataProcessingFn
from utils.util import (
getattr_recursive,
set_seed,
StreamingDataset,
EmbeddingCache,
get_checkpoint_no,
get_latest_ann_data,
is_f... | 46,511 | 35.027885 | 149 | py |
modir | modir-master/utils/eval_mrr.py | import sys
sys.path += ["../"]
from utils.msmarco_eval import quality_checks_qids, compute_metrics, load_reference
import torch.distributed as dist
import gzip
import faiss
import numpy as np
from data.process_fn import dual_process_fn
from tqdm import tqdm
import torch
import os
from utils.util import concat_key, is_f... | 7,984 | 34.807175 | 100 | py |
modir | modir-master/utils/dpr_utils.py | import collections
import sys
sys.path += ['../']
import glob
import logging
import os
from typing import List, Tuple, Dict
import faiss
import pickle
import numpy as np
import unicodedata
import torch
import torch.distributed as dist
from torch import nn
from torch.serialization import default_restore_location
import ... | 12,483 | 35.934911 | 118 | py |
modir | modir-master/utils/modir_utils.py | import os
import sys
import csv
import numpy as np
import faiss
import torch
import torch.distributed as dist
from torch.utils.data import DataLoader
try:
from apex import amp
except ImportError:
print("apex not imported")
from utils.util import (
is_first_worker,
StreamingDataset,
EmbeddingCache,... | 10,586 | 36.676157 | 115 | py |
modir | modir-master/utils/util.py | import sys
sys.path += ['../']
import pandas as pd
from sklearn.metrics import roc_curve, auc
import gzip
import copy
import torch
from torch import nn
import torch.distributed as dist
from tqdm import tqdm, trange
import os
from os import listdir
from os.path import isfile, join
import json
import logging
import rando... | 12,596 | 29.354217 | 126 | py |
modir | modir-master/utils/lamb.py | """Lamb optimizer."""
import collections
import math
import torch
from tensorboardX import SummaryWriter
from torch.optim import Optimizer
def log_lamb_rs(optimizer: Optimizer, event_writer: SummaryWriter, token_count: int):
"""Log a histogram of trust ratio scalars in across layers."""
results = collection... | 4,887 | 38.419355 | 109 | py |
modir | modir-master/data/process_fn.py | import torch
def pad_ids(input_ids, attention_mask, token_type_ids, max_length, pad_token, mask_padding_with_zero, pad_token_segment_id, pad_on_left=False):
padding_length = max_length - len(input_ids)
if pad_on_left:
input_ids = ([pad_token] * padding_length) + input_ids
attention_mask = ([0 ... | 5,071 | 43.884956 | 167 | py |
modir | modir-master/data/msmarco_data.py | import sys
import os
import torch
sys.path += ['../']
import gzip
import pickle
from utils.util import pad_input_ids, multi_file_process, numbered_byte_file_generator, EmbeddingCache
import csv
from model.models import MSMarcoConfigDict, ALL_MODELS
from torch.utils.data import DataLoader, Dataset, TensorDataset, Iterab... | 16,967 | 29.085106 | 162 | py |
modir | modir-master/data/DPR_data.py | from os.path import join
import sys
sys.path += ['../']
import argparse
import json
import os
import random
import numpy as np
import torch
from torch.utils.data import Dataset, TensorDataset
from model.models import MSMarcoConfigDict, ALL_MODELS
import csv
from utils.util import multi_file_process, numbered_byte_file_... | 14,512 | 34.923267 | 135 | py |
modir | modir-master/model/domain_classifier.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader
class DomainClassifier(nn.Module):
def __init__(self,
args,
input_size=768,
n_class=2):
super(DomainClassifier, sel... | 8,906 | 37.227468 | 104 | py |
modir | modir-master/model/models.py | import sys
sys.path += ['../']
import torch
from torch import nn
from transformers import (
RobertaConfig,
RobertaModel,
RobertaForSequenceClassification,
RobertaTokenizer,
BertModel,
BertTokenizer,
BertConfig
)
import torch.nn.functional as F
from data.process_fn import triple_process_fn, t... | 11,058 | 35.863333 | 144 | py |
container | container-main/main.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import argparse
import datetime
import numpy as np
import time
import torch
import torch.backends.cudnn as cudnn
import json
from pathlib import Path
from timm.data import Mixup
from timm.models import create_model
from timm.loss import LabelSmoothin... | 20,346 | 47.330166 | 119 | py |
container | container-main/losses.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Implements the knowledge distillation loss
"""
import torch
from torch.nn import functional as F
class DistillationLoss(torch.nn.Module):
"""
This module wraps a standard criterion and adds an extra knowledge distillation loss by
taki... | 2,771 | 41.646154 | 114 | py |
container | container-main/engine.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Train and eval functions used in main.py
"""
import math
import sys
from typing import Iterable, Optional
import torch
from timm.data import Mixup
from timm.utils import accuracy, ModelEma
from losses import DistillationLoss
import utils
def t... | 3,508 | 35.175258 | 98 | py |
container | container-main/hubconf.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
from models import *
dependencies = ["torch", "torchvision", "timm"]
| 138 | 22.166667 | 47 | py |
container | container-main/utils.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Misc functions, including distributed helpers.
Mostly copy-paste from torchvision references.
"""
import io
import os
import time
from collections import defaultdict, deque
import datetime
import torch
import torch.distributed as dist
class Smo... | 7,067 | 28.573222 | 94 | py |
container | container-main/datasets.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import os
import json
from torchvision import datasets, transforms
from torchvision.datasets.folder import ImageFolder, default_loader
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.data import create_transform
... | 4,114 | 36.409091 | 105 | py |
container | container-main/models.py | import torch
import torch.nn as nn
from functools import partial
import math
from timm.models.vision_transformer import VisionTransformer, _cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal_, DropPath, to_2tuple
import pdb
__all__ = [
'deit_tiny_patch16_224', 'deit_sma... | 18,794 | 44.071942 | 164 | py |
container | container-main/samplers.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import torch
import torch.distributed as dist
import math
class RASampler(torch.utils.data.Sampler):
"""Sampler that restricts data loading to a subset of the dataset for distributed,
with repeated augmentation.
It ensures that different ... | 2,292 | 37.216667 | 103 | py |
MAgent | MAgent-master/python/magent/builtin/mx_model/base.py | import os
import mxnet as mx
from magent.utility import has_gpu
from magent.model import BaseModel
class MXBaseModel(BaseModel):
def __init__(self, env, handle, name, subclass_name):
"""init a model
Parameters
----------
env: magent.Environment
handle: handle (ctypes.c_in... | 1,779 | 25.567164 | 74 | py |
MAgent | MAgent-master/python/magent/builtin/mx_model/a2c.py | """advantage actor critic"""
import os
import time
import numpy as np
import mxnet as mx
from .base import MXBaseModel
class AdvantageActorCritic(MXBaseModel):
def __init__(self, env, handle, name, eval_obs=None,
batch_size=64, reward_decay=0.99, learning_rate=1e-3,
train_freq... | 10,630 | 34.674497 | 95 | py |
MAgent | MAgent-master/python/magent/builtin/mx_model/dqn.py | import time
import numpy as np
import mxnet as mx
from .base import MXBaseModel
from ..common import ReplayBuffer
from ...utility import has_gpu
class DeepQNetwork(MXBaseModel):
def __init__(self, env, handle, name,
batch_size=64, learning_rate=1e-4, reward_decay=0.99,
train_fr... | 15,724 | 39.424165 | 101 | py |
cwn | cwn-main/mp/cell_mp.py | """
Based on https://github.com/rusty1s/pytorch_geometric/blob/master/torch_geometric/nn/conv/message_passing.py
MIT License
Copyright (c) 2020 Matthias Fey <matthias.fey@tu-dortmund.de>
Copyright (c) 2021 The CWN Project Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this so... | 26,998 | 48 | 110 | py |
cwn | cwn-main/mp/test_layers.py | import torch
import torch.optim as optim
from mp.layers import (
DummyCellularMessagePassing, CINConv, OrientedConv, InitReduceConv, EmbedVEWithReduce)
from data.dummy_complexes import get_house_complex, get_molecular_complex
from torch import nn
from data.datasets.flow import load_flow_dataset
def test_dummy_ce... | 6,243 | 34.276836 | 96 | py |
cwn | cwn-main/mp/cell_mp_inspector.py | """
Based on https://github.com/rusty1s/pytorch_geometric/blob/76d61eaa9fc8702aa25f29dfaa5134a169d0f1f6/torch_geometric/nn/conv/utils/inspector.py
MIT License
Copyright (c) 2020 Matthias Fey <matthias.fey@tu-dortmund.de>
Copyright (c) 2021 The CWN Project Authors
Permission is hereby granted, free of charge, to any ... | 2,143 | 41.88 | 142 | py |
cwn | cwn-main/mp/ring_exp_models.py | import torch
from mp.layers import SparseCINConv
from mp.nn import get_nonlinearity, get_graph_norm
from data.complex import ComplexBatch
from torch.nn import Linear, Sequential
from torch_geometric.nn import GINConv
class RingSparseCIN(torch.nn.Module):
"""
A simple cellular version of GIN employed for Ring... | 4,771 | 35.151515 | 102 | py |
cwn | cwn-main/mp/test_permutation.py | import torch
from data.utils import compute_ring_2complex
from data.perm_utils import permute_graph, generate_permutation_matrices
from data.dummy_complexes import get_mol_testing_complex_list, convert_to_graph
from data.complex import ComplexBatch
from mp.models import SparseCIN
def test_sparse_cin0_perm_invariance_... | 1,983 | 52.621622 | 127 | py |
cwn | cwn-main/mp/molec_models.py | import torch
import torch.nn.functional as F
from torch.nn import Linear, Embedding, Sequential, BatchNorm1d as BN
from torch_geometric.nn import JumpingKnowledge, GINEConv
from mp.layers import InitReduceConv, EmbedVEWithReduce, OGBEmbedVEWithReduce, SparseCINConv, CINppConv
from ogb.graphproppred.mol_encoder import ... | 26,185 | 42.140033 | 106 | py |
cwn | cwn-main/mp/test_models.py | import torch
import pytest
import itertools
from data.complex import ComplexBatch
from data.dummy_complexes import get_testing_complex_list
from mp.models import CIN0, EdgeCIN0, SparseCIN
from data.data_loading import DataLoader, load_dataset
def test_cin_model_with_batching():
"""Check this runs without errors ... | 9,019 | 37.712446 | 99 | py |
cwn | cwn-main/mp/layers.py | import torch
from typing import Any, Callable, Optional
from torch import Tensor
from mp.cell_mp import CochainMessagePassing, CochainMessagePassingParams
from torch_geometric.nn.inits import reset
from torch.nn import Linear, Sequential, BatchNorm1d as BN, Identity
from data.complex import Cochain
from torch_scatter ... | 26,386 | 43.422559 | 130 | py |
cwn | cwn-main/mp/nn.py | import torch
import torch.nn.functional as F
from torch_geometric.nn import global_mean_pool, global_add_pool
from torch.nn import BatchNorm1d as BN, LayerNorm as LN, Identity
def get_nonlinearity(nonlinearity, return_module=True):
if nonlinearity == 'relu':
module = torch.nn.ReLU
function = F.rel... | 2,030 | 32.295082 | 101 | py |
cwn | cwn-main/mp/models.py | import torch
import torch.nn.functional as F
from torch.nn import Linear, Sequential, BatchNorm1d as BN
from torch_geometric.nn import JumpingKnowledge
from mp.layers import (
CINConv, EdgeCINConv, SparseCINConv, CINppConv,DummyCellularMessagePassing, OrientedConv)
from mp.nn import get_nonlinearity, get_pooling_f... | 27,151 | 40.015106 | 102 | py |
cwn | cwn-main/mp/test_orientation.py | import torch
import numpy as np
from data.datasets.flow import load_flow_dataset
from mp.models import EdgeOrient, EdgeMPNN
from mp.layers import OrientedConv
from data.complex import CochainBatch
from data.data_loading import DataLoader
from data.datasets.flow_utils import build_cochain
def generate_oriented_flow_p... | 5,926 | 39.047297 | 107 | py |
cwn | cwn-main/mp/graph_models.py | """
Code based on https://github.com/rusty1s/pytorch_geometric/blob/master/benchmark/kernel/gin.py
Copyright (c) 2020 Matthias Fey <matthias.fey@tu-dortmund.de>
Copyright (c) 2021 The CWN Project Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated docum... | 10,168 | 37.086142 | 96 | py |
cwn | cwn-main/mp/test_molec_models.py | import torch
import itertools
import pytest
from data.complex import ComplexBatch
from data.dummy_complexes import get_testing_complex_list
from mp.molec_models import EmbedSparseCIN, OGBEmbedSparseCIN, EmbedSparseCINNoRings, EmbedGIN
from data.data_loading import DataLoader, load_dataset
def test_zinc_sparse_cin0_m... | 11,149 | 38.122807 | 102 | py |
cwn | cwn-main/mp/test_cell_mp.py | import pytest
import torch
from data.helper_test import check_edge_index_are_the_same, check_edge_attr_are_the_same
from mp.cell_mp import CochainMessagePassing
from torch_geometric.nn.conv import MessagePassing
from data.dummy_complexes import (get_square_dot_complex, get_house_complex,
... | 13,576 | 49.285185 | 180 | py |
cwn | cwn-main/data/perm_utils.py | import torch
import numpy as np
from scipy import sparse as sp
from torch_geometric.data import Data
def permute_graph(graph: Data, P: np.ndarray) -> Data:
# TODO: support edge features and their permutation
assert graph.edge_attr is None
# Check validity of permutation matrix
n = graph.x.size(0)
... | 2,177 | 29.25 | 110 | py |
cwn | cwn-main/data/test_data.py | import torch
from data.dummy_complexes import get_house_complex
def test_up_and_down_feature_extraction_on_house_complex():
house_complex = get_house_complex()
v_cochain_params = house_complex.get_cochain_params(dim=0)
v_up_attr = v_cochain_params.kwargs['up_attr']
expected_v_up_attr = torch.tensor(... | 2,318 | 41.163636 | 100 | py |
cwn | cwn-main/data/helper_test.py | import itertools
import torch
import networkx as nx
from torch_geometric.utils import convert
from torch_geometric.data import Data
def check_edge_index_are_the_same(upper_index, edge_index):
"""Checks that two edge/cell indexes are the same."""
# These two tensors should have the same content but in differe... | 8,463 | 41.532663 | 98 | py |
cwn | cwn-main/data/data_loading.py | """
Code is adapted from https://github.com/rusty1s/pytorch_geometric/blob/6442a6e287563b39dae9f5fcffc52cd780925f89/torch_geometric/data/dataloader.py
Copyright (c) 2020 Matthias Fey <matthias.fey@tu-dortmund.de>
Copyright (c) 2021 The CWN Project Authors
Permission is hereby granted, free of charge, to any person ob... | 14,860 | 56.378378 | 146 | py |
cwn | cwn-main/data/tu_utils.py | """
Based on code from https://github.com/weihua916/powerful-gnns/blob/master/util.py
MIT License
Copyright (c) 2021 Weihua Hu
Copyright (c) 2021 The CWN Project Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), ... | 8,611 | 34.883333 | 119 | py |
cwn | cwn-main/data/utils.py | import graph_tool as gt
import graph_tool.topology as top
import numpy as np
import torch
import gudhi as gd
import itertools
import networkx as nx
from tqdm import tqdm
from data.complex import Cochain, Complex
from typing import List, Dict, Optional, Union
from torch import Tensor
from torch_geometric.typing import ... | 23,431 | 41.915751 | 120 | py |
cwn | cwn-main/data/complex.py | """
Copyright (c) 2020 Matthias Fey <matthias.fey@tu-dortmund.de>
Copyright (c) 2021 The CWN Project Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without ... | 30,723 | 41.145405 | 110 | py |
cwn | cwn-main/data/test_tu_utils.py | import pytest
import os
import numpy as np
import torch
import random
from data.tu_utils import get_fold_indices, load_data, S2V_to_PyG
from torch_geometric.utils import degree
from definitions import ROOT_DIR
@pytest.fixture
def imdbbinary_graphs():
data, num_classes = load_data(os.path.join(ROOT_DIR, 'datasets'... | 3,720 | 32.827273 | 111 | py |
cwn | cwn-main/data/test_batching.py | import torch
import pytest
import itertools
from data.dummy_complexes import (get_house_complex, get_square_complex, get_pyramid_complex,
get_square_dot_complex, get_kite_complex)
from data.complex import ComplexBatch
from data.dummy_complexes import get_testing_complex_list
from data.data_loading import DataLoad... | 46,797 | 43.065913 | 201 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.