content
stringlengths
200
198k
repo
stringlengths
4
186
path
stringclasses
1 value
license
stringclasses
101 values
size
int64
200
198k
sha
stringlengths
40
40
lang
stringclasses
1 value
ext
stringclasses
1 value
import torch from torch.autograd import Variable import time import os import sys from utils import AverageMeter, calculate_accuracy def train_epoch(epoch, data_loader, model, criterion, optimizer, opt, epoch_logger, batch_logger): print('train at epoch {}'.format(epoch)) model.train() ...
train.py
MIT
2,637
652643d091cb787a83ec58ec0e878fa5e6b7d1cd
Python
py
# -*- coding: utf-8 -*- """ Created on Sun Jul 4 12:59:27 2021 @author: talha """ import torch.nn as nn import torch.nn.functional as F import torch class Model(nn.Module): def __init__(self): super(Model, self).__init__() keep_rate=0.50 #contracting ...
code/Model.py
MIT
6,174
3aa99d6dbce3ee0f8e36344e97d9873102bd9b64
Python
py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain 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/LICENSE-2.0 # # U...
src/transformers/modeling_albert.py
Apache-2.0
58,075
4598b73ca8f46381106c8989d62ef47a9dd8633d
Python
py
# coding=utf-8 import numpy as np import scipy.sparse as sp import json import torch from sklearn.preprocessing import OneHotEncoder from sklearn.metrics import f1_score from util.nlp_utils import * def normalize(mx): """Row-normalize sparse matrix""" rowsum = np.array(mx.sum(1)) r_inv = np.power(rowsum, ...
src/models/CCIG/loader.py
BSD-3-Clause
7,174
45c5e0cc488f4cb3a94e9e673ef2c399b0c261e1
Python
py
import time import collections import os from typing import Optional, List, Tuple import torchvision import numpy as np import torch from trw.train import SequenceArray, SamplerRandom from ..basic_typing import ShapeX, Datasets, DatasetsInfo from ..transforms import Transform def _clutter(images, cluttered_size, cl...
src/trw/datasets/mnist_cluttered.py
MIT
5,600
1ec3d0370ca4d5f635510bfa43d7a36a98712c82
Python
py
import torch import logging import csv import os import gzip from torch.utils.data import Dataset from typing import List from transformers import GPT2TokenizerFast from pkg_resources import resource_filename import itertools from tqdm.auto import tqdm import numpy as np import sys csv.field_size_limit(sys.maxsize) l...
aitextgen/TokenDataset.py
MIT
14,461
3aa9b4d949d2f3218fd2b486d3ca341741d2ace8
Python
py
# -*- coding: utf-8 -*- """ # @file name : cifar_train.py # @author : zjgbz https://github.com/zjgbz # @date : 2021-04-22 # @brief : 模型训练主代码 """ import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(BASE_DIR, '..')) import argparse import torch.optim as...
src/cifar_train.py
MIT
5,907
b2bef807547a7b3a16f3f29261a9461722be4146
Python
py
import torch from .degree import degree_hyedge def contiguous_hyedge_idx(H): node_idx, hyedge_idx = H unorder_pairs = [(hyedge_id, sequence_id) for sequence_id, hyedge_id in enumerate(hyedge_idx.numpy().tolist())] unorder_pairs.sort(key=lambda x: x[0]) new_hyedge_id = -1 pre_hyedge_id = None ...
SuperMoon/hyedge/utils/verify.py
MIT
1,025
3aa9bacd09d28fff5ce8d6f30fef424f3fd955be
Python
py
import copy import datetime import random import time import numpy as np import torch import torch.backends.cudnn as cudnn from loguru import logger from torch import optim from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from pathlib import Path from iva...
ivadomed/training.py
MIT
21,804
1e890c838e3a3ecb6529c0d701f4187ac7163f25
Python
py
""" Agent - this is a class that has a unique id, and a step function which runs every cycle. It is in this step() function where their lifecycle exists. Things like check life state, buy product, make product, get paid, move to position... all happens here. Custom Classes which build on Agent: - BananaWorldAgents - ...
agents.py
Apache-2.0
27,628
7059fc5e5bde7d0a0fbcde3be479d1c373576b3e
Python
py
import os import numpy as np import random import copy import torch import torch.nn as nn from .system import prefix def setup_seed(seed): print(prefix(__name__) + 'seed is: ', seed) random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) tor...
rllib/basic/tools.py
MIT
5,875
3aa9da80182f6d44781d33a88e020b0460216abb
Python
py
from __future__ import division from __future__ import absolute_import #typing import torch from torch.nn import ParameterList, Parameter from allennlp.common.checks import ConfigurationError try: from itertools import izip except: izip = zip class ScalarMix(torch.nn.Module): u""" Computes a param...
pymagnitude/third_party/allennlp/modules/scalar_mix.py
MIT
3,392
12e6e7fee9cdc1f672859f6cac54842198b51391
Python
py
import warnings from functools import partial from typing import Any, Optional from torchvision.transforms.functional import InterpolationMode from ....models.segmentation.fcn import FCN, _fcn_resnet from ...transforms.presets import VocEval from .._api import Weights, WeightEntry from .._meta import _VOC_CATEGORIES ...
torchvision/prototype/models/segmentation/fcn.py
BSD-3-Clause
3,984
3aa9e533d62d738b1b27838ff4e1a195cb35e07d
Python
py
from math import pi import subprocess import logging from argparse import ArgumentParser, Namespace, ArgumentDefaultsHelpFormatter from pathlib import Path from typing import Tuple, Union import torch from torch import nn from torch.utils.data import DataLoader import pytorch_lightning as pl import transformers from t...
cort/model.py
MIT
18,767
e9ace96cb2f774e6bf40ac3da0398e0b194b6c2a
Python
py
#!/usr/bin/python3.6 ''' Trains a model. ''' import argparse, hashlib, logging, math, os, pprint, random, sys, time import multiprocessing from typing import * from collections import defaultdict, Counter import numpy as np import pandas as pd import torch import torch.nn as nn import torch.optim as optim import tor...
old_models/train_3d_se_resnext50__fixed_oversmp.py
Apache-2.0
18,478
d7529c439b8786e84f2f7bbf8befaef3db58c868
Python
py
import torch import time import musa_torch_extension from utils.diff import diff_cpu from utils.save import save_torch_to_txt def make_data(): seq_len = 200 batch_size = 32 feature_num = 512 hidden_size = 256 num_layers = 4 inp = torch.rand([seq_len, batch_size, feature_num]) bidirectional...
mtPytorchTest/test_bilstm_multilayer.py
MIT
3,092
fce764caa3b3ae3a5815db4aa875ee04cbcd51c7
Python
py
""" --- title: Relative Multi-Headed Attention summary: > Documented implementation with explanations of Relative Multi-Headed Attention from paper Transformer-XL. --- # Relative Multi-Headed Attention This is an implementation of relative multi-headed attention from paper [Transformer-XL: Attentive Language Mode...
labml_nn/transformers/xl/relative_mha.py
MIT
6,390
3aaa318944c4dcb311de3612c4039c9af3d9404a
Python
py
# Copyright 2018-2019 Open-MMLab. All rights reserved. import torch import os import mmcv from mmcv.runner import load_checkpoint from mmcv.parallel import MMDistributedDataParallel from .env import get_root_logger from .test import multi_gpu_test from ..datasets.dataloader import build_dataloader def test_network(...
pyvrl/apis/inference.py
MIT
2,398
e65fba7632e5d4d61af35d0d1ea90b0ccf104da1
Python
py
import cv2 import math import json import pickle import random import numpy as np from matplotlib import cm from pathlib import Path from torchvision.transforms import ToTensor from .utils import interp_l2_distance from .utils import l2_distance_to_trajectory_set, angle_to_trajectory_set from lidardet.datasets.base im...
lidardet/datasets/trajectory/covernet_dataset.py
Apache-2.0
16,047
8044e5682ed9c0f8bff493d45c3a4fe5e3b9e0c3
Python
py
import unittest import numpy as np import torch from torch.autograd import Variable, grad, gradcheck from qmctorch.wavefunction.jastrows.elec_elec_nuclei.jastrow_factor_electron_electron_nuclei import JastrowFactorElectronElectronNuclei from qmctorch.wavefunction.jastrows.elec_elec_nuclei.kernels.boys_handy_jastrow_ke...
tests/wavefunction/jastrows/elec_elec_nuc/test_three_body_jastrow_boys_handy.py
Apache-2.0
4,359
b2d31fef1c497064ac8254e5ff8ad35b26f38b7c
Python
py
import contextlib import sys import os import torch import unittest from torchvision import io from torchvision.datasets.video_utils import VideoClips, unfold from common_utils import get_tmp_dir @contextlib.contextmanager def get_list_of_videos(num_videos=5, sizes=None, fps=None): with get_tmp_dir() as tmp_dir...
test/test_datasets_video_utils.py
BSD-3-Clause
4,944
2488edc613d55b1a0c808685681648620b789b51
Python
py
# Copyright The PyTorch Lightning 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/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
pytorch_lightning/trainer/logging.py
Apache-2.0
6,628
3aaa84468eaa4542bc70a58faa46a68253c2a7b4
Python
py
from __future__ import absolute_import from __future__ import print_function import os import sys import functools import math import numpy as np import torch import torchvision import torchvision.transforms as transforms import torch.nn as nn import torch.nn.functional as F import torch.autograd # the next line can...
tests/onnx_matrix_mul/onnx_matrix_mul.py
Apache-2.0
8,956
3aaaa49953d34a8f5f8b462b084dea4006f620ee
Python
py
# ------------------------------------------------------------------------------------ # BaSSL # Copyright (c) 2021 KakaoBrain. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------------------ import c...
bassl/dataset/base.py
Apache-2.0
4,405
3aaab19e92b9231de82a55ef7b3f28a4dbd74186
Python
py
#!/usr/bin/env python3 from math import exp, pi import os import random import torch import unittest import gpytorch from torch import optim from gpytorch.kernels import SpectralMixtureKernel from gpytorch.likelihoods import GaussianLikelihood from gpytorch.means import ConstantMean from gpytorch.priors import Smooth...
test/examples/test_spectral_mixture_gp_regression.py
MIT
4,164
d7581c6c3193e1305efdd9400986fb4092fea375
Python
py
# -*- coding: utf-8 -*- """ This is a simple example of DNN using Pytorch's nn package and optim package """ import torch from torch.autograd import Variable # data type: CPU or GPU # dtype = torch.FloatTensor dtype = torch.cuda.FloatTensor # N batch: size # D_in: input size # D_out: output size # H: hidden size N, ...
tutorial/09_simple_dnn_optim.py
MIT
1,182
6515cf81f20c7c243acbbf86c883644e76f74bf2
Python
py
import torch import torch.nn as nn from torch import cuda from sentence_transformers import SentenceTransformer torch.manual_seed(0) cuda.manual_seed_all(0) class Encoder(nn.Module): def __init__(self, emb_size, hidden_size, dropout_rate): super(Encoder, self).__init__() self.hidden_layer = nn.Li...
MoRT/mort/adaptBias/model.py
MIT
3,164
7c2889c376512973856618a6a76fd7af20938796
Python
py
# *************************************************************************************** # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * # * # Permission is hereby granted, free of charge, to...
src/dbpedia_dataset.py
MIT-0
2,330
5e8dfd72f4c9a8418881c6b7927dd61c6966bdc9
Python
py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def hidden_init(layer): fan_in = layer.weight.data.size()[0] lim = 1. / np.sqrt(fan_in) return (-lim, lim) class Actor(nn.Module): """Actor (Policy) Model.""" def __init__(self, state_size, action_size, seed, f...
ddpg_model.py
MIT
2,853
3aaaf25b9fe0bfdc85d3f28baccac5beecd221d3
Python
py
import os import torch import pickle from itertools import chain import pandas as pd import numpy as np from rdkit.Chem import Descriptors from rdkit.Chem import AllChem from rdkit.Chem.rdMolDescriptors import GetMorganFingerprintAsBitVect from torch.utils import data from torch_geometric.data import Data from torch_g...
loader.py
MIT
31,298
652b0a110c064aa39254d41bfa11c287b45cc331
Python
py
import os import shutil import random import math import time import argparse import yaml from collections import OrderedDict import sys # for import parent utils sys.path.append('../') import utils import modules import datasets import models import numpy as np import torch import torch.nn as nn import torch.optim...
AttentionRouting/trainer.py
Apache-2.0
15,294
6b16493e233bc5bc5ae0622f930b3ff851b4ab9a
Python
py
import os import glob import json import random import os.path as osp from timeit import default_timer as timer from collections import deque import cv2 import numpy as np import torch import matplotlib.pylab as plt from skimage import io, transform from torch.utils.data import Dataset import wireframe.utils as utils...
wireframe/datasets.py
MIT
2,245
1e98fdc5a0155f56129246ac66e179702ac2528b
Python
py
from collections import OrderedDict import torch.distributed as dist from torch._utils import (_flatten_dense_tensors, _take_tensors, _unflatten_dense_tensors) def _allreduce_coalesced(tensors, world_size, bucket_size_mb=-1): """Allreduce parameters as a whole.""" if bucket_size_mb ...
mmpose/core/utils/dist_utils.py
Apache-2.0
1,703
3aab2af8593b7bcf7d540b0109d81994561b3b8e
Python
py
import torch import torch.nn.functional as F from torch import nn, einsum from einops import rearrange, repeat from einops.layers.torch import Rearrange # helper functions def exists(val): return val is not None def batched_index_select(values, indices, dim = 1): value_dims = values.shape[(dim + 1):] va...
en_transformer/en_transformer.py
MIT
8,943
fda283cb600a8a47a4b90f08c7a1cc23001c05ad
Python
py
from transformers import * import torch from torch.utils.data import DataLoader, RandomSampler, TensorDataset from keras.preprocessing.sequence import pad_sequences from utils import normalize_text, flat_accuracy import tempfile import pandas as pd import numpy as np import random import os import time class BertTex...
text_classifier/bert_text_classifier.py
MIT
15,668
03fccff4c4d29d7488f97fe9be2d19f034b28e95
Python
py
from functools import partial import multiprocessing from pathlib import Path from PIL import Image from random import random import torch from torch import nn from torch.optim import Adam from torch.utils import data from torch.utils.data.distributed import DistributedSampler from torchvision import transforms EXTS =...
stylegan2_deepspeed/dataset.py
MIT
3,058
3aab3e20f81a350a827c4ee7a43091979ef3d0a4
Python
py
import numpy as np from skimage import io, color import torch from PIL import Image from torch.utils.data import Dataset, DataLoader, TensorDataset import torchvision.transforms as T batch_size = 128 offsets = (47.5, 2.4, 7.4) scales = (25.6, 11.2, 16.8) def norm_lab_to_rgb(L, ab, norm=True): '''given an Nx1xWxH...
experiments/colorization_minimal_example/data.py
MIT
2,479
3aab4bdf06d4aae13de4d0ca70fa1a3c7450fdd6
Python
py
from collections import defaultdict import os import numpy as np import matplotlib.pyplot as plt import torch def one_cold(i, n): """Inverse one-hot encoding.""" x = torch.ones(n, dtype=torch.bool) x[i] = 0 return x class GridBasedPooling(torch.nn.Module): def __init__(self, cell_side=2.0, n=4, ...
Social-NCE_U-LSTM/gridbased_pooling.py
MIT
17,386
12bff2b81008eeb8dacf328a367ce18336b5a37f
Python
py
# -*- encoding: utf-8 -*- # @File : base.py # @Time : 2021/05/20 11:55:32 # @Author : Ugur Gudelek # @Contact : ugurgudelek@gmail.com # @Desc : None import torch from torch.utils.data import Dataset, Subset, ConcatDataset class BaseTorchDataset(Dataset): def __init__(self): super(Base...
berries/datasets/base.py
MIT
773
3aaba77b886b237b5d8a012096cdc65790b41f3d
Python
py
import numpy as np import torch from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt from sklearn.utils.multiclass import unique_labels from sklearn.metrics import roc_curve, auc class Scale(object): def __call__(self, sample): heartbeat, label = sample['cardiac_cycle'], ...
codes/utils/transform.py
MIT
4,586
45d48cbde8e5254bfca738b8f3d7d9e75bdffd35
Python
py
# -*- coding: utf-8 -*- """ @date: 2020/8/22 下午8:50 @file: step_lr.py @author: zj @description: """ import torch.optim as optim from torch.optim.optimizer import Optimizer from .. import registry @registry.LR_SCHEDULERS.register('StepLR') def build_step_lr(cfg, optimizer): assert isinstance(optimizer, Optimiz...
tsn/optim/lr_schedulers/step_lr.py
Apache-2.0
494
4247d49cf7c36ff1c40c479e0e403bd91143d45b
Python
py
# -*- coding: utf-8 -*- """ @date: 2020/4/3 下午8:07 @file: custom_bbox_regression_dataset.py @author: zj @description: """ import os import cv2 import numpy as np import torch import torchvision.transforms as transforms from torch.utils.data import Dataset from torch.utils.data import DataLoader import utils.util as ...
py/utils/data/custom_bbox_regression_dataset.py
Apache-2.0
4,418
3aabd90cbbc923c235a758020f70fb11e0dc05f2
Python
py
""" `Model` is an abstract class representing an AllenNLP model. """ import logging import os from typing import Dict, Union, List, Set, Type, Optional try: from apex import amp except ImportError: amp = None import numpy import torch from allennlp.common.checks import ConfigurationError from allennlp.common...
allennlp/models/model.py
Apache-2.0
21,230
f9c6496fe5361c8a44fa09e2b03f601cdd248e1a
Python
py
# encoding: utf-8 import os import torch import torch.distributed as dist import sys paths = os.getcwd().split("/")[0:-1] base_path = "/".join(paths) nets_path = os.path.join(base_path, "netspresso-compression-toolkit") sys.path.append(nets_path) from yolox.data import get_yolox_datadir from yolox.exp import Exp as My...
exps/example/yolox_voc/yolox_voc_m.py
Apache-2.0
4,436
3aabe325f2dec9adfad60be1c05c5afe8d8831b3
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Normal import numpy as np from copy import deepcopy import sys try: #sys.path.append('../torchkit/torchkit') # Chin-Wei's NAF code for NAF from torchkit import nn as nn_, flows, utils from torchkit.transform...
model.py
MIT
24,559
6517381b519aa2c7307f0a0988c41873df749f84
Python
py
import random import torch import torch.nn as nn import torch.nn.functional as F class Residual(nn.Module): def __init__(self, in_channels, num_hiddens, num_residual_hiddens): super(Residual, self).__init__() self._block = nn.Sequential( nn.ReLU(True), nn.Conv2d(in_channels...
query_old/graph/vae_v3.py
MIT
9,218
6501b7d40506f809a2f3cbb47e328b17c6e6f0d9
Python
py
import torch from syft.generic import object_storage def test_clear_objects(): """ Checks the clear_objects method """ obj_storage = ( object_storage.ObjectStore() ) # obj_storage is a wrapper object to a collection of objects x = torch.tensor(1) obj_storage.set_obj(x) obj...
test/generic/test_object_storage.py
Apache-2.0
919
5e69516da451569c1cf67ee1d374d042b88830d4
Python
py
# Copyright 2020 MONAI Consortium # 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 applicable law or agreed to in writing, s...
examples/segmentation_3d/unet_training_array.py
Apache-2.0
6,942
3aac22bff7588a9698dc3aa91ff006bc7366f69c
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch import torch.nn.functional as F from torch import nn from lib.layers import ROIAlign from .utils import cat class LevelMapper(object): """Determine which FPN level each RoI in a set of RoIs should map to based on the heuris...
lib/modeling/poolers.py
MIT
4,536
3aac3e3a2589556c7be0d67c6e3e2e68afb7d005
Python
py
from __future__ import print_function import os import os.path import h5py import numpy as np import arrow import json import torch class H5Logger(object): Default_Auto_Incr_Format = '{0:06d}' def __init__( self, filename='data.hdf5', auto_incr=False, auto_i...
h5_logger/h5_logger.py
MIT
4,449
3aac3faa70ee43003276f343e6de4719bcec1520
Python
py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import math import warnings import torch from pyro.distributions.util import is_identically_zero from pyro.infer.elbo import ELBO from pyro.infer.enum import get_importance_trace from pyro.infer.util import get_dependent_plate_di...
pyro/infer/renyi_elbo.py
Apache-2.0
9,308
3aac4854ba897751515f137cb6303c8e38dc909f
Python
py
import os import streamlit as st import joblib import torch import json import base64 import uuid import re import jupytext from bokeh.models.widgets import Div import math import importlib.util def import_from_file(module_name: str, filepath: str): """ Imports a module from file. Args: module_na...
app/util/utils.py
MIT
8,819
039c3d802405f3b542775f055fd2f32bd4118b2d
Python
py
import math import tree import torch import sympy import random import graph_utils import numpy as np import pickle as pkl from random import randint from operator import itemgetter from sympy.parsing.sympy_parser import parse_expr class SymbolsManager(): def __init__(self, whether_add_special_tags): se...
src/data_utils.py
Apache-2.0
6,654
5f3454d577b0e794992f037daa15c597e27893b7
Python
py
""" ################################################################################################## # Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved. # Filename : gaspin_transformation.py # Abstract : Implementations of the gaspin transformation # C...
davarocr/davarocr/davar_rcg/models/transformations/gaspin_transformation.py
Apache-2.0
11,675
3aac5e7dcadf6973872c4f2178e02339db0769c0
Python
py
import torch import numpy as np from torch import nn from torch.nn import BatchNorm1d from torch.autograd import Function import torch.nn.functional as F def _make_ix_like(input, dim=0): d = input.size(dim) rho = torch.arange(1, d + 1, device=input.device, dtype=input.dtype) view = [1] * input.dim() v...
src/nn_utils.py
MIT
8,268
3aac8a7a88684f371bc8c3b31eec060de7d9a832
Python
py
import transformers import torch from lm_eval import utils from lm_eval.base import BaseLM from tqdm import tqdm class XGLM(BaseLM): def __init__(self, device='cuda', pretrained='facebook/xglm-1.7B', revision='main', subfolder=None, tokenizer=None, batch_size=1): super().__init__() assert isinstan...
lm_eval/models/xglm.py
MIT
4,183
3aac8f9ead27978623a7f751081aec5ec2c5255d
Python
py
import torch import torch.nn as nn class DenseLayer(nn.Sequential): def __init__(self, in_channels, growth_rate): super().__init__() self.add_module('norm', nn.BatchNorm2d(in_channels)) self.add_module('relu', nn.ReLU(True)) self.add_module('conv', nn.Conv2d(in_channels, g...
network/layers.py
Apache-2.0
3,092
5fbdbceeab7332d44aebff3d6439158a6796fc30
Python
py
from typing import Callable import torch from autoPyTorch.pipeline.components.setup.network_initializer.base_network_initializer import ( BaseNetworkInitializerComponent ) class SparseInit(BaseNetworkInitializerComponent): """ Fills the 2D input Tensor as a sparse matrix """ def weights_init(se...
autoPyTorch/pipeline/components/setup/network_initializer/SparseInit.py
Apache-2.0
1,077
1e6dbdbf3c41a6fac83a2f09abfe5a37bc3cd2b0
Python
py
from functools import partial from typing import Any, Optional from torchvision.prototype.transforms import VocEval from torchvision.transforms.functional import InterpolationMode from ....models.segmentation.fcn import FCN, _fcn_resnet from .._api import WeightsEnum, Weights from .._meta import _VOC_CATEGORIES from ...
torchvision/prototype/models/segmentation/fcn.py
BSD-3-Clause
3,823
108e6c13860189d08684974e47df428a0888e26c
Python
py
""" Implementation of EfficientDet object detection network Reference: EfficientDet: Scalable and Efficient Object Detection - https://arxiv.org/abs/1911.09070 This version supports init from pretrained weights and easy changing of many hyper-parameters hacked by @bonlime """ import logging from copy import deepcopy fr...
pytorch_tools/detection_models/efficientdet.py
MIT
14,227
3aad21d42567eb65fb536225e0628db569550515
Python
py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
nemo/collections/tts/modules/fastspeech2_submodules.py
Apache-2.0
5,170
b2403d98ea0ed3f184edaf6fe6717f67c34061e6
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import kaiming_init, xavier_init, normal_init from mmdet.core import auto_fp16, force_fp32, sanitize_coordinates from ..registry import HEADS from ..utils import ConvModule @HEADS.register_module class RdsMaskHead(nn.Module): """Mul...
mmdet/models/mask_heads/rdsnet_mask_head.py
Apache-2.0
13,827
5e4874a351198af4caf30aa2cc89dfb70b5d7881
Python
py
"""This module implements an abstract base class (ABC) 'BaseDataset' for datasets. It also includes common transformation functions (e.g., get_transform, __scale_width), which can be later used in subclasses. """ import random import numpy as np import torch import torch.utils.data as data from PIL import Image import...
data/base3D_dataset.py
BSD-3-Clause
3,700
3aad641d2fc3991a29adbf3aff101a8ba0df1ba1
Python
py
# coding: utf-8 import datetime import os import random import re import string import time from collections import Counter import numpy as np import pandas as pd import torch import torch.nn as nn import torch.optim import torch.tensor as tensor import torch.utils.data from keras.preprocessing.sequence import pad_s...
quora/kernels/quora-6-milestone-2.py
MIT
18,574
6b3a24620961bb950a48133180b8c7e4d97b5131
Python
py
import torch import torch.nn.functional as F import os import argparse from tqdm import trange from transformers import GPT2LMHeadModel, GPT2Config, BertTokenizer def is_word(word): for item in list(word): if item not in "qwertyuiopasdfghjklzxcvbnm": return False return True def _is_chin...
generate.py
MIT
8,745
10729edde9aa51459078e133a014bf6698c6225e
Python
py
import torch import torch.nn as nn import torch.nn.functional as F class BaseModel(nn.Module): def __init__(self, num_classes): super().__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=7, stride=1) self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1) self.conv3 = nn.Conv2d(...
code/Resnet50/model.py
MIT
1,361
d75e7390cffe8dcad0554745731a090b0a51ab97
Python
py
# Owner(s): ["module: dataloader"] import math import sys import errno import multiprocessing import os import ctypes import faulthandler import torch import gc import time import signal import unittest import itertools import warnings import tempfile from torch import multiprocessing as mp from torch.utils.data impor...
test/test_dataloader.py
Intel
107,000
5e9415afc7a72fd5fbf26bb5d8f0aee96a1d5783
Python
py
#!/usr/bin/env python3 # encoding: utf-8 # @Time : 2018/8/2 下午3:23 # @Author : yuchangqian # @Contact : changqian_yu@163.com # @File : engine.py import os import os.path as osp import time import argparse import torch import torch.distributed as dist from utils.logger import get_logger from utils.pyt_utils imp...
engine.py
MIT
4,796
3aada45843daeffb1036888f95a2b3baf476d3be
Python
py
# %% import os import torch from pytorch_lightning import LightningModule, Trainer from torch import nn from torch.nn import functional as F from torch.utils.data import DataLoader, random_split from torchmetrics import Accuracy from torchvision import transforms from torchvision.datasets import MNIST PATH_DATASETS =...
lightning_examples/mnist-hello-world/hello-world.py
Apache-2.0
7,425
03e234816c0bab46744e26153b122680196e83bf
Python
py
import torch import numpy as np from torch import nn from typing import Any, Dict, List, Type, Optional from tianshou.policy import A2CPolicy from tianshou.data import Batch, ReplayBuffer, to_torch_as class PPOPolicy(A2CPolicy): r"""Implementation of Proximal Policy Optimization. arXiv:1707.06347. :param to...
tianshou/policy/modelfree/ppo.py
MIT
7,676
e66a5f88249c815a14e6b76d0270bb6b2e58a3b2
Python
py
import logging import torch from tools.registry import registry logger = logging.getLogger(__name__) class ScaledSupConLoss(torch.nn.Module): """Scaled Supervised Contrastive Learning: https://arxiv.org/pdf/2004.11362.pdf. It also supports the unsupervised contrastive loss in SimCLR""" def __init__( ...
mmt/losses.py
MIT
7,910
d71b98c999f7e2a851984f5cd0ae9bf5c2d3e34f
Python
py
import pytest import torch from toma import cpu_memory @pytest.mark.forked def test_cpu_mem_limit(): # 128 MB (128/4M float32) tensor = torch.empty((128, 1024, 1024 // 4), dtype=torch.float32) tensor.resize_(1) cpu_memory.set_cpu_memory_limit(0.25) # 512 MB (128/4M float32) with pytest.rais...
tests/test_cpu_mem_limit.py
MIT
403
dfa3043cc44c166e37bb3ed7a6c976e1b9cd0393
Python
py
""" Main model implementation """ import torch from .encoder import ImageEncoder from .code import PositionalEncoding from .model_util import make_encoder, make_mlp import torch.autograd.profiler as profiler from util import repeat_interleave import os import os.path as osp import warnings import torch.nn.functional as...
src/model/models.py
BSD-2-Clause
13,841
b2a6fa01d352b45f64bd8cef314424791d93d56f
Python
py
import base import torch import torchvision import json # 声明模型路径 PATH = './data/AlexNet_animals.pth' # 读取部分测试数据 dataiter = iter(base.testloader) images, labels, image_path = dataiter.next() # 实例化网络并加载训练完成的模型 # net = base.MyCustomNet() print(len(base.classes)) net = base.AlexNet(len(base.classes)) net.load_state_dic...
MY_ANIMALS/evaluate.py
MIT
2,553
5f0d54b75044cd5d542a5a85294676c26a67d44a
Python
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import cv2 import numpy as np from progress.bar import Bar import time import torch from external.nms import soft_nms from models.decode import ctdet_angle_decode from models.utils import flip_tensor from util...
src/lib/detectors/ctdet_angle.py
MIT
3,949
3aae08f13ad0fe0c9bbc26e1ef9641905bed4336
Python
py
#!/usr/bin/env python3 #使用交集融合而不是简单相加 import argparse import logging from pathlib import Path import sys import time from typing import Any from typing import Optional from typing import Sequence from typing import Tuple from typing import Union import humanfriendly import numpy as np import torch from typeguard import...
espnet2/bin/asr_inference_ilme_intersect.py
Apache-2.0
22,471
3aae109724af351f57be114e38f53a63b96ea669
Python
py
import os import shutil import subprocess import time from autonmt.bundle import utils from autonmt.toolkits.base import BaseTranslator from fairseq import options import torch from fairseq import options from fairseq_cli import preprocess, train, generate from fairseq.distributed import utils as distributed_utils f...
autonmt/toolkits/fairseq.py
MIT
13,302
12eaa7a5c5a3af205442fbac90290dc91f1243c5
Python
py
#!/usr/bin/env python3 import time import unittest from itertools import product from typing import NamedTuple import torch import torch.nn.functional as F from pytorch_translate.dictionary import Dictionary from pytorch_translate.research.adversarial import adversaries from pytorch_translate.tasks.pytorch_translate_...
pytorch_translate/research/test/test_adversaries.py
BSD-3-Clause
10,126
fd66139846b03f3ed4432490b35151527143faf2
Python
py
# coding=utf-8 # Copyright 2018 The Microsoft Research Asia LayoutLM 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/...
src/transformers/models/layoutlm/modeling_layoutlm.py
Apache-2.0
51,816
3aae3c62dd057565a8649cbe509a74cee1450dfe
Python
py
"""Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. Portions of the source code are from the OLTR project which notice below and in LICENSE in the root directory of this source tree...
loss/SoftmaxLoss.py
BSD-3-Clause
495
3aae4354508f2305582aa2f41d6aca02af8712b5
Python
py
import os import numpy as np import torch from torch.utils.data import DataLoader from data import task_a, task_b, task_c, all_tasks, read_test_file, read_test_file_all from config import OLID_PATH from cli import get_args from utils import load from datasets import HuggingfaceDataset, HuggingfaceMTDataset, ImbalancedD...
train.py
CC-BY-4.0
5,321
28f2b0edf036ff3c49f5635fe22ca94827573893
Python
py
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # 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://w...
training/network_training/nnUNet_variants/architectural_variants/nnUNetTrainerV2_GN.py
Apache-2.0
7,404
70a14d025bc1a5af12a3aeb2f4b6586956d700f3
Python
py
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under the BSD 3-Clause License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://opensource.org/licenses/BSD-...
built-in/PyTorch/Official/cv/image_classification/ResNet50_for_PyTorch/DistributedResnet50/image_classification/mixup.py
Apache-2.0
2,172
ff9830430654da662372bca99bc32e9f60614148
Python
py
import glob import logging import math import os import platform import random import shutil import subprocess import time from contextlib import contextmanager from copy import copy from pathlib import Path import cv2 import matplotlib import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as...
YOLOV5+DEEPSORT/yolov5/utils/general.py
MIT
53,153
fdd2f47233fcf918dcb42b9a9810c6d7824a00f2
Python
py
#!/usr/bin/env python3 # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import os im...
examples/interactive_asr/utils.py
BSD-2-Clause
6,127
3aae6c6864b405648104214f839c1a7eb979c3a7
Python
py
"""Example of classifying data using topological layers.""" from torch_topological.datasets import SphereVsTorus from torch_topological.nn.data import make_tensor from torch_topological.nn import VietorisRipsComplex from torch_topological.nn.layers import StructureElementLayer from torch.utils.data import DataLoade...
torch_topological/examples/classification.py
BSD-3-Clause
1,916
3aae771d1ab865cb5ecab07c7fb989bc911bf757
Python
py
import torch from torch import nn as nn try: from inplace_abn.functions import inplace_abn, inplace_abn_sync has_iabn = True except ImportError: has_iabn = False def inplace_abn(x, weight, bias, running_mean, running_var, training=True, momentum=0.1, eps=1e-05, activation="leaky_re...
timm/models/layers/inplace_abn.py
Apache-2.0
3,353
3aae7cf563edfe6c9d2bf1a9f3994d911aacea23
Python
py
import itertools from collections import OrderedDict import torch.nn as nn import torch import torch.nn.functional as F __all__ = ['bLVNet_TAM_BACKBONE', 'blvnet_tam_backbone'] model_urls = { 'blresnet50': 'pretrained/ImageNet-bLResNet-50-a2-b4.pth.tar', 'blresnet101': 'pretrained/ImageNet-bLResNet-101-a2-b...
core/models/blvnet_tam_backbone.py
Apache-2.0
15,804
45627f0064ec7c1d59c0e35c6f6233d284167451
Python
py
import matplotlib.pyplot as plt import numpy as np import torch def decode_seg_map_sequence(label_masks, dataset='pascal'): rgb_masks = [] for label_mask in label_masks: rgb_mask = decode_segmap(label_mask, dataset) rgb_masks.append(rgb_mask) rgb_masks = torch.from_numpy(np.array(rgb_masks)...
dataloaders/utils.py
MIT
3,696
3aaeabe920faac4470ce7c6a09594f3898f7c939
Python
py
from torch.utils.data import Dataset import numpy as np from h5py import File import scipy.io as sio from utils import data_utils from matplotlib import pyplot as plt class H36motion3D(Dataset): def __init__(self, path_to_data, actions, input_n=20, output_n=10, dct_used=15, split=0, sample_rate=2): """ ...
utils/h36motion3d.py
MIT
2,317
3aaeb1a8f1191b41fe98886ed2529890a931fcec
Python
py
import math import itertools import numpy as np import torch from torch import nn from torch.nn import functional as F from .utils import get_knn_faiss, cartesian_product, bool_flag from .utils import get_gaussian_keys, get_uniform_keys from .query import QueryIdentity, QueryMLP, QueryConv MemoryDefaultDict = { "...
pytorch_transformers/memory_pkm/memory.py
Apache-2.0
32,455
e6346df6951dec4a806c92b90cbeb4f945cc65eb
Python
py
from __future__ import print_function, division import argparse import logging import numpy as np from pathlib import Path from tqdm import tqdm from torch.utils.tensorboard import SummaryWriter import torch import torch.nn as nn import torch.optim as optim from core.raft_stereo import RAFTStereo from evaluate_stere...
train_stereo.py
MIT
10,170
7c3897f6c15287aa2d486cef1114632dcc6b89bc
Python
py
"""Implements a Mixture Density LSTM Network for predicting the future latents based on past latents """ import torch import torch.nn as nn import torch.nn.functional as f from torch.distributions.normal import Normal class _MixtureDensityLSTMBase(nn.Module): def __init__(self, NUM_LATENTS: int, NUM_ACTIONS: ...
mdrnn/MixtureDensityLSTM.py
MIT
6,245
b24778b37fb97bfba23594088d5a384212445abb
Python
py
# Software Name: AIVC # SPDX-FileCopyrightText: Copyright (c) 2021 Orange # SPDX-License-Identifier: BSD 3-Clause "New" # # This software is distributed under the BSD-3-Clause license. # # Authors: Theo Ladune <theo.ladune@orange.com> # Pierrick Philippe <pierrick.philippe@orange.com> import torch import torc...
src/layers/entropy_coding/entropy_coder.py
BSD-3-Clause
887
3aaed44b270aac12480011277d819e2c18bf5d3c
Python
py
# This file contains experimental modules import numpy as np import torch import torch.nn as nn from models.common import Conv, DWConv class CrossConv(nn.Module): # Cross Convolution Downsample def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): # ch_in, ch_out, kernel, stride, groups, ...
intelligencelayer/shared/models/experimental.py
Apache-2.0
5,744
3aaf48590dcfebe18039aab53e2b279fb379504d
Python
py
import math import numpy as np import pytest import torch from sklearn.metrics import average_precision_score as sk_average_precision from torchmetrics.functional.retrieval.average_precision import retrieval_average_precision @pytest.mark.parametrize(['sklearn_metric', 'torch_metric'], [ pytest.param(sk_average...
tests/functional/test_retrieval.py
Apache-2.0
1,020
3aaf60d607d5a090f5cd55f2a7766feb1f0607d0
Python
py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # Note: this file is modeled after td3.py import logging from typing import Dict, Optional import reagent.core.types as rlt import torch from reagent.core.dataclasses import dataclass, field from reagent.core.parameters imp...
reagent/model_managers/discrete/discrete_crr.py
BSD-3-Clause
12,552
3aaf649f978a7617da4d24d6dd6c898f0724147a
Python
py
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # 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://w...
nnunet/network_architecture/generic_modular_UNet.py
Apache-2.0
20,009
3aaf7360b245861c37736f6f2f157bdb0ba1ba46
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import torch from fvcore.common.benchmark import benchmark from pytorch3d.renderer.points.rasterize_points import ( rasterize_points, rasterize_points_python, ) from pytorch3d.structures.pointclouds import Pointclouds def _bm_python_wi...
tests/bm_rasterize_points.py
BSD-3-Clause
1,901
3aaf77c3b5ef71d390737772acad4790800ef0d8
Python
py
from torch import nn class ConvWithBatchNorm(nn.Module): def __init__( self, in_channels, out_channels, spacetime_ndim, kernel_size=3, normalization=None, # "batch", activation="ReLU", ): super(ConvWithBatchNorm, self).__init__() self.i...
aydin/nn/layers/conv_with_batch_norm.py
BSD-3-Clause
1,408
e9058ae88751851005c7cc812438446a30e51edc
Python
py