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 |
|---|---|---|---|---|---|---|
Gated-LIF | Gated-LIF-master/data_builder.py | import os
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
from torchvision.datasets import CIFAR10, CIFAR100, ImageFolder
from data.autoaugment import CIFAR10Policy, Cutout
import torch
####################################################
# da... | 10,198 | 43.929515 | 193 | py |
Gated-LIF | Gated-LIF-master/networks_for_ImageNet.py | from blocks import *
from layers import *
from spikingjelly.clock_driven import layer
import numpy as np
init_constrain = 0.2
# for ImageNet
class ResNet_34_stand(nn.Module):
def __init__(self, lif_param:dict, input_size=224, n_class=1000, tunable_lif=False):
super(ResNet_34_stand, self).__init__()
... | 18,535 | 40.00885 | 125 | py |
Gated-LIF | Gated-LIF-master/train.py | import time
import logging
from data_builder import *
import argparse
from networks_for_CIFAR import *
from networks_for_ImageNet import *
from utils import accuracy, AvgrageMeter, save_checkpoint, get_model, create_para_dict, read_param, record_param, deletStrmodule, randomize_gate
import sys
sys.path.append("..")
fro... | 18,871 | 44.474699 | 156 | py |
Gated-LIF | Gated-LIF-master/networks_for_CIFAR.py | from blocks import *
from layers import *
from spikingjelly.clock_driven import layer
import numpy as np
init_constrain = 0.2
# for CIFAR
class CIFARNet(nn.Module):
def __init__(self, lif_param: dict, input_size=32, n_class=100, tunable_lif=False):
super(CIFARNet, self).__init__()
assert input_siz... | 31,509 | 39.76326 | 113 | py |
Gated-LIF | Gated-LIF-master/blocks.py | import torch
import torch.nn as nn
from spikingjelly.clock_driven import layer
from layers import *
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilat... | 16,425 | 36.674312 | 127 | py |
Gated-LIF | Gated-LIF-master/cifar10dvs/smodels.py | import torch
import torch.nn as nn
from layers import *
from spikingjelly.clock_driven.neuron import MultiStepParametricLIFNode, MultiStepLIFNode
from spikingjelly.clock_driven import layer
def conv3x3(in_channels, out_channels):
return nn.Sequential(
layer.SeqToANNContainer(
nn.Conv2d(in_chann... | 17,150 | 39.64218 | 120 | py |
Gated-LIF | Gated-LIF-master/cifar10dvs/utils.py | from collections import defaultdict, deque
import datetime
import time
import torch
import torch.distributed as dist
import errno
import os
class SmoothedValue(object):
"""Track a series of values and provide access to smoothed values over a
window or the global series average.
"""
def __init__(self... | 7,468 | 28.062257 | 94 | py |
Gated-LIF | Gated-LIF-master/cifar10dvs/layers.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
import torch.optim as optim
from spikingjelly.clock_driven.surrogate import sigmoid
torch.pi = torch.acos(torch.zeros(1)).item() * 2
steps = 16
dt = 5
simwin = dt * steps
a = 0.25
Vth = 0.99999 # 阈值电压 V_threshold
aa = Vt... | 13,220 | 41.925325 | 277 | py |
Gated-LIF | Gated-LIF-master/cifar10dvs/train.py | import datetime
import os
import time
import torch
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torchvision.transforms as transforms
from torch.utils.tensorboard import SummaryWriter
import sys
from torch.cuda import amp
import smodels
import argparse
from spikingjelly.clock_driven im... | 12,717 | 36.85119 | 386 | py |
Gated-LIF | Gated-LIF-master/data/autoaugment.py | from PIL import Image, ImageEnhance, ImageOps
import numpy as np
import random
import torch
class Cutout(object):
"""Randomly mask out one or more patches from an image.
Args:
n_holes (int): Number of patches to cut out of each image.
length (int): The length (in pixels) of each square patch.... | 12,613 | 43.259649 | 116 | py |
trlda | trlda-master/code/utils/epydoc.py | """
Post-processing of epydoc generated documentation.
"""
import os
import sys
from glob import glob
# adds MathJax capabilities to documentation
injection = """
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$','$']],
displayMath: [['$$','$$']],
... | 1,282 | 23.207547 | 126 | py |
Model_Emotion | Model_Emotion-main/Model_Emotion-1.0/get_active_neuron.py | import os
from tqdm import tqdm
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset, DataLoader
from transformers import AutoTokenizer
from framework.roberta import RobertaWarp
import argparse
# Define 12 Random Seeds
random_seeds = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 42, 100]
# D... | 4,353 | 37.192982 | 113 | py |
Model_Emotion | Model_Emotion-main/Model_Emotion-1.0/eval_mask_neuron.py | import os
os.environ['HF_HOME'] = './huggingface_cache'
import json
import pickle
import argparse
from tqdm import tqdm
import torch
from transformers import AutoTokenizer
from framework import RobertaForMaskedLMPrompt, get_loader
nlayers = 12
state = 'best'
def get_pred(logits):
_, pred = torch.max(logits.view... | 4,620 | 30.868966 | 114 | py |
Model_Emotion | Model_Emotion-main/Model_Emotion-1.0/train.py | import os
os.environ['HF_HOME'] = './huggingface_cache'
# os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
# os.environ['CUDA_VISIBLE_DEVICES'] = '3'
import torch,gc
gc.collect()
torch.cuda.empty_cache()
import sys
import logging
import argparse
from tqdm import tqdm, trange
import numpy as np
import pandas as pd
import to... | 5,116 | 33.113333 | 117 | py |
Model_Emotion | Model_Emotion-main/Model_Emotion-1.0/gen_mask.py | import torch
import pickle
import numpy as np
import pandas as pd
import argparse
import os
def inverse_mask(mask):
'''
Convert a mask that masks neuron by ranking their importance into a mask that randomly masks neurons.
All 0s get converted into 1s.
Randomly sample the same amount of 1s to c... | 5,776 | 38.568493 | 123 | py |
Model_Emotion | Model_Emotion-main/Model_Emotion-1.0/framework/data_loader.py | import os
import numpy as np
import pandas as pd
from torch.utils.data import Dataset, DataLoader
def get_loader(args, num_workers=8, root='./data', eval_only=False):
train_dataset = RandomSequenceClassificationDataset(args.sentiment, args.random_seed, 'train')
valid_dataset = RandomSequenceClassificationData... | 1,846 | 35.94 | 120 | py |
Model_Emotion | Model_Emotion-main/Model_Emotion-1.0/framework/roberta.py | import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss, MSELoss
from transformers.models.roberta.modeling_roberta import (
RobertaClassificationHead,
RobertaPreTrainedModel,
RobertaModel,
RobertaEmbeddings,
create_position_ids_from_input_ids,
RobertaLMHead
)
from transformer... | 12,203 | 36.666667 | 145 | py |
Model_Emotion | Model_Emotion-main/Model_Emotion-1.0/framework/trainer.py | import os
import copy
import torch
import numpy as np
from tqdm import tqdm, trange
from sklearn.metrics import accuracy_score, f1_score
class Trainer:
def __init__(self, args=None, logger=None, tokenizer=None, model=None, optimizer=None, scheduler=None,
num_labels=None, train_loader=None, val_l... | 4,890 | 34.18705 | 122 | py |
Model_Emotion | Model_Emotion-main/Model_Emotion-2.0-latest/train.py | import os
import sys
import logging
import numpy as np
import torch
from transformers import (
AutoTokenizer,
AdamW,
set_seed,
TrainingArguments,
DataCollatorWithPadding,
default_data_collator,
EvalPrediction
)
from datasets import load_metric
from framework import RobertaForMaskedLMPrompt,... | 2,963 | 28.346535 | 187 | py |
Model_Emotion | Model_Emotion-main/Model_Emotion-2.0-latest/framework/roberta.py | import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss, MSELoss
from transformers.models.roberta.modeling_roberta import (
RobertaClassificationHead,
RobertaPreTrainedModel,
RobertaModel,
RobertaEmbeddings,
create_position_ids_from_input_ids,
RobertaLMHead
)
from transformer... | 12,203 | 36.666667 | 145 | py |
Model_Emotion | Model_Emotion-main/Model_Emotion-2.0-latest/framework/dataset.py | import os
import numpy as np
import pandas as pd
from torch.utils.data import Dataset, DataLoader
from transformers import set_seed
class EmotionDataset(Dataset):
def __init__(self, sentiment, tokenizer, max_length, seed, split, root='../data'):
self.data = []
self.sentiment = sentiment
... | 1,122 | 30.194444 | 137 | py |
Model_Emotion | Model_Emotion-main/Model_Emotion-2.0-latest/framework/trainer.py | import os
import copy
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from transformers import Trainer
from transformers.trainer_pt_utils import nested_detach
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
from .dataset import EmotionDataset
from... | 10,949 | 35.258278 | 148 | py |
UFNRec | UFNRec-main/main.py | from operator import ne
import os
import torch
import argparse
import random
import numpy as np
from model import SASRec
from SASRec_utils import *
from UFN_utils import *
from torch_ema import ExponentialMovingAverage
def str2bool(s):
if s not in {'false', 'true'}:
raise ValueError('Not a valid boolean st... | 7,478 | 40.782123 | 206 | py |
UFNRec | UFNRec-main/SASRec_utils.py | import sys
import copy
import torch
import random
import numpy as np
from collections import defaultdict
from multiprocessing import Process, Queue
# sampler for batch generation
np.random.seed(100)
def random_neq(l, r, s):
t = np.random.randint(l, r)
while t in s:
t = np.random.randint(l, r)
ret... | 7,009 | 29.34632 | 102 | py |
UFNRec | UFNRec-main/model.py | import numpy as np
import torch
import random
class PointWiseFeedForward(torch.nn.Module):
def __init__(self, hidden_units, dropout_rate):
super(PointWiseFeedForward, self).__init__()
self.conv1 = torch.nn.Conv1d(hidden_units, hidden_units, kernel_size=1)
self.dropout1 = torch.nn.Dropout(... | 4,415 | 40.660377 | 107 | py |
UFNRec | UFNRec-main/torch_ema/ema.py | from __future__ import division
from __future__ import unicode_literals
from typing import Iterable, Optional
import weakref
import copy
import contextlib
import torch
# Partially based on:
# https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/python/training/moving_averages.py
class ExponentialMovingAve... | 11,692 | 37.718543 | 99 | py |
NegIoU-PosIoU-Miou | NegIoU-PosIoU-Miou-main/train_ssd512.py | from src.ssd_model import SSD640
from src.res50_backbone import resnet50
import torch
import transform
from my_dataset import NightDataSet
import os
import train_utils.train_eval_utils as utils
from train_utils.coco_utils import get_coco_api_from_dataset
def create_model(num_classes=21, device=torch.device('cpu')):
... | 6,627 | 37.760234 | 116 | py |
NegIoU-PosIoU-Miou | NegIoU-PosIoU-Miou-main/test.py | from src.ssd_model import SSD300
from src.res50_backbone import resnet50
import torch
import transform
from my_dataset import NightDataSet
import os
import train_utils.train_eval_utils as utils
from train_utils.coco_utils import get_coco_api_from_dataset
def create_model(num_classes=21, device=torch.device('cpu')):
... | 4,564 | 36.113821 | 92 | py |
NegIoU-PosIoU-Miou | NegIoU-PosIoU-Miou-main/transform.py | import random
import torchvision.transforms as t
from torchvision.transforms import functional as F
from src.utils import dboxes300_coco, calc_iou_tensor, Encoder
import torch
class Compose(object):
"""组合多个transform函数"""
def __init__(self, transforms):
self.transforms = transforms
def __call__(se... | 6,608 | 32.211055 | 94 | py |
NegIoU-PosIoU-Miou | NegIoU-PosIoU-Miou-main/compute_my_dataset.py | from torchvision import transforms, datasets, models
import numpy as np
from PIL import Image
from my_dataset import NightDataSet
import os
# 计算自己数据集的均值方差
def compute_mean_and_std(dataset):
# 均值计算
mean_r = 0
mean_g = 0
mean_b = 0
for img_id in dataset.ids:
print(img_id)
img_path = o... | 1,567 | 25.576271 | 82 | py |
NegIoU-PosIoU-Miou | NegIoU-PosIoU-Miou-main/predict_test.py | import torch
from draw_box_utils import draw_box
from PIL import Image
import json
import matplotlib.pyplot as plt
from train_ssd512 import create_model
import transform
import time
import cv2
import numpy as np
# get devices
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
# crea... | 2,577 | 29.329412 | 97 | py |
NegIoU-PosIoU-Miou | NegIoU-PosIoU-Miou-main/eval.py | """Adapted from:
@longcw faster_rcnn_pytorch: https://github.com/longcw/faster_rcnn_pytorch
@rbgirshick py-faster-rcnn https://github.com/rbgirshick/py-faster-rcnn
Licensed under The MIT License [see LICENSE for details]
"""
from __future__ import print_function
import torch
import transform
from my_datas... | 15,932 | 35.047511 | 101 | py |
NegIoU-PosIoU-Miou | NegIoU-PosIoU-Miou-main/my_dataset.py | from torch.utils.data import Dataset
import os
import torch
import json
from PIL import Image
from lxml import etree
class NightDataSet(Dataset):
"""读取解析PASCAL VOC2012数据集"""
def __init__(self, night_root, transforms, train_set='train.txt'):
self.root = os.path.join(night_root, "NightData")
s... | 5,654 | 33.272727 | 98 | py |
NegIoU-PosIoU-Miou | NegIoU-PosIoU-Miou-main/src/ssd_model.py | from src.res50_backbone import resnet50
from torch import nn, Tensor
import torch
from torch.jit.annotations import Optional, List, Dict, Tuple, Module
from src.utils import dboxes300_coco, Encoder, PostProcess,calc_iou_tensor,calc_c_tensor,calc_iou_tensor_diag
import torchvision.transforms.functional as func
import nu... | 14,473 | 40.711816 | 130 | py |
NegIoU-PosIoU-Miou | NegIoU-PosIoU-Miou-main/src/utils.py | import os
import numpy as np
from math import sqrt
import itertools
import torch
import torch.nn.functional as F
from torch.jit.annotations import Tuple, List
from torch import nn, Tensor
# This function is from https://github.com/kuangliu/pytorch-ssd.
# def calc_iou_tensor(box1, box2):
# """ Calculation of IoU b... | 24,236 | 35.667171 | 112 | py |
NegIoU-PosIoU-Miou | NegIoU-PosIoU-Miou-main/src/res50_backbone.py | import torch.nn as nn
import torch
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, in_channel, out_channel, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=out_channel,
kern... | 3,890 | 35.027778 | 112 | py |
NegIoU-PosIoU-Miou | NegIoU-PosIoU-Miou-main/train_utils/group_by_aspect_ratio.py | import bisect
from collections import defaultdict
import copy
from itertools import repeat, chain
import math
import numpy as np
import torch
import torch.utils.data
from torch.utils.data.sampler import BatchSampler, Sampler
from torch.utils.model_zoo import tqdm
import torchvision
from PIL import Image
def _repeat... | 7,385 | 35.564356 | 99 | py |
NegIoU-PosIoU-Miou | NegIoU-PosIoU-Miou-main/train_utils/train_eval_utils.py | import math
import sys
import time
import datetime
import pickle
import os
import torch
import errno
from collections import defaultdict, deque
import torch.distributed as dist
from train_utils.coco_utils import get_coco_api_from_dataset
from train_utils.coco_eval import CocoEvaluator
def train_one_epoch(model, optim... | 16,181 | 32.364948 | 95 | py |
NegIoU-PosIoU-Miou | NegIoU-PosIoU-Miou-main/train_utils/coco_utils.py | import torch
import torchvision
import torch.utils.data
from pycocotools.coco import COCO
def convert_to_coco_api(ds):
coco_ds = COCO()
# annotation IDs need to start at 1, not 0
ann_id = 1
dataset = {'images': [], 'categories': [], 'annotations': []}
categories = set()
for img_idx in range(le... | 2,199 | 35.065574 | 83 | py |
NegIoU-PosIoU-Miou | NegIoU-PosIoU-Miou-main/train_utils/coco_eval.py | import json
import tempfile
import numpy as np
import copy
import time
import torch
import torch._six
from pycocotools.cocoeval import COCOeval
from pycocotools.coco import COCO
import pycocotools.mask as mask_util
from collections import defaultdict
from train_utils import train_eval_utils as utils
class CocoEva... | 12,364 | 33.635854 | 107 | py |
IsingBornMachine | IsingBornMachine-master/auxiliary_functions.py | ## @package auxiliary_functions some additional useful functions
#
# A collection of sever additional function useful during the running of the code.
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
from pyquil.api import get_qc
import torch
import sys
def AllBinaryStrings(N_qubits)... | 10,362 | 34.611684 | 111 | py |
IsingBornMachine | IsingBornMachine-master/feydy_sinkhorn.py | #--------------------------------------------------------------------------------------------
# Simplistic implementation of the Sinkhorn divergences, with a vanilla PyTorch backend
#--------------------------------------------------------------------------------------------
import numpy as np
import torch
#######... | 4,062 | 43.163043 | 128 | py |
IsingBornMachine | IsingBornMachine-master/sinkhorn_functions.py | import numpy as np
from auxiliary_functions import L2Norm,SampleListToArray
from file_operations_in import DataImport
import feydy_sinkhorn as feydy_sink
import torch
import auxiliary_functions as aux
'''
This function computes the Sinkhorn Cost function, and its gradient, following the Method of:
Interpolatin... | 4,586 | 54.26506 | 184 | py |
Paddle | Paddle-master/python/paddle/trainer/config_parser.py | # Copyright (c) 2016 PaddlePaddle 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 applic... | 166,008 | 36.322167 | 111 | py |
Paddle | Paddle-master/python/paddle/utils/predefined_net.py | # Copyright (c) 2016 PaddlePaddle 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 applic... | 14,269 | 36.454068 | 80 | py |
Paddle | Paddle-master/python/paddle/utils/torch2paddle.py | # Copyright (c) 2016 PaddlePaddle 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 applic... | 2,946 | 30.688172 | 97 | py |
RecAdam | RecAdam-master/run_glue_with_RecAdam.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, 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 cop... | 36,356 | 43.940667 | 150 | py |
RecAdam | RecAdam-master/RecAdam.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# 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/LICEN... | 7,084 | 48.545455 | 132 | py |
STGCN | STGCN-main/main.py | import logging
import os
import argparse
import math
import random
import tqdm
import numpy as np
import pandas as pd
from sklearn import preprocessing
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils as utils
from script import dataloader, utility, earlystopping
from model import mod... | 9,002 | 42.703883 | 147 | py |
STGCN | STGCN-main/model/layers.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
class Align(nn.Module):
def __init__(self, c_in, c_out):
super(Align, self).__init__()
self.c_in = c_in
self.c_out = c_out
self.align_conv = nn.Conv2d(in_channels=c_in, out_ch... | 11,622 | 38.804795 | 178 | py |
STGCN | STGCN-main/model/models.py | import torch
import torch.nn as nn
from model import layers
class STGCNChebGraphConv(nn.Module):
# STGCNChebGraphConv contains 'TGTND TGTND TNFF' structure
# ChebGraphConv is the graph convolution from ChebyNet.
# Using the Chebyshev polynomials of the first kind as a graph filter.
# T: Gated... | 4,413 | 40.252336 | 182 | py |
STGCN | STGCN-main/script/utility.py | import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import norm
import torch
def calc_gso(dir_adj, gso_type):
n_vertex = dir_adj.shape[0]
if sp.issparse(dir_adj) == False:
dir_adj = sp.csc_matrix(dir_adj)
elif dir_adj.format != 'csc':
dir_adj = dir_adj.tocsc()
id = s... | 4,357 | 34.721311 | 124 | py |
STGCN | STGCN-main/script/dataloader.py | import os
import numpy as np
import pandas as pd
import scipy.sparse as sp
import torch
def load_adj(dataset_name):
dataset_path = './data'
dataset_path = os.path.join(dataset_path, dataset_name)
adj = sp.load_npz(os.path.join(dataset_path, 'adj.npz'))
adj = adj.tocsc()
if dataset_name == 'met... | 1,358 | 27.3125 | 68 | py |
STGCN | STGCN-main/script/earlystopping.py | import torch
class EarlyStopping(object):
def __init__(self, mode='min', min_delta=0, patience=10, percentage=False):
self.mode = mode
self.min_delta = min_delta
self.patience = patience
self.best = None
self.num_bad_epochs = 0
self.is_better = None
self._ini... | 1,603 | 31.08 | 79 | py |
DT-FM | DT-FM-master/foo.py | import torch
import cupy
print("<== Load torch and cupy. ==>")
| 64 | 12 | 37 | py |
DT-FM | DT-FM-master/dist_runner.py | import argparse
import torch.autograd.profiler as profiler
from task_datasets.qqp import get_glue_qqp_train_data_loader
from task_datasets.tokenizer import build_tokenizer
from pipeline_parallel.dist_pp_utils import get_pp_module
from utils.dist_args_utils import *
from utils.dist_train_utils import *
from comm.comm_ut... | 3,273 | 40.443038 | 103 | py |
DT-FM | DT-FM-master/task_datasets/abstract_dataset.py | """This follows Megatron's implementation to make a fair comparison."""
"""GLUE dataset."""
from abc import ABC
from abc import abstractmethod
from torch.utils.data import Dataset
from .data_utils import build_sample
from .data_utils import build_tokens_types_paddings_from_text
class GLUEAbstractDataset(ABC, Dataset)... | 1,859 | 36.959184 | 89 | py |
DT-FM | DT-FM-master/task_datasets/qqp.py | """QQP dataset."""
import torch
from .data_utils import clean_text
from .abstract_dataset import GLUEAbstractDataset
LABELS = [0, 1]
class QQPDataset(GLUEAbstractDataset):
def __init__(self, name, datapaths, tokenizer, max_seq_length,
test_label=0):
self.test_label = test_label
... | 4,859 | 42.783784 | 89 | py |
DT-FM | DT-FM-master/task_datasets/pretrain_corpus.py | import os
import re
import torch
from torch.utils.data import IterableDataset, DataLoader
from itertools import cycle, islice
# task_datasets from hf.
from datasets import Dataset
from datasets import load_dataset, load_from_disk
from comm.comm_utils import *
class StreamDataset(IterableDataset):
def __init__(sel... | 3,230 | 40.423077 | 95 | py |
DT-FM | DT-FM-master/modules/dist_gpt_pp_module.py | from torch import nn
from .gpt_modules import GPTEmbedding, GPTTransformerLayer
from .task_modules import SeqClassification, Seq2SeqClassification
class GPTStageBase(nn.Module):
def __init__(self, args, vocab_size, num_classes):
super(GPTStageBase, self).__init__()
self._to_cpu = (args.dist_backen... | 3,509 | 41.289157 | 98 | py |
DT-FM | DT-FM-master/modules/gpt_modules.py | import math
from torch import nn
from torch.nn import functional
from torch.utils.checkpoint import checkpoint
from .task_modules import SeqClassification, Seq2SeqClassification
from utils.dist_debug_utils import *
class MultiHeadAttention(nn.Module):
def __init__(self, model_dim, head_num):
super(MultiHe... | 7,282 | 42.094675 | 118 | py |
DT-FM | DT-FM-master/modules/task_modules.py | import torch
from torch.utils.checkpoint import checkpoint
class SeqClassification(torch.nn.Module):
def __init__(self, model_dim, num_classes):
super(SeqClassification, self).__init__()
self.model_dim = model_dim
self.num_classes = num_classes
self.pooler_layer = torch.nn.Linear(m... | 1,923 | 40.826087 | 112 | py |
DT-FM | DT-FM-master/data_parallel/dist_dp_sharded_ps.py | import torch.cuda
from comm.comm_utils import *
from .flatten_utils import flatten_params
class ShardedPSDP:
def __init__(self, args, device, module: torch.nn.Module, optimizer: torch.optim.Optimizer = None, flatten=True):
self.flatten = flatten
self.global_rank = args.rank
self.dp_group_s... | 5,712 | 47.82906 | 118 | py |
DT-FM | DT-FM-master/data_parallel/dist_dp_allreduce.py | import torch.cuda
from comm.comm_utils import *
from .flatten_utils import flatten_params
class AllReduceDP:
def __init__(self, args, device, module: torch.nn.Module, optimizer: torch.optim.Optimizer = None, flatten=True):
self.flatten = flatten
self.global_rank = args.rank
self.dp_group_s... | 7,110 | 52.067164 | 121 | py |
DT-FM | DT-FM-master/data_parallel/dist_dp_central_ps.py | import torch.cuda
from comm.comm_utils import *
from .flatten_utils import flatten_params
class CentralPSDP:
def __init__(self, args, device, module: torch.nn.Module, optimizer: torch.optim.Optimizer = None, flatten=True):
self.flatten = flatten
self.global_rank = args.rank
self.dp_group_s... | 10,343 | 54.612903 | 122 | py |
DT-FM | DT-FM-master/data_parallel/flatten_utils.py | import torch
def _assert_contiguous(tensors):
data_ptr = None
for t in tensors:
if data_ptr is not None:
assert t.data_ptr() == data_ptr
data_ptr = t.data_ptr() + t.numel() * t.element_size()
def flatten_params(param_set, chunk=None):
params = [p for p in param_set]
weigh... | 1,985 | 36.471698 | 98 | py |
DT-FM | DT-FM-master/pipeline_parallel/dist_gpipe_pipeline_async.py | import time
import json
import torch.nn.functional
from torch import optim
from comm.comm_utils import *
from modules.dist_gpt_pp_module import *
from data_parallel.dist_dp_utils import get_dp_module
from optimizer.optimizer import get_fp16_optimizer
class GpipeAsync:
r"""
Async implementation of Gpipe.
T... | 24,528 | 58.248792 | 120 | py |
DT-FM | DT-FM-master/comm/nccl_backend.py | import torch
import numpy as np
import cupy
import torch.distributed as dist
from typing import List
def _type_torch_to_cupy(torch_type: torch.dtype):
# print(torch_type)
mappings = {
torch.uint8: cupy.cuda.nccl.NCCL_UINT8,
torch.int32: cupy.cuda.nccl.NCCL_INT32,
torch.int: cupy.cuda.n... | 7,264 | 32.948598 | 114 | py |
DT-FM | DT-FM-master/offload/offload_utils.py | import numpy as np
import torch
import cupy
def pin_memory(array):
mem = cupy.cuda.alloc_pinned_memory(array.nbytes)
ret = np.frombuffer(mem, array.dtype, array.size).reshape(array.shape)
ret[...] = array
return ret
def copy_torch_gpu_tensor2numpy_cpu_array(gpu_tensor: torch.Tensor, cpu_array: np.nd... | 589 | 28.5 | 91 | py |
DT-FM | DT-FM-master/utils/dist_args_utils.py | def add_device_arguments(parser):
parser.add_argument('--use-cuda', default=True, type=lambda x: (str(x).lower() == 'true'),
help='if this is set to True, will use cuda to train')
parser.add_argument('--cuda-id', type=int, default=0, metavar='N',
help='cuda index,... | 6,183 | 52.773913 | 121 | py |
DT-FM | DT-FM-master/utils/dist_debug_utils.py | import torch
def print_cuda_memory(args, info: str, device=None):
if args.debug_mem:
if device is None:
device = torch.device('cuda', args.cuda_id)
print("<{}>: current memory allocated: {:2.3f} MB, peak memory: {:2.3f} MB".format(
info, torch.cuda.memory_allocated(device)/... | 794 | 43.166667 | 120 | py |
DT-FM | DT-FM-master/optimizer/grad_scalar.py | from abc import ABC
from abc import abstractmethod
import torch
class GradScaler(ABC):
def __init__(self, initial_scale, offload=False):
"""Initialize scale value with the input initial scale."""
assert initial_scale > 0.0
self._scale = torch.cuda.FloatTensor([initial_scale]) if not offlo... | 3,910 | 34.880734 | 126 | py |
DT-FM | DT-FM-master/optimizer/optimizer.py | import torch
from .grad_scalar import *
# This follows some implementation from Megatron
def _has_overflow_serial(grads):
def _has_inf_or_nan(x):
try:
# if x is half, the .float() incurs an additional deep copy, but it's necessary if
# Pytorch's .sum() creates a one-element tenso... | 9,916 | 41.930736 | 121 | py |
DT-FM | DT-FM-master/udp_hole_punching_test/pytorch_send_recv_test.py | import random
import torch
import argparse
import time
import torch.distributed as dist
from nccl_backend import NCCLCommunicator
def test_sync_send_recv_delay(args, device, communicator):
print("<==== Test delay ====>")
if args.rank == 1:
send_tensor = torch.ones(1, dtype=torch.float32, device=device... | 6,607 | 39.048485 | 120 | py |
DT-FM | DT-FM-master/udp_hole_punching_test/nccl_backend.py | import torch
import numpy as np
import cupy
import torch.distributed as dist
from typing import List
def _type_torch_to_cupy(torch_type: torch.dtype):
# print(torch_type)
mappings = {
torch.uint8: cupy.cuda.nccl.NCCL_UINT8,
torch.int32: cupy.cuda.nccl.NCCL_INT32,
torch.int: cupy.cuda.n... | 7,253 | 32.739535 | 106 | py |
UnifiedSKG | UnifiedSKG-main/train.py | import logging
import os
import time
import torch
import datasets
import transformers
from transformers import (
HfArgumentParser,
set_seed,
EarlyStoppingCallback,
)
from transformers.trainer_utils import get_last_checkpoint
from collections import OrderedDict
import utils.tool
from utils.configue import C... | 9,806 | 42.78125 | 177 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/sql2text.py | import os
import torch
from copy import deepcopy
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from datasets.dataset_dict import DatasetDict
from tqdm import tqdm
class Constructor(object):
def __init__(self, args):
self.args = args
def to_seq2seq(self, raw_datasets: D... | 3,608 | 34.382353 | 83 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/sparc.py | import os
import torch
import random
import re
from typing import List, Dict
from datasets.dataset_dict import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from tqdm import tqdm
from third_party.miscs.bridge_content_encoder import get_database_matches
from copy import deep... | 11,807 | 34.353293 | 116 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/wikitq.py | import copy
import os
from copy import deepcopy
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from transformers import AutoTokenizer
from tqdm import tqdm
from utils.processor import get_default_processor
class Constructor(object):
de... | 7,511 | 43.188235 | 131 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/russ.py | import copy
import os
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from tqdm import tqdm
"""
{
"id": datasets.Value("string"),
"question": datasets.Value("string"),
"query": datasets.Value("string"),
}
"""
class Constructor(object... | 4,523 | 37.338983 | 83 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/e2e_nlg_cleaned.py | import re
import os
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from tqdm import tqdm
class Constructor(object):
def __init__(self, args):
self.args = args
def to_seq2seq(self, raw_datasets: DatasetDict, cache_root: str)... | 6,133 | 36.402439 | 101 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/meta_tuning.py | import os
import math
from typing import Dict
from copy import deepcopy
import numpy as np
from datasets import DatasetDict
from random import shuffle
from torch.utils.data import Dataset, ConcatDataset
from torch.utils.data.dataset import T_co
from utils.configue import Configure
"""
Meta-tuning concat part.
After ... | 9,201 | 35.228346 | 169 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/spider.py | import os
import torch
import random
import re
from copy import deepcopy
from typing import List, Dict
from datasets.dataset_dict import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from third_party.miscs.bridge_content_encoder import get_database_matches
from tqdm impor... | 15,104 | 36.857143 | 133 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/wikisql.py | import os
from copy import deepcopy
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from transformers import AutoTokenizer
from tqdm import tqdm
from utils.processor import get_default_processor
"""
These packages are inherit from the old ve... | 8,607 | 43.601036 | 131 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/compwebq.py | import os
import torch
from copy import deepcopy
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from tqdm import tqdm
class Constructor(object):
def __init__(self, args):
self.args = args
def to_seq2seq(self, raw_datasets: DatasetDict, c... | 4,828 | 35.037313 | 105 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/dart.py | import os
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from tqdm import tqdm
class Constructor(object):
def __init__(self, args):
self.args = args
def to_seq2seq(self, raw_datasets: DatasetDict, cache_root: str):
i... | 6,988 | 38.710227 | 124 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/kvret.py | import copy
import os
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from transformers import AutoTokenizer
from tqdm import tqdm
from utils.processor import get_default_processor
class Constructor(object):
def __init__(self, args):
... | 11,485 | 51.930876 | 127 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/ottqa.py | import copy
import os
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from transformers import AutoTokenizer
from utils.processor import get_default_processor
from tqdm import tqdm
class Constructor(object):
def __init__(self, args):
... | 5,590 | 44.08871 | 131 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/mtop.py | import copy
import os
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from tqdm import tqdm
"""
{
"inputs": datasets.Value("string"),
"targets": datasets.Value("string"),
}
"""
class Constructor(object):
def __init__(self, args):
... | 4,352 | 38.93578 | 111 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/tab_fact.py | import os
from copy import deepcopy
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from transformers import AutoTokenizer
from tqdm import tqdm
from utils.processor import get_default_processor
# The TabFact dataset is quiet special in the... | 8,214 | 44.137363 | 131 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/webqsp.py | import os
import torch
from copy import deepcopy
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from tqdm import tqdm
class Constructor(object):
def __init__(self, args):
self.args = args
def to_seq2seq(self, raw_datasets: DatasetDict, c... | 5,080 | 36.087591 | 109 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/logic2text.py | import os
import torch
from copy import deepcopy
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from tqdm import tqdm
class Constructor(object):
def __init__(self, args):
self.args = args
def to_seq2seq(self, raw_datasets: DatasetDict, c... | 4,705 | 36.349206 | 86 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/multi_woz_22_response.py | import copy
import json
import os
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from transformers import AutoTokenizer
from utils.processor import get_default_processor
class Constructor(object):
def __init__(self, args):
sel... | 16,070 | 41.181102 | 117 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/cosql.py | import os
import torch
import random
import re
from typing import List, Dict
from datasets.dataset_dict import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from tqdm import tqdm
from third_party.miscs.bridge_content_encoder import get_database_matches
from copy import deep... | 11,813 | 34.371257 | 116 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/totto.py | import os
import copy
import torch
from copy import deepcopy
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from tqdm import tqdm
def _add_adjusted_col_offsets(table):
"""Add adjusted column offsets to take into account multi-column cells."""
adj... | 7,764 | 35.97619 | 87 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/fetaqa.py | import os
import copy
import os
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from transformers import AutoTokenizer
from tqdm import tqdm
from utils.processor import get_default_processor
class Constructor(object):
def __init__(self,... | 7,884 | 43.801136 | 139 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/multiwoz.py | import copy
import os
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from tqdm import tqdm
class Constructor(object):
def __init__(self, args):
self.args = args
def to_seq2seq(self, raw_datasets: DatasetDict, cache_root: s... | 13,340 | 45.16263 | 117 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/kvret_glmp.py | import copy
import os
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from transformers import AutoTokenizer
from tqdm import tqdm
from utils.processor import get_default_processor
class Constructor(object):
def __init__(self, args):
... | 8,007 | 43.988764 | 127 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/msr_sqa.py | import copy
import os
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from transformers import AutoTokenizer
from utils.processor import get_default_processor
from tqdm import tqdm
class Constructor(object):
def __init__(self, args):
... | 8,962 | 45.682292 | 131 | py |
UnifiedSKG | UnifiedSKG-main/seq2seq_construction/feverous.py | import copy
import os
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from transformers import AutoTokenizer
from tqdm import tqdm
from utils.processor import get_default_processor
class Constructor(object):
def __init__(self, args):... | 6,854 | 43.512987 | 118 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.