repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
AutoCO | AutoCO-main/exp_public/adult/data/process.py | import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
data1 = pd.read_csv("./adult.data",header=None)
data2 = pd.read_csv("./adult.test",header=None)
data = pd.concat([data1, data2], axis=0)
data.columns = ["age", "workclass", "fnlwgt", "ed... | 1,767 | 44.333333 | 154 | py |
AutoCO | AutoCO-main/exp_public/adult/simulate/utils.py | import numpy as np
import pandas as pd
import os
import os.path
import sys
import shutil
import torch
import torch.nn as nn
import torch.utils
from sklearn.preprocessing import StandardScaler
from sklearn.feature_extraction import DictVectorizer
from sklearn.utils import shuffle
from torch.utils.data import Dataset, Da... | 4,315 | 36.206897 | 126 | py |
AutoCO | AutoCO-main/exp_public/adult/simulate/models.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
import utils
import time
PRIMITIVES_BINARY = ['plus', 'multiply', 'max', 'min', 'concat']
PRIMITIVES_NAS = [0, 2, 4, 8, 16]
SPACE_NAS = pow(len(PRIMITIVES_NAS), 5)
OPS = {
'plus': lambda p, q: ... | 29,058 | 42.962179 | 165 | py |
AutoCO | AutoCO-main/exp_public/adult/simulate/__init__.py | 0 | 0 | 0 | py | |
AutoCO | AutoCO-main/exp_public/adult/simulate/baseline.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
import utils
from collections import Counter
from torch.distributions.multivariate_normal import MultivariateNormal
PRIMITIVES_BINARY = ['plus', 'multiply', 'max', 'min', 'concat']
PRIMITIVES_NAS =... | 37,292 | 45.909434 | 141 | py |
AutoCO | AutoCO-main/exp_public/adult/simulate/vartional_model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
import utils
import ipdb
PRIMITIVES_BINARY = ['plus', 'multiply', 'max', 'min', 'concat']
PRIMITIVES_NAS = [0, 2, 4, 8, 16]
SPACE_NAS = pow(len(PRIMITIVES_NAS), 5)
OPS = {
'plus': lambda p, q: ... | 55,609 | 50.730233 | 176 | py |
AutoCO | AutoCO-main/exp_public/adult/simulate/train.py | import numpy as np
import time
def train(train_queue, model, optimizer, arch_optimizer, logging):
rewards_all = []
losses_all = []
for step, features in enumerate(train_queue):
rewards = model.recommend(features)
rewards_all.append(rewards)
losses = model.step(optimizer, arch_optimizer, step)
losses_all.app... | 635 | 34.333333 | 71 | py |
gae | gae-master/setup.py | from setuptools import setup
from setuptools import find_packages
setup(name='gae',
version='0.0.1',
description='Implementation of (Variational) Graph Auto-Encoders in Tensorflow',
author='Thomas Kipf',
author_email='thomas.kipf@gmail.com',
url='https://tkipf.github.io',
download_u... | 733 | 30.913043 | 86 | py |
gae | gae-master/gae/initializations.py | import tensorflow as tf
import numpy as np
def weight_variable_glorot(input_dim, output_dim, name=""):
"""Create a weight variable with Glorot & Bengio (AISTATS 2010)
initialization.
"""
init_range = np.sqrt(6.0 / (input_dim + output_dim))
initial = tf.random_uniform([input_dim, output_dim], minval... | 446 | 36.25 | 76 | py |
gae | gae-master/gae/preprocessing.py | import numpy as np
import scipy.sparse as sp
def sparse_to_tuple(sparse_mx):
if not sp.isspmatrix_coo(sparse_mx):
sparse_mx = sparse_mx.tocoo()
coords = np.vstack((sparse_mx.row, sparse_mx.col)).transpose()
values = sparse_mx.data
shape = sparse_mx.shape
return coords, values, shape
def ... | 4,057 | 35.232143 | 104 | py |
gae | gae-master/gae/input_data.py | import numpy as np
import sys
import pickle as pkl
import networkx as nx
import scipy.sparse as sp
def parse_index_file(filename):
index = []
for line in open(filename):
index.append(int(line.strip()))
return index
def load_data(dataset):
# load the data: x, tx, allx, graph
names = ['x',... | 1,432 | 33.119048 | 83 | py |
gae | gae-master/gae/model.py | from gae.layers import GraphConvolution, GraphConvolutionSparse, InnerProductDecoder
import tensorflow as tf
flags = tf.app.flags
FLAGS = flags.FLAGS
class Model(object):
def __init__(self, **kwargs):
allowed_kwargs = {'name', 'logging'}
for kwarg in kwargs.keys():
assert kwarg in all... | 4,738 | 39.504274 | 105 | py |
gae | gae-master/gae/layers.py | from gae.initializations import *
import tensorflow as tf
flags = tf.app.flags
FLAGS = flags.FLAGS
# global unique layer ID dictionary for layer name assignment
_LAYER_UIDS = {}
def get_layer_uid(layer_name=''):
"""Helper function, assigns unique layer IDs
"""
if layer_name not in _LAYER_UIDS:
_... | 4,046 | 32.446281 | 107 | py |
gae | gae-master/gae/__init__.py | from __future__ import print_function
from __future__ import division
| 70 | 22.666667 | 37 | py |
gae | gae-master/gae/train.py | from __future__ import division
from __future__ import print_function
import time
import os
# Train on CPU (hide GPU) due to memory constraints
os.environ['CUDA_VISIBLE_DEVICES'] = ""
import tensorflow as tf
import numpy as np
import scipy.sparse as sp
from sklearn.metrics import roc_auc_score
from sklearn.metrics ... | 5,635 | 32.547619 | 103 | py |
gae | gae-master/gae/optimizer.py | import tensorflow as tf
flags = tf.app.flags
FLAGS = flags.FLAGS
class OptimizerAE(object):
def __init__(self, preds, labels, pos_weight, norm):
preds_sub = preds
labels_sub = labels
self.cost = norm * tf.reduce_mean(tf.nn.weighted_cross_entropy_with_logits(logits=preds_sub, targets=labe... | 1,962 | 44.651163 | 144 | py |
malfoy | malfoy-master/setup.py | from setuptools import setup, find_packages
setup(
name='v2x',
version='0.1',
author='j80055002',
packages=find_packages(),
install_requires=[
'numpy',
'mesa'
]
) | 203 | 16 | 43 | py |
malfoy | malfoy-master/run.py | # -*- coding: utf-8 -*-
from v2x.config.config import (PSTATS_FILE,LOGS_DIR,
RESOURCE_SITE_PARAMS as rsp)
from v2x.utils.common_utils import openFiles,closeFiles
from v2x.solutions.v2x import V2XModel
from v2x.utils.graphic_utils import Graphics
import cProfile
import pstats
import os,sys... | 4,206 | 34.957265 | 84 | py |
malfoy | malfoy-master/output.py | # -*- coding: utf-8 -*-
from v2x.config.config import (LOGS_DIR, PRICE_MODEL_PARAMS as pmp,
CURIOUS_MODEL_PARAMS as cmp)
from v2x.utils.graphic_utils import Graphics
from v2x.utils.name_utils import ColumnHead as ch
import numpy as np
import pandas as pd
pd.set_option('display.max_columns... | 48,341 | 41.59207 | 92 | py |
malfoy | malfoy-master/v2x/__init__.py | 0 | 0 | 0 | py | |
malfoy | malfoy-master/v2x/config/config.py | # -*- coding: utf-8 -*-
import os
import sys
import torch
torch.set_num_threads(1)
ROOT_DIR = os.path.normpath(os.path.join(
os.path.dirname(os.path.realpath(__file__)), '../..'))
LOGS_DIR = os.path.join(ROOT_DIR, 'logs')
RESOURCES_DIR = os.path.join(ROOT_DIR, 'resources')
MODEL... | 13,031 | 50.920319 | 80 | py |
malfoy | malfoy-master/v2x/config/__init__.py | 0 | 0 | 0 | py | |
malfoy | malfoy-master/v2x/solutions/price_model_curious.py | # -*- coding: utf-8 -*-
import os
import numpy as np
import torch
from torch import tensor,nn
from torch.autograd import Variable
torch.autograd.set_detect_anomaly(True)
from torch.nn import functional as F
from torch.distributions.multivariate_normal import MultivariateNormal
from ..config.config import (PRICE_MODEL_P... | 58,987 | 42.373529 | 106 | py |
malfoy | malfoy-master/v2x/solutions/v2x.py | # -*- coding: utf-8 -*-
from ..utils.common_utils import CommonUtils as utCom
from ..supports.data import (ServiceType,ServiceAmount,ServiceProposal,
ResourceSiteDistance,SiteType,BidStatus,BidState,
BidFailureReason as bfr,QoSType,Task,DefaultProfile,
ResourceName,Resour... | 153,617 | 46.47157 | 151 | py |
malfoy | malfoy-master/v2x/solutions/__init__.py | 0 | 0 | 0 | py | |
malfoy | malfoy-master/v2x/solutions/attention.py | # -*- coding: utf-8 -*-
import torch
from torch import nn,optim,tensor
from torch.nn import functional as F
from ..config.config import (PRICE_MODEL_PARAMS as pmp,DEVICE)
class EncoderRNN(nn.Module):
max_length = pmp.batch_size
def __init__(self, input_size, hidden_size=128):
super().__init__()
... | 5,674 | 39.827338 | 83 | py |
malfoy | malfoy-master/v2x/supports/data.py | # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from itertools import combinations,product
import sys,os
#import xml.etree.ElementTree as et
from lxml import etree
from ..utils.common_utils import CommonUtils as utCom
from ..config.config import (LOGS_DIR,
RESOURCE_PARAMS a... | 26,138 | 39.029096 | 111 | py |
malfoy | malfoy-master/v2x/supports/__init__.py | 0 | 0 | 0 | py | |
malfoy | malfoy-master/v2x/utils/name_utils.py | # -*- coding: utf-8 -*-
class ColumnHead():
ATT = 'D2+R_2000'
CUR = 'CUR'
LEARNED = 'D2+R_1'
RANDOM = 'RIAL'
ACTORLOSS = 'actorLoss'
ADMITTED = 'admitted'
ADMITTEDRATE = 'totalAcceptRatio'
ADMITTEDRATEBYTIME = 'admitted r... | 3,805 | 37.06 | 123 | py |
malfoy | malfoy-master/v2x/utils/common_utils.py | # -*- coding: utf-8 -*-
import re
from ..config.config import FILES
class CommonUtils():
def listClassVariables(clazz,text='__',include=False):
pattern = re.compile(text)
if include:
elements = [clazz.__dict__[variable] for variable
in clazz.__dict__.keys(... | 2,624 | 35.971831 | 84 | py |
malfoy | malfoy-master/v2x/utils/__init__.py | 0 | 0 | 0 | py | |
malfoy | malfoy-master/v2x/utils/graphic_utils.py | # -*- coding: utf-8 -*-
from ..config.config import (GRAPH_DIR, MDL_PARAMS as mp,
RESOURCE_SITE_PARAMS as rsp,
VEHICLE_PARAMS as vp,
PRICE_MODEL_PARAMS as pmp)
from ..supports.data import TraceData
from ..utils.name_utils import Col... | 44,748 | 43.749 | 115 | py |
ESSENCE | ESSENCE-main/essence/essence.py | """
Copyright (C) 2022, Takafumi Tsukui
E-mail: tsukuitk23@gmail.com
Updated versions of the software are available from my web page
https://sites.google.com/view/takafumitk/home?authuser=0
If you have found this software useful for your research,
I would appreciate an acknowledgement to the u... | 21,578 | 44.334034 | 207 | py |
ESSENCE | ESSENCE-main/essence/__init__.py | __version__ = "0.0.1"
| 22 | 10.5 | 21 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/tools/merge_qrels.py | from utils import load_from_trec
import argparse
import torch
import csv
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--scores_path", type=str)
parser.add_argument("--qrels_path", type=str)
parser.add_argument("--save_path", type=str)
parser.add_argument("run"... | 1,581 | 28.296296 | 73 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/tools/transform.py | # coding:utf-8
import torch
import argparse
import os
import tqdm
import copy
def transform_new_model(model_hf, layer_num):
model_new = {}
cnt = 0
for i in range(layer_num):
# encoder
target_k = "encoder.blocks.{}.self_attn.self_attn.project.weight".format(i)
source = [
... | 10,433 | 34.610922 | 88 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/tools/utils.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import csv
import json
import warnings
from dataclasses import dataclass
from typing import Dict, List
import datasets
import torch
from transformers import PreTrainedTokenizer
@dataclass
class SimpleTrainPreProcessor:
query_file: str
collection... | 7,762 | 31.894068 | 134 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/tools/build_hn.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
from utils import SimpleTrainPreProcessor as TrainPreProcessor
from argparse import ArgumentParser
from transformers import AutoTokenizer
import os
import random
from tqdm import tqdm
from datetime import datetime
from multiprocessing import Pool
def lo... | 3,844 | 33.026549 | 87 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/tools/get_docs.py | from utils import load_from_trec
import argparse
import csv
import json
import os
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--collection", type=str, required=False)
parser.add_argument("--ra_name", type=str, required=False)
parser.add_argument("--FiD", action="s... | 1,972 | 29.828125 | 86 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/tools/gather_result_MMLU.py | import argparse
import os
import csv
import numpy as np
subcategories_mapping = {
"abstract_algebra": ["math"],
"anatomy": ["health"],
"astronomy": ["physics"],
"business_ethics": ["business"],
"clinical_knowledge": ["health"],
"college_biology": ["biology"],
"college_chemistry": ["chemistr... | 6,104 | 31.822581 | 104 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/tools/ds_fix/engine.py | '''
Copyright 2019 The Microsoft DeepSpeed Team
'''
import os
import time
import torch
import warnings
import torch.distributed as dist
from torch.nn.modules import Module
from torch.distributed.distributed_c10d import _get_global_rank
from tensorboardX import SummaryWriter
from deepspeed.runtime.zero.stage2 import ... | 62,693 | 40.740346 | 227 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/tools/ds_fix/stage1.py | import math
import torch
import torch.distributed as dist
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from collections import defaultdict
from deepspeed.runtime.zero.utils import _initialize_parameter_parallel_groups
from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossSc... | 52,782 | 45.79344 | 155 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/InstructGPT/run_PopQA.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from tqdm import tqdm
import argparse
import os
import time
import json
import torch
import random
import numpy as np
import pandas as pd
import openai
openai.api_key = "YOUR_API_KEY"
seed = 633
torch.backends.cudnn.deterministic = True
random.seed(seed)
np.random.seed(seed)... | 18,470 | 34.521154 | 211 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/InstructGPT/run_MMLU.py | from promptsource.templates import TemplateCollection
from tqdm import tqdm
import argparse
import openai
import json
import time
import numpy as np
import os
openai.api_key = "YOUR_API_KEY"
choices = ["A", "B", "C", "D"]
def softmax(x):
z = x - max(x)
numerator = np.exp(z)
denominator = np.sum(numerator... | 4,880 | 27.881657 | 149 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/arguments.py | # coding=utf-8
"""argparser configuration"""
import argparse
import os
import torch
import deepspeed
def add_model_config_args(parser: argparse.ArgumentParser):
"""Model arguments"""
group = parser.add_argument_group("model", "model configuration")
group.add_argument(
"--model-config",
... | 15,323 | 29.344554 | 110 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/learning_rates.py | # coding=utf-8
"""PyTorch DataLoader for TFRecords"""
import torch
from torch.optim.lr_scheduler import _LRScheduler
import math
class AnnealingLR(_LRScheduler):
"""Anneals the learning rate from start to zero along a cosine curve."""
DECAY_STYLES = ['linear', 'cosine', 'exponential', 'constant', 'None', 'n... | 2,974 | 40.901408 | 176 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/utils.py | # coding=utf-8
"""Utilities for logging and serialization"""
import os
import random
import numpy as np
import torch
from fp16 import FP16_Optimizer
import mpu
import deepspeed
from apex.optimizers import FusedAdam as Adam
from fp16 import FP16_Module
from fp16 import FP16_Optimizer
from learning_rates import Annea... | 13,650 | 35.209549 | 126 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/generation_utils.py | # coding=utf-8
import os
import torch
import torch.nn.functional as F
from collections import defaultdict
from tokenization_t5 import EncDecTokenizer
class BeamHypotheses(object):
def __init__(
self, num_beams, max_length, length_penalty, early_stopping, tokenizer=None
):
"""
Initia... | 26,394 | 36.439716 | 139 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/train_t0.py | # coding=utf-8
"""Training Enc-Dec"""
import os
import torch
import json
import numpy as np
from arguments import get_args
from data_utils.T0Datasets import T0Dataset
from data_utils.data_config import (
DATA_GROUP_CONFIG,
DATA_NO_EVAL,
DATA_NO_VALID,
DATA_NO_TRAIN,
DATA_EVAL_GEN,
DATA_RETRI... | 36,843 | 34.022814 | 104 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/metrics.py | from sklearn.metrics import f1_score
import collections
import numpy as np
from generation_metrics import Metric
from t5.evaluation import metrics
def popqa(all_labels_real, all_preds_real):
assert len(all_labels_real) == len(all_preds_real)
accuracy = []
for possible_answers, pred in zip(all_labels_real, ... | 5,252 | 31.226994 | 110 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/samplers.py | # coding=utf-8
"""Batch samplers that work with either random or sequential data samplers."""
import torch
from torch.utils import data
class RandomSampler(data.sampler.Sampler):
"""Based off of pytorch RandomSampler and DistributedSampler. Essentially
a RandomSampler, but this class lets the user set an e... | 5,911 | 38.677852 | 91 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/tokenization_t5.py | # coding=utf-8
""" Tokenization class for model T5. Taken from Huggingface Transformers"""
import os
import re
import warnings
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
PRETRAINED_VOCAB_FILES_MAP ... | 9,482 | 41.334821 | 164 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/generation_metrics.py | # coding=utf-8
import warnings
import numpy as np
from typing import List
from collections import Counter
from nltk.translate.bleu_score import corpus_bleu, SmoothingFunction
from copy import deepcopy
class Ngrams(object):
"""
Ngrams datastructure based on `set` or `list`
depending in `exclusive`... | 7,988 | 32.426778 | 100 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/fp16/fp16util.py | # coding=utf-8
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
import mpu
class tofp16(nn.Module):
"""
Utility module that implements::
def forward(self, input):
return input.half()
"""... | 7,072 | 35.647668 | 337 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/fp16/__init__.py | # coding=utf-8
from .fp16util import (
BN_convert_float,
network_to_half,
prep_param_lists,
model_grads_to_master_grads,
master_params_to_model_params,
tofp16,
to_python_float,
clip_grad_norm,
convert_module,
convert_network,
FP16Model,
)
from .fp16 import *
from .loss_scal... | 332 | 16.526316 | 34 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/fp16/loss_scaler.py | import torch
import mpu
# item() is a recent addition, so this helps with backward compatibility.
def to_python_float(t):
if hasattr(t, 'item'):
return t.item()
else:
return t[0]
class LossScaler:
"""
Class that manages a static loss scale. This class is intended to interact with
... | 9,150 | 40.035874 | 326 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/fp16/fp16.py | # coding=utf-8
"""Stable version of apex FP16 Optimizer"""
import torch
from torch import nn
from torch.autograd import Variable
from torch.nn.parameter import Parameter
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from .loss_scaler import DynamicLossScaler, LossScaler
from .fp16util impo... | 31,108 | 49.338188 | 437 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/mappings.py | # coding=utf-8
import torch
from .initialize import get_model_parallel_group
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""All-reduce the the input tensor across model parallel group."""
group = get_model_parallel_group()
# Bypass the function if we are using only 1 GPU.
i... | 3,527 | 26.138462 | 76 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/initialize.py | # coding=utf-8
"""Model and data parallel groups."""
import torch
from .utils import ensure_divisibility
# Model parallel group that the current rank belongs to.
_MODEL_PARALLEL_GROUP = None
# Data parallel group that the current rank belongs to.
_DATA_PARALLEL_GROUP = None
def initialize_model_parallel(model_... | 4,274 | 33.475806 | 77 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/cross_entropy.py | # coding=utf-8
import torch
from .initialize import get_model_parallel_group
from .initialize import get_model_parallel_rank
from .initialize import get_model_parallel_world_size
from .utils import VocabUtility
class _VocabParallelCrossEntropy(torch.autograd.Function):
@staticmethod
def forward(ctx, voca... | 9,078 | 41.425234 | 101 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/utils.py | # coding=utf-8
import torch
def ensure_divisibility(numerator, denominator):
"""Ensure that numerator is divisible by the denominator."""
assert numerator % denominator == 0, '{} is not divisible by {}'.format(
numerator, denominator)
def divide(numerator, denominator):
"""Ensure that numerat... | 2,102 | 34.644068 | 80 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/data.py | # coding=utf-8
import torch
from .initialize import get_model_parallel_group
from .initialize import get_model_parallel_rank
from .initialize import get_model_parallel_src_rank
_MAX_DATA_DIM = 4
def _check_data_types(keys, data, target_dtype):
"""Check that all the keys have the same target data type."""
... | 3,409 | 31.47619 | 80 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/grads.py | # coding=utf-8
# Parts of the code here are adapted from PyTorch
# repo: https://github.com/pytorch/pytorch
import torch
from torch._six import inf
from .initialize import get_model_parallel_group
from .initialize import get_model_parallel_rank
def clip_grad_norm(parameters, max_norm, norm_type=2):
"""Clips... | 2,406 | 37.206349 | 79 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/layers.py | # coding=utf-8
# Parts of the code here are adapted from PyTorch
# repo: https://github.com/pytorch/pytorch
import math
import torch
import torch.nn.functional as F
import torch.nn.init as init
from torch.nn.parameter import Parameter
from apex.normalization.fused_layer_norm import FusedLayerNorm as LayerNorm
f... | 12,967 | 39.652038 | 80 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/random.py | # coding=utf-8
#Modified by Samyam Rajbhandari
#Used to partition the activations stored for backward propagation
#Therefore reduces the memory consumption
# Parts of the code here are adapted from PyTorch
# repo: https://github.com/pytorch/pytorch
import contextlib
import torch.distributed as dist
import torch
fro... | 14,040 | 36.442667 | 151 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/transformer_enc_dec.py | from audioop import cross
import math
from numpy.lib.function_base import insert
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
# from apex.normalization.fused_layer_norm import FusedLayerNorm as LayerNorm
from .initialize import get_model_parallel_world_size
from .lay... | 35,723 | 41.427553 | 186 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/mpu/__init__.py | # coding=utf-8
"""Model parallel utility interface."""
from .cross_entropy import vocab_parallel_cross_entropy
from .cross_entropy import parallel_soft_cross_entropy_loss
from .data import broadcast_data
from .grads import clip_grad_norm
from .initialize import destroy_model_parallel
from .initialize import get_d... | 1,406 | 32.5 | 59 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/model/enc_dec_modeling.py | import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
import mpu
from .configuration_enc_dec import EncDecConfig
def init_method_normal(std):
"""Init method based on normal distribution.
This is only used for embeddings. The transformer has its
own initializer.
"""
def ... | 7,115 | 35.492308 | 186 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/model/distributed.py | # coding=utf-8
import torch
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
import torch.distributed as dist
from torch.nn.modules import Module
from torch.autograd import Variable
import mpu
class DistributedDataParallel(Module):
def __init__(self, module):
super(DistributedD... | 4,286 | 42.30303 | 103 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/model/__init__.py | # coding=utf-8
from .distributed import *
from .enc_dec_modeling import EncDecModel
from .enc_dec_modeling import enc_dec_get_params_for_weight_decay_optimization
from .enc_dec_modeling import enc_dec_get_params_for_prompt_optimization
from .configuration_enc_dec import EncDecConfig
| 287 | 27.8 | 78 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/model/configuration_enc_dec.py | """ enc_dec model configuration """
import json
import os
import copy
from typing import Any, Dict, Tuple, Union
class EncDecConfig(object):
def __init__(
self,
d_model=768,
d_kv=64,
d_ff=256,
num_layers=12,
num_decoder_layers=12,
num_heads=12,
relat... | 2,881 | 34.146341 | 103 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/data_utils/__init__.py | from .data_config import DATA_CONFIG
from .postprocess import ANSWER_POST_FN
| 77 | 25 | 39 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/data_utils/data_config.py | import os
BASE_DATA_DIR = "data"
def string_to_float(preds, labels):
return [float(p) for p in preds], [float(l) for l in labels]
DATA_GROUP_CONFIG = {
"MCQA": [
"dream",
"quail",
"quartz",
"social_i_qa",
"wiqa",
"cosmos_qa",
"qasc",
"quarel",... | 22,045 | 29.035422 | 88 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/data_utils/T0Datasets.py | import json
import re
import os
import torch
import math
import numpy as np
import pickle
from torch.utils.data import Dataset
from utils import print_rank_0, save_rank_0
from tokenization_t5 import EncDecTokenizer
from .data_config import DATA_GROUP_CONFIG, DATA_CONFIG
import datasets
from promptsource.templates impor... | 21,571 | 38.29326 | 122 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/LM/Flan-T5/data_utils/postprocess.py | OPTION_POST_FN = {
("imdb", "Negation template for positive and negative"): lambda x: ["negative review.", "positive review."],
("imdb_pseudo", "Negation template for positive and negative"): lambda x: ["negative review.", "positive review."],
("wiqa", "which_of_the_following_is_the_supposed_perturbation"):... | 814 | 66.916667 | 210 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/arguments.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
from dataclasses import dataclass, field
from typing import Optional, List
from transformers import TrainingArguments
@dataclass
class ModelArguments:
model_name_or_path: str = field(
metadata={
"help": "Path to pretrained model o... | 8,692 | 33.496032 | 215 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/qa_utils.py | import copy
import logging
import re
import unicodedata
import regex
logger = logging.getLogger(__name__)
class Tokens(object):
"""A class to represent a list of tokenized text."""
TEXT = 0
TEXT_WS = 1
SPAN = 2
POS = 3
LEMMA = 4
NER = 5
def __init__(self, data, annotators, opts=None... | 6,346 | 28.52093 | 77 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/loss.py | import torch
from torch import Tensor
from torch.nn import functional as F
from torch import distributed as dist
class SimpleContrastiveLoss:
def __call__(self, x: Tensor, y: Tensor, target: Tensor = None, reduction: str = 'mean'):
if target is None:
target_per_qry = y.size(0) // x.size(0)
... | 2,694 | 35.418919 | 118 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/utils.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import csv
import json
import warnings
from dataclasses import dataclass
from typing import Dict, List
import datasets
import torch
from transformers import PreTrainedTokenizer
try:
from opendelta import BitFitModel, AdapterModel, PrefixModel, LoraMo... | 8,668 | 32.087786 | 134 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/data_augmentation_strategy.py | import random
from typing import List
class DataAugmentationStrategy:
def augment(self, data: List[int]) -> List[int]:
raise NotImplementedError
def __call__(self, data: List[int]) -> List[int]:
return self.augment(data)
class NullStrategy(DataAugmentationStrategy):
def augment(self, ... | 1,261 | 25.851064 | 71 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/__init__.py | 0 | 0 | 0 | py | |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/trainer/dense_trainer.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import logging
import os
from itertools import repeat
from typing import Any, Dict, List, Optional, Tuple, Union
import datasets
import torch
import torch.distributed as dist
from torch.utils.data import DataLoader
from transformers.file_utils import is_d... | 6,280 | 36.837349 | 111 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/trainer/__init__.py | from .dense_trainer import DRTrainer, GCDenseTrainer
from .reranker_trainer import RRTrainer | 92 | 45.5 | 52 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/trainer/reranker_trainer.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import logging
import os
from typing import Any, Dict, List, Optional, Tuple, Union
import torch
import torch.nn as nn
from transformers.trainer import Trainer
from transformers.trainer_pt_utils import nested_detach
logger = logging.getLogger(__name__)
... | 2,539 | 32.866667 | 96 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/dataset/inference_dataset.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import os
from functools import lru_cache
from typing import List, Union, Callable
from datasets import load_dataset
from torch.utils.data import Dataset, IterableDataset
from transformers import PreTrainedTokenizer
from ..arguments import DataArguments
... | 9,674 | 32.947368 | 138 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/dataset/data_collator.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
from dataclasses import dataclass
from transformers import DataCollatorWithPadding, DefaultDataCollator
@dataclass
class QPCollator(DataCollatorWithPadding):
"""
Wrapper that does conversion from List[Tuple[encode_qry, encode_psg]] to List[qry],... | 2,786 | 29.293478 | 97 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/dataset/train_dataset.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import glob
import logging
import os
import random
from typing import Callable, Dict, List, Union
from datasets import load_dataset
from torch.utils.data import Dataset, IterableDataset
from transformers import BatchEncoding, PreTrainedTokenizer
from ..a... | 11,428 | 34.604361 | 121 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/dataset/beir_dataset.py | import csv
import logging
import os
from transformers import PreTrainedTokenizer
from ..arguments import BEIRDataArguments
from .inference_dataset import InferenceDataset
logger = logging.getLogger(__name__)
def load_beir_qrels(qrels_file):
qrels = {}
with open(qrels_file) as f:
tsvreader = csv.Dic... | 2,840 | 32.821429 | 87 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/dataset/__init__.py | from .beir_dataset import BEIRDataset
from .data_collator import DRInferenceCollator, QPCollator, PairCollator, RRInferenceCollator
from .inference_dataset import StreamJsonlDataset, StreamTsvDataset, MappingJsonlDataset, MappingTsvDataset, InferenceDataset
from .train_dataset import StreamDRTrainDataset, MappingDRTrai... | 425 | 84.2 | 166 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/driver/train_dr.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import logging
import os
import sys
from ..arguments import DataArguments
from ..arguments import DRTrainingArguments as TrainingArguments
from ..arguments import ModelArguments
from ..dataset import QPCollator, StreamDRTrainDataset, MappingDRTrainDataset... | 4,236 | 33.447154 | 133 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/driver/pretrain_dr.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import logging
import os
import sys
from openmatch.arguments import DRPretrainingDataArguments
from openmatch.arguments import DRTrainingArguments as TrainingArguments
from openmatch.arguments import ModelArguments
from openmatch.dataset import QPCollator... | 3,895 | 33.785714 | 133 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/driver/successive_retrieve.py | import logging
import os
import sys
from openmatch.arguments import DataArguments
from openmatch.arguments import InferenceArguments as EncodingArguments
from openmatch.arguments import ModelArguments
from openmatch.dataset import InferenceDataset
from openmatch.modeling import DRModelForInference
from openmatch.retri... | 2,927 | 33.447059 | 109 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/driver/retrieve.py | import logging
import os
import sys
from ..arguments import DataArguments
from ..arguments import InferenceArguments as EncodingArguments
from ..arguments import ModelArguments
from ..dataset import InferenceDataset
from ..modeling import DRModelForInference
from ..retriever import Retriever
from ..utils import save_a... | 3,253 | 35.155556 | 126 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/driver/build_index.py | import logging
import os
from ..arguments import DataArguments
from ..arguments import InferenceArguments as EncodingArguments
from ..arguments import ModelArguments
from ..dataset import InferenceDataset
from ..modeling import DRModelForInference
from ..retriever import Retriever
from ..utils import get_delta_model_c... | 2,993 | 34.223529 | 126 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/driver/rerank.py | import logging
import os
import sys
from openmatch.arguments import DataArguments
from openmatch.arguments import InferenceArguments
from openmatch.arguments import ModelArguments
from openmatch.dataset import InferenceDataset
from openmatch.modeling import RRModel
from openmatch.retriever import Reranker
from openmat... | 3,032 | 31.967391 | 110 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/driver/train_rr.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import logging
import os
import sys
from openmatch.arguments import DataArguments
from openmatch.arguments import RRTrainingArguments as TrainingArguments
from openmatch.arguments import ModelArguments
from openmatch.dataset import PairCollator, StreamRRT... | 3,825 | 32.561404 | 133 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/modeling/reranking_model.py | import copy
import json
import logging
import os
from dataclasses import dataclass
from typing import Dict, Optional
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from transformers import (AutoModel, BatchEncoding, PreTrainedModel,
... | 6,685 | 35.736264 | 119 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/modeling/linear.py | import logging
import os
import json
import torch
import torch.nn as nn
from torch import Tensor
logger = logging.getLogger(__name__)
class LinearHead(nn.Module):
def __init__(
self,
input_dim: int = 768,
output_dim: int = 768,
):
super(LinearHead, self).__init__(... | 1,182 | 29.333333 | 75 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/modeling/dense_retrieval_model.py | # Adapted from Tevatron (https://github.com/texttron/tevatron)
import copy
import importlib
import json
import logging
import os
from dataclasses import dataclass
from typing import Dict, Optional
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch import Ten... | 12,826 | 35.440341 | 98 | py |
Augmentation-Adapted-Retriever | Augmentation-Adapted-Retriever-main/src/Retriever/modeling/__init__.py | from .dense_retrieval_model import DRModel, DRModelForInference, DROutput
from .reranking_model import RRModel, RROutput | 120 | 59.5 | 73 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.