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 |
|---|---|---|---|---|---|---|
DiffFashion | DiffFashion-main/guided_diffusion/guided_diffusion/respace.py | import numpy as np
import torch as th
from .gaussian_diffusion import GaussianDiffusion
def space_timesteps(num_timesteps, section_counts):
"""
Create a list of timesteps to use from an original diffusion process,
given the number of timesteps we want to take from equally-sized portions
of the origin... | 5,193 | 39.263566 | 85 | py |
DiffFashion | DiffFashion-main/guided_diffusion/guided_diffusion/dist_util.py | """
Helpers for distributed training.
"""
import io
import os
import socket
import blobfile as bf
from mpi4py import MPI
import torch as th
import torch.distributed as dist
# Change this to reflect your cluster layout.
# The GPU for a given rank is (rank % GPUS_PER_NODE).
GPUS_PER_NODE = 8
SETUP_RETRY_COUNT = 3
d... | 2,424 | 24.797872 | 87 | py |
DiffFashion | DiffFashion-main/model_vit/contra_loss.py | import torch
from torch import nn
from torch.nn import functional as F
class Normalize(nn.Module):
def __init__(self, power=2):
super(Normalize, self).__init__()
self.power = power
def forward(self, x):
norm = x.pow(self.power).sum(1, keepdim=True).pow(1. / self.power)
out = x... | 3,125 | 32.612903 | 95 | py |
DiffFashion | DiffFashion-main/model_vit/model.py | import torch
from . import networks
class Model(torch.nn.Module):
def __init__(self, cfg):
super().__init__()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.netG = networks.define_G(cfg['init_type'], cfg['init_gain']).to(device)
self.cfg = cfg
def f... | 867 | 32.384615 | 98 | py |
DiffFashion | DiffFashion-main/model_vit/networks.py | from torch.nn import init
from torch.optim import lr_scheduler
from models.unet.skip import skip
def get_scheduler(optimizer, opt):
if opt.lr_policy == 'linear':
def lambda_rule(epoch):
lr_l = 1.0 - max(0, epoch + opt.epoch_count - opt.n_epochs) / float(opt.n_epochs_decay + 1)
retu... | 2,636 | 43.694915 | 116 | py |
DiffFashion | DiffFashion-main/model_vit/extractor.py | import torch
def attn_cosine_sim(x, eps=1e-08):
x = x[0] # TEMP: getting rid of redundant dimension, TBF
norm1 = x.norm(dim=2, keepdim=True)
factor = torch.clamp(norm1 @ norm1.permute(0, 2, 1), min=eps)
sim_matrix = (x @ x.permute(0, 2, 1)) / factor
return sim_matrix
class VitExtractor:
BLO... | 6,749 | 38.473684 | 112 | py |
DiffFashion | DiffFashion-main/model_vit/loss_vit.py | from torchvision.transforms import Resize
from torchvision import transforms
import torch
import torch.nn.functional as F
import torch.nn as nn
from model_vit.extractor import VitExtractor
from model_vit.contra_loss import PatchLoss,ConstLoss
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class ... | 6,405 | 43.797203 | 117 | py |
DiffFashion | DiffFashion-main/model_vit/unet/downsampler.py | import numpy as np
import torch
import torch.nn as nn
class Downsampler(nn.Module):
'''
http://www.realitypixels.com/turk/computergraphics/ResamplingFilters.pdf
'''
def __init__(self, n_planes, factor, kernel_type, phase=0, kernel_width=None, support=None, sigma=None, preserve_size=False):
... | 5,379 | 30.83432 | 129 | py |
DiffFashion | DiffFashion-main/model_vit/unet/common.py | import torch
import torch.nn as nn
import numpy as np
from .downsampler import Downsampler
def add_module(self, module):
self.add_module(str(len(self) + 1), module)
torch.nn.Module.add = add_module
class Concat(nn.Module):
def __init__(self, dim, *args):
super(Concat, self).__init__()
sel... | 3,531 | 27.483871 | 128 | py |
learnable-embed-sizes-for-RecSys | learnable-embed-sizes-for-RecSys-master/train_criteo_retrain.py | from engine import setup_args, Engine
import torch
import os
import random
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
torch.backends.cudnn.enabled = True
if __name__ == '__main__':
parser = setup_args()
parser.set_defaults(
alias='test',
tensorboard='./tmp/runs/{factorizer}/{data_type}',
... | 2,792 | 25.6 | 113 | py |
learnable-embed-sizes-for-RecSys | learnable-embed-sizes-for-RecSys-master/train_avazu.py | from engine import setup_args, Engine
import torch
import os
import random
import numpy as np
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
torch.backends.cudnn.enabled = True
if __name__ == '__main__':
parser = setup_args()
parser.set_defaults(
alias='test',
tensorboard='./tmp/runs/{factorizer}/{d... | 2,858 | 25.971698 | 113 | py |
learnable-embed-sizes-for-RecSys | learnable-embed-sizes-for-RecSys-master/train_ml-1m_retrain.py | from engine import setup_args, Engine
import torch
import os
import random
import numpy as np
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
torch.backends.cudnn.enabled = True
if __name__ == '__main__':
parser = setup_args()
parser.set_defaults(
alias='test',
tensorboard='./tmp/runs/{factorizer}/{da... | 2,826 | 26.182692 | 113 | py |
learnable-embed-sizes-for-RecSys | learnable-embed-sizes-for-RecSys-master/train_criteo.py | from engine import setup_args, Engine
import torch
import os
import random
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
torch.backends.cudnn.enabled = True
if __name__ == '__main__':
parser = setup_args()
parser.set_defaults(
alias='test',
tensorboard='./tmp/runs/{factorizer}/{data_type}',
... | 2,779 | 25.730769 | 113 | py |
learnable-embed-sizes-for-RecSys | learnable-embed-sizes-for-RecSys-master/train_avazu_retrain.py | from engine import setup_args, Engine
import torch
import os
import random
import numpy as np
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
torch.backends.cudnn.enabled = True
if __name__ == '__main__':
parser = setup_args()
parser.set_defaults(
alias='test',
tensorboard='./tmp/runs/{factorizer}/{d... | 2,871 | 25.841121 | 113 | py |
learnable-embed-sizes-for-RecSys | learnable-embed-sizes-for-RecSys-master/train_ml-1m.py | from engine import setup_args, Engine
import torch
import os
import random
import numpy as np
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
torch.backends.cudnn.enabled = True
if __name__ == '__main__':
parser = setup_args()
parser.set_defaults(
alias='test',
tensorboard='./tmp/runs/{factorizer}/{da... | 2,813 | 26.320388 | 113 | py |
learnable-embed-sizes-for-RecSys | learnable-embed-sizes-for-RecSys-master/data_loader/data_loader.py | import math
from datetime import datetime
import numpy as np
import torch
from torch.utils.data import DataLoader
from data_loader.movielens import MovieLensDataset
from data_loader.avazu import AvazuDataset
from data_loader.criteo import CriteoDataset
def setup_generator(opt):
"""Choose different type of sampl... | 5,398 | 34.058442 | 117 | py |
learnable-embed-sizes-for-RecSys | learnable-embed-sizes-for-RecSys-master/data_loader/avazu.py | import shutil
import struct
from collections import defaultdict
from pathlib import Path
import lmdb
import numpy as np
import torch.utils.data
from tqdm import tqdm
import pandas as pd
class AvazuDataset(torch.utils.data.Dataset):
"""
Avazu Click-Through Rate Prediction Dataset
Dataset preparation
... | 5,311 | 40.5 | 119 | py |
learnable-embed-sizes-for-RecSys | learnable-embed-sizes-for-RecSys-master/data_loader/criteo.py | import math
import shutil
import struct
from collections import defaultdict
from functools import lru_cache
from pathlib import Path
import lmdb
import numpy as np
import torch.utils.data
from tqdm import tqdm
import pandas as pd
class CriteoDataset(torch.utils.data.Dataset):
"""
Criteo Display Advertising C... | 6,608 | 39.796296 | 120 | py |
learnable-embed-sizes-for-RecSys | learnable-embed-sizes-for-RecSys-master/data_loader/movielens.py | import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import math
from torch.utils.data import Dataset
class MovieLensDataset(Dataset):
def __init__(self, data_path, data_type):
self.label_encoder = LabelEncoder()
self.data, self.labels, self.field_dims = self.lo... | 5,191 | 47.981132 | 112 | py |
learnable-embed-sizes-for-RecSys | learnable-embed-sizes-for-RecSys-master/models/modules.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchfm.layer import FactorizationMachine, FeaturesLinear, MultiLayerPerceptron
import numpy as np
from models.pep_embedding import PEPEmbedding
class LR(torch.nn.Module):
def __init__(self, opt):
super(LR, self).__init__()
s... | 4,741 | 32.871429 | 135 | py |
learnable-embed-sizes-for-RecSys | learnable-embed-sizes-for-RecSys-master/models/pep_embedding.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class PEPEmbedding(nn.Module):
def __init__(self, opt):
super(PEPEmbedding, self).__init__()
self.use_cuda = opt.get('use_cuda')
self.threshold_type = opt['threshold_type']
self.latent_dim = opt['... | 3,629 | 38.032258 | 103 | py |
learnable-embed-sizes-for-RecSys | learnable-embed-sizes-for-RecSys-master/models/factorizer.py | import torch
from torch.nn import BCEWithLogitsLoss
from torch.optim.lr_scheduler import ExponentialLR
from copy import deepcopy
from models.modules import LR, FM, DeepFM, AutoInt
from utils.train import use_cuda, use_optimizer, get_grad_norm
def setup_factorizer(opt):
new_opt = deepcopy(opt)
for k, v in opt... | 4,056 | 29.734848 | 96 | py |
learnable-embed-sizes-for-RecSys | learnable-embed-sizes-for-RecSys-master/utils/evaluate.py | from sklearn import metrics
import torch
from torch import multiprocessing as mp
import pandas as pd
import numpy as np
from datetime import datetime
def evaluate_fm(factorizer, sampler, use_cuda, on='test'):
all_logloss, all_auc = [], []
model = factorizer.model
model.eval()
for i in range(sampler.nu... | 925 | 29.866667 | 90 | py |
learnable-embed-sizes-for-RecSys | learnable-embed-sizes-for-RecSys-master/utils/train.py | """
Some handy functions for pytroch model training ...
"""
import torch
def get_grad_norm(model):
grads = []
for p in model.parameters():
if p.grad is not None:
grads.append(p.grad.data.view(-1, 1))
if len(grads) == 0:
grads.append(torch.FloatTensor([0]))
grad_norm = t... | 1,990 | 34.553571 | 126 | py |
netqasm-develop | netqasm-develop/docs/conf.py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | 2,924 | 32.238636 | 81 | py |
sncosmo | sncosmo-master/docs/conf.py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
#
# Astropy documentation build configuration file.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this file.
#
# All configurati... | 7,815 | 33.280702 | 80 | py |
SME | SME-master/docs/conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | 5,432 | 29.016575 | 79 | py |
IDGL | IDGL-master/src/main.py | import argparse
import yaml
import torch
import numpy as np
from collections import defaultdict, OrderedDict
from core.model_handler import ModelHandler
################################################################################
# Main #
###########################################################################... | 4,032 | 30.507813 | 109 | py |
IDGL | IDGL-master/src/core/model.py | import os
import random
import numpy as np
from collections import Counter
from sklearn.metrics import r2_score
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import ReduceLROnPlateau
import torch.nn.functional as F
from .models.graph_clf import GraphClf
from .models.tex... | 10,267 | 44.839286 | 144 | py |
IDGL | IDGL-master/src/core/model_handler.py | import os
import time
import json
import glob
import numpy as np
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torch.backends.cudnn as cudnn
from .model import Model
from .utils.generic_utils import to_cuda
from .utils.data_utils import prepare_datasets, DataStream, vect... | 53,353 | 44.797425 | 225 | py |
IDGL | IDGL-master/src/core/models/text_graph.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..layers.graphlearn import GraphLearner, get_binarized_kneighbors_graph
from ..layers.scalable_graphlearn import AnchorGraphLearner
from ..layers.anchor import AnchorGCN
from ..layers.common import dropout, EncoderRNN
from ..layers.gnn import GCN,... | 14,611 | 42.61791 | 175 | py |
IDGL | IDGL-master/src/core/models/graph_clf.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..layers.graphlearn import GraphLearner
from ..layers.scalable_graphlearn import AnchorGraphLearner
from ..layers.anchor import AnchorGCN
from ..layers.common import dropout
from ..layers.gnn import GCN, GAT, GraphSAGE
from ..utils.generic_utils i... | 5,626 | 42.284615 | 141 | py |
IDGL | IDGL-master/src/core/layers/scalable_graphlearn.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..utils.generic_utils import to_cuda, normalize_adj
from ..utils.constants import VERY_SMALL_NUMBER, INF
def compute_normalized_laplacian(adj):
rowsum = torch.sum(adj, -1)
d_inv_sqrt = torch.pow(rowsum, -0.5)
d_inv_sqrt[t... | 7,132 | 39.994253 | 133 | py |
IDGL | IDGL-master/src/core/layers/gnn.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .graphlearn import GraphLearner
from ..utils.generic_utils import to_cuda
from ..utils.constants import VERY_SMALL_NUMBER, INF
class GraphSAGE(nn.Module):
"""https://github.com/dmlc/dgl/blob/master/examples/pytorch/graphsage/train_full.py""... | 5,818 | 33.636905 | 126 | py |
IDGL | IDGL-master/src/core/layers/common.py | '''
Created on Nov, 2018
@author: hugo
'''
from typing import List
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence
import torch.nn.functional as F
from ..utils.generic_utils import to_cuda
from ..utils.constants import VERY_SMALL_NUMBER
def dropout(x, dro... | 4,281 | 40.572816 | 122 | py |
IDGL | IDGL-master/src/core/layers/anchor.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..utils.generic_utils import to_cuda, create_mask
from ..utils.constants import VERY_SMALL_NUMBER, INF
def sample_anchors(node_vec, s):
idx = torch.randperm(node_vec.size(0))[:s]
return node_vec[idx], idx
def batch_sample_an... | 4,745 | 35.790698 | 128 | py |
IDGL | IDGL-master/src/core/layers/graphlearn.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..utils.generic_utils import to_cuda
from ..utils.constants import VERY_SMALL_NUMBER, INF
def compute_normalized_laplacian(adj):
rowsum = torch.sum(adj, -1)
d_inv_sqrt = torch.pow(rowsum, -0.5)
d_inv_sqrt[torch.isinf(d_in... | 6,883 | 40.221557 | 133 | py |
IDGL | IDGL-master/src/core/utils/generic_utils.py | '''
Created on Nov, 2018
@author: hugo
'''
import yaml
import numpy as np
import networkx as nx
from collections import defaultdict
import scipy.sparse as sp
import torch
import torch.nn as nn
import torch.nn.functional as F
from .constants import VERY_SMALL_NUMBER, INF
def tile(x, count, dim=0):
"""
Tiles... | 3,552 | 29.110169 | 126 | py |
IDGL | IDGL-master/src/core/utils/radam.py | import math
import torch
from torch.optim.optimizer import Optimizer, required
class RAdam(Optimizer):
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0):
defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)
self.buffer = [[None, None, None] for in... | 7,987 | 37.403846 | 189 | py |
IDGL | IDGL-master/src/core/utils/data_utils.py | # -*- coding: utf-8 -*-
"""
Module to handle getting data loading classes and helper functions.
"""
import json
import re
import random
import io
import torch
import numpy as np
from scipy.sparse import *
from collections import Counter, defaultdict
from .network_data import data_utils as network_data_utils
from .uci... | 7,831 | 43.248588 | 479 | py |
IDGL | IDGL-master/src/core/utils/network_data/data_utils.py | # https://github.com/tkipf/gcn/blob/master/gcn/utils.py
import os
import sys
import numpy as np
import pickle as pkl
import networkx as nx
import scipy.sparse as sp
from sklearn.neighbors import kneighbors_graph
import torch
from ..generic_utils import *
from ..constants import VERY_SMALL_NUMBER
def parse_index_fil... | 9,079 | 38.137931 | 161 | py |
IDGL | IDGL-master/src/core/utils/uci_data/data_utils.py | # The code below are borrowed from https://github.com/lucfra/LDS-GNN/blob/master/
import os
import pickle
import numpy as np
from sklearn import datasets
from sklearn.preprocessing import LabelBinarizer
from sklearn.neighbors import kneighbors_graph
import torch
from ..generic_utils import *
class Config:
""" Ba... | 7,493 | 39.290323 | 103 | py |
Survival-DeepMTS | Survival-DeepMTS-master/src/losses.py | # Third party inports
import tensorflow as tf
import keras.backend as K
import numpy as np
def Dice_loss(y_true, y_pred):
"""
N-D dice for binary segmentation
"""
ndims = len(y_pred.get_shape().as_list()) - 2
vol_axes = list(range(1, ndims+1))
top = 2 * tf.reduce_sum(y_true * y_pred, vol... | 1,171 | 25.636364 | 71 | py |
Survival-DeepMTS | Survival-DeepMTS-master/src/test.py | # py imports
import os
import sys
import glob
from argparse import ArgumentParser
# third party
import tensorflow as tf
import scipy.io as sio
import numpy as np
import cv2
from keras.backend.tensorflow_backend import set_session
from scipy.interpolate import interpn
from sklearn import metrics
from lifelines.utils im... | 4,790 | 30.94 | 114 | py |
Survival-DeepMTS | Survival-DeepMTS-master/src/networks.py | # main imports
import sys
# third party
import numpy as np
import keras.backend as K
from keras.models import Model
import keras.layers as KL
from keras.layers import Layer
from keras.layers import Conv3D, Activation, Input, UpSampling3D, concatenate, Conv3DTranspose, ZeroPadding3D, AveragePooling3D, BatchNormalizatio... | 16,115 | 32.02459 | 211 | py |
Survival-DeepMTS | Survival-DeepMTS-master/src/metrics.py | # Third party inports
import tensorflow as tf
import keras.backend as K
import numpy as np
def Dice(y_true, y_pred):
"""
Dice score for binary segmentation
"""
ndims = len(y_pred.get_shape().as_list()) - 2
vol_axes = list(range(1, ndims+1))
y_pred = tf.cast(y_pred > 0.5, y_pred.dtype)
... | 1,246 | 24.44898 | 74 | py |
Survival-DeepMTS | Survival-DeepMTS-master/src/train.py | # python imports
import os
import glob
import sys
import random
from argparse import ArgumentParser
import matplotlib
matplotlib.use('Agg')
# third-party imports
import tensorflow as tf
import numpy as np
from keras.backend.tensorflow_backend import set_session
from keras.optimizers import Adam
from keras.callbacks im... | 7,800 | 36.868932 | 159 | py |
Essential-Step-Detection | Essential-Step-Detection-main/ESD code/intent.py | from transformers import RobertaTokenizer,RobertaForMultipleChoice,RobertaConfig
from utils import *
import json
import torch
import numpy as np
from sklearn.metrics import roc_auc_score
import argparse
def load_model():
model_name='zharry29/intent_fb-en_wh_id_rl'
tokenizer = RobertaTokenizer.from_pretrained(m... | 2,109 | 34.762712 | 124 | py |
Essential-Step-Detection | Essential-Step-Detection-main/ESD code/entail.py | '''
using entailment score to infer essentiality
'''
from utils import *
import json
import torch
import numpy as np
from sklearn.metrics import roc_auc_score
from allennlp_models.pretrained import load_predictor
import argparse
def load_model():
model = load_predictor("pair-classification-roberta-mnli")
retur... | 1,886 | 31.534483 | 124 | py |
Essential-Step-Detection | Essential-Step-Detection-main/ESD code/probing_qa.py | from utils import *
from transformers import AutoTokenizer, T5ForConditionalGeneration
import json
import torch
import numpy as np
from sklearn.metrics import roc_auc_score
import argparse
def load_model():
model_name = "allenai/unifiedqa-t5-large"
tokenizer = AutoTokenizer.from_pretrained(model_name)
mod... | 2,064 | 32.852459 | 124 | py |
Essential-Step-Detection | Essential-Step-Detection-main/ESD code/probing.py | '''
calculate perplexity by making a template, and then infer essentiality
'''
from utils import *
import torch
import numpy as np
from transformers import GPT2LMHeadModel, GPT2TokenizerFast
from sklearn.metrics import roc_auc_score
import json
import argparse
#Bert
# config = BertConfig.from_pretrained("bert-base-unc... | 3,862 | 35.443396 | 124 | py |
RESCAN | RESCAN-master/config/cal_ssim.py | import torch
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from math import exp
def gaussian(window_size, sigma):
gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)])
return gauss/gauss.sum()
def create_window(window_size,... | 2,635 | 34.621622 | 104 | py |
RESCAN | RESCAN-master/config/model.py | import torch
from torch import nn
from torch import autograd
from torch.autograd import Variable
from torch.nn import functional as F
from torch.nn.parameter import Parameter
import settings
class SEBlock(nn.Module):
def __init__(self, input_dim, reduction):
super().__init__()
mid = int(input_dim... | 6,196 | 29.678218 | 92 | py |
RESCAN | RESCAN-master/config/dataset.py | import os
import cv2
import numpy as np
from numpy.random import RandomState
from torch.utils.data import Dataset
import settings
class TrainValDataset(Dataset):
def __init__(self, name):
super().__init__()
self.rand_state = RandomState(66)
self.root_dir = os.path.join(settings.data_dir,... | 4,681 | 28.632911 | 66 | py |
RESCAN | RESCAN-master/config/show.py | import os
import sys
import cv2
import argparse
import numpy as np
import itertools
import torch
from torch import nn
from torch.nn import DataParallel
from torch.optim import Adam
from torch.autograd import Variable
from torch.utils.data import DataLoader
import settings
from dataset import ShowDataset
from model i... | 2,755 | 25.757282 | 73 | py |
RESCAN | RESCAN-master/config/eval.py | import os
import sys
import cv2
import argparse
import numpy as np
import torch
from torch import nn
from torch.nn import MSELoss
from torch.optim import Adam
from torch.optim.lr_scheduler import MultiStepLR
from torch.autograd import Variable
from torch.utils.data import DataLoader
from tensorboardX import SummaryWri... | 3,326 | 27.681034 | 81 | py |
RESCAN | RESCAN-master/config/train.py | import os
import sys
import cv2
import argparse
import numpy as np
import torch
from torch import nn
from torch.nn import MSELoss
from torch.optim import Adam
from torch.optim.lr_scheduler import MultiStepLR
from torch.autograd import Variable
from torch.utils.data import DataLoader
from tensorboardX import SummaryWri... | 6,448 | 30.612745 | 88 | py |
wordwise | wordwise-master/wordwise/core.py | import logging
from typing import Dict, List, Set, Tuple, Union
import spacy
import spacy_transformers # noqa: F401
import torch
from torch.nn import functional as F
from transformers import AutoModel, AutoTokenizer
from .utils import get_all_candidates, squash, torch_fast_mode
logger = logging.getLogger(__name__)
... | 3,470 | 35.536842 | 111 | py |
wordwise | wordwise-master/wordwise/utils.py | from typing import Callable, List, Tuple, Union
import torch
from sklearn.feature_extraction.text import CountVectorizer
def squash(value: torch.Tensor) -> torch.Tensor:
if not torch.is_tensor(value):
raise ValueError(
f"Expected `torch.Tensor`, but got an unexpected `value` of type {value.__... | 892 | 27.806452 | 95 | py |
Polyglot_Prompt | Polyglot_Prompt-main/evaluate.py | import logging
import os
import sys
import numpy as np
import torch
from tqdm.auto import tqdm
from utils.squad_eval import evaluate as evaluate_squad
from utils.mlqa_eval import evaluate as evaluate_mlqa
from utils.tc_eval import evaluate as evaluate_tc
import json
logger = logging.getLogger(__name__)
TASK2LANGS = {
... | 8,084 | 35.917808 | 143 | py |
Polyglot_Prompt | Polyglot_Prompt-main/data_preprocess.py | import torch
import nlp
from transformers import MT5Tokenizer
import os
import functools
import pandas as pd
from nlp import Dataset
import json
import shutil
import numpy as np
import random
TASK2LANGS = {
"pawsx": "de,en,es,fr,ja,ko,zh".split(","),
"xnli": "ar,bg,de,el,en,es,fr,hi,ru,sw,th,tr,ur,vi,zh".split("... | 8,728 | 39.981221 | 148 | py |
Polyglot_Prompt | Polyglot_Prompt-main/train_mt5.py | import dataclasses
import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Dict, List, Optional
import torch
from evaluate import evaluate_save
from transformers import MT5ForConditionalGeneration, MT5Tokenizer, EvalPrediction,HfArgumentParser,Trainer,TrainingArguments,set_seed
... | 7,578 | 38.473958 | 134 | py |
wetectron | wetectron-master/setup.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#!/usr/bin/env python
import glob
i... | 2,234 | 29.616438 | 100 | py |
wetectron | wetectron-master/tools/test_net.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# Set up custom environment before ... | 4,575 | 33.666667 | 114 | py |
wetectron | wetectron-master/tools/train_net.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# Set up custom environment before ... | 10,406 | 33.460265 | 109 | py |
wetectron | wetectron-master/wetectron/solver/lr_scheduler.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from bisect import bisect_right
imp... | 2,029 | 34.614035 | 80 | py |
wetectron | wetectron-master/wetectron/solver/build.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from .lr_scheduler imp... | 2,084 | 33.180328 | 79 | py |
wetectron | wetectron-master/wetectron/layers/batch_norm.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
class FrozenBatchNorm2d(nn.Module):
"""
BatchNorm2d where the batch statistics and the affine parameters
are fixed
"""
def __init__(self, n):
super(FrozenBatchNorm2d, self).__init__()... | 1,094 | 33.21875 | 71 | py |
wetectron | wetectron-master/wetectron/layers/roi_pool.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from wetectron import _C
from apex import amp
class _ROIPool(Function):
@st... | 1,890 | 28.092308 | 74 | py |
wetectron | wetectron-master/wetectron/layers/roi_align.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from wetectron import _C
from apex import amp
class _ROIAlign(Function):
@s... | 2,144 | 30.086957 | 85 | py |
wetectron | wetectron-master/wetectron/layers/smooth_l1_loss.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
def smooth_l1_loss(input, target, beta=1. / 9, size_average=True, reduction=True):
"""
very similar to the smooth_l1_loss from pytorch, but with
the extra beta parameter
"""
n = torch.abs(input - target)
cond =... | 513 | 29.235294 | 82 | py |
wetectron | wetectron-master/wetectron/layers/sigmoid_focal_loss.py | import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from wetectron import _C
# TODO: Use JIT to replace CUDA implementation in the future.
class _SigmoidFocalLoss(Function):
@staticmethod
def forward(ctx, logits, targets, gamma, alpha):... | 2,333 | 29.311688 | 118 | py |
wetectron | wetectron-master/wetectron/layers/_utils.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import glob
import os.path
import torch
from torch.utils.cpp_extension import load as load_ext
from torch.utils.cpp_extension import CUDA_HOME
def _load_C_extensions():
this_dir = os.path.dirname(os.path.abspath(__file__))
this_dir = os.p... | 1,049 | 29 | 71 | py |
wetectron | wetectron-master/wetectron/layers/misc.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
helper class that supports empty tensors on some nn functions.
Ideally, add support directly in PyTorch to empty tensors in
those functions.
This can be removed once https://github.com/pytorch/pytorch/issues/12013
is implemented
"""
import m... | 6,643 | 31.568627 | 88 | py |
wetectron | wetectron-master/wetectron/layers/__init__.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from .batch_norm import FrozenBatchNorm2d
from .misc import Conv2d
from .misc import DFConv2d
from .misc import ConvTranspose2d
from .misc import BatchNorm2d
from .misc import interpolate
from .nms import nms
from .roi_align import RO... | 1,327 | 26.666667 | 105 | py |
wetectron | wetectron-master/wetectron/layers/dcn/deform_conv_func.py | import torch
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from wetectron import _C
class DeformConvFunction(Function):
@staticmethod
def forward(
ctx,
input,
offset,
weight,
stride... | 8,300 | 30.562738 | 83 | py |
wetectron | wetectron-master/wetectron/layers/dcn/deform_pool_func.py | import torch
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from wetectron import _C
class DeformRoIPoolingFunction(Function):
@staticmethod
def forward(
ctx,
data,
rois,
offset,
spatial_scale,
out_size,
out... | 2,586 | 25.947917 | 99 | py |
wetectron | wetectron-master/wetectron/layers/dcn/deform_pool_module.py | from torch import nn
from .deform_pool_func import deform_roi_pooling
class DeformRoIPooling(nn.Module):
def __init__(self,
spatial_scale,
out_size,
out_channels,
no_trans,
group_size=1,
part_size=None,
... | 6,307 | 40.774834 | 79 | py |
wetectron | wetectron-master/wetectron/layers/dcn/deform_conv_module.py | import math
import torch
import torch.nn as nn
from torch.nn.modules.utils import _pair
from .deform_conv_func import deform_conv, modulated_deform_conv
class DeformConv(nn.Module):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
... | 5,802 | 31.601124 | 78 | py |
wetectron | wetectron-master/wetectron/engine/inference.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import time
import os
import torch
from tqdm import tqdm
from wetectron.config import cfg
from wetectron.data.datasets.evaluation import evaluate
from ..utils.comm import is_main_process, get_world_size
from ..utils.comm import all... | 4,802 | 34.843284 | 96 | py |
wetectron | wetectron-master/wetectron/engine/bbox_aug.py | import torch
import torchvision.transforms as TT
from wetectron.config import cfg
from wetectron.data import transforms as T
from wetectron.structures.image_list import to_image_list
from wetectron.structures.bounding_box import BoxList
from wetectron.modeling.roi_heads.box_head.inference import make_roi_box_post_proc... | 5,365 | 37.328571 | 112 | py |
wetectron | wetectron-master/wetectron/engine/trainer.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import datetime
import logging
impor... | 9,965 | 36.325843 | 146 | py |
wetectron | wetectron-master/wetectron/utils/c2_model_loading.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import pickle
from co... | 8,526 | 39.604762 | 129 | py |
wetectron | wetectron-master/wetectron/utils/metric_logger.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from collections import defaultdict
... | 3,426 | 29.873874 | 84 | py |
wetectron | wetectron-master/wetectron/utils/checkpoint.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import os
import torc... | 6,607 | 37.196532 | 84 | py |
wetectron | wetectron-master/wetectron/utils/comm.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
"""
This file contains primitives for multi-gpu communication.
This is useful when doing distributed trainin... | 3,584 | 28.385246 | 84 | py |
wetectron | wetectron-master/wetectron/utils/model_zoo.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
import sys
try:
from ... | 3,265 | 48.484848 | 126 | py |
wetectron | wetectron-master/wetectron/utils/collect_env.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import PIL
from torch.utils.collect... | 550 | 28 | 71 | py |
wetectron | wetectron-master/wetectron/utils/model_serialization.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from collections import OrderedDict
... | 3,666 | 42.654762 | 91 | py |
wetectron | wetectron-master/wetectron/utils/miscellaneous.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import errno
import json
import logg... | 2,015 | 29.545455 | 116 | py |
wetectron | wetectron-master/wetectron/utils/visualize.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
import cv2
import torch
import os
import numpy as np
import matplotlib.pyplot as plt
from . import cv2_util... | 11,318 | 41.235075 | 141 | py |
wetectron | wetectron-master/wetectron/utils/imports.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
if torch._six.PY3:
... | 1,054 | 38.074074 | 168 | py |
wetectron | wetectron-master/wetectron/data/build.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import bisect
import copy
import logging
import numpy as np
import torch.utils.data
from wetectron.utils.comm import get_world_size
from wetectron.utils.imports import import_file
from wetectron.utils.miscellaneous import save_labels, seed_all_rng... | 8,007 | 38.643564 | 143 | py |
wetectron | wetectron-master/wetectron/data/datasets/voc.py | import os
import pickle
import torch
import torch.utils.data
from PIL import Image
import xml.etree.ElementTree as ET
from wetectron.structures.bounding_box import BoxList
from wetectron.structures.boxlist_ops import remove_small_boxes
from .coco import unique_boxes
class PascalVOCDataset(torch.utils.data.Dataset):
... | 6,431 | 34.733333 | 118 | py |
wetectron | wetectron-master/wetectron/data/datasets/concat_dataset.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import bisect
from torch.utils.data.dataset import ConcatDataset as _ConcatDataset
class ConcatDataset(_ConcatDataset):
"""
Same as torch.utils.data.dataset.ConcatDataset, but exposes an extra
method for querying the sizes of the ima... | 766 | 30.958333 | 72 | py |
wetectron | wetectron-master/wetectron/data/datasets/coco.py | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torchvision
impo... | 7,789 | 40 | 101 | py |
wetectron | wetectron-master/wetectron/data/datasets/evaluation/coco/coco_eval.py | import logging
import tempfile
import os
import torch
from collections import OrderedDict
from tqdm import tqdm
from wetectron.modeling.roi_heads.mask_head.inference import Masker
from wetectron.structures.bounding_box import BoxList
from wetectron.structures.boxlist_ops import boxlist_iou
def do_coco_evaluation(
... | 13,711 | 34.069054 | 88 | py |
wetectron | wetectron-master/wetectron/data/samplers/grouped_batch_sampler.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import itertools
import torch
from torch.utils.data.sampler import BatchSampler
from torch.utils.data.sampler import Sampler
class GroupedBatchSampler(BatchSampler):
"""
Wraps another sampler to yield a mini-batch of indices.
It enfo... | 4,845 | 40.775862 | 88 | py |
wetectron | wetectron-master/wetectron/data/samplers/iteration_based_batch_sampler.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from torch.utils.data.sampler import BatchSampler
class IterationBasedBatchSampler(BatchSampler):
"""
Wraps a BatchSampler, resampling from it until
a specified number of iterations have been sampled
"""
def __init__(self, ba... | 1,164 | 35.40625 | 71 | py |
wetectron | wetectron-master/wetectron/data/samplers/distributed.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# Code is copy-pasted exactly as in torch.utils.data.distributed.
# FIXME remove this once c10d fixes the bug it has
import math
import torch
import torch.distributed as dist
from torch.utils.data.sampler import Sampler
class DistributedSampler(S... | 2,569 | 37.358209 | 86 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.