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
# 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/plugins/training_type/single_tpu.py
Apache-2.0
4,327
f9fa415e67090bc637b3b21cf836133ec83413ab
Python
py
# torch imports import torch.nn.functional as F import torch.nn as nn ## TODO: Complete this classifier class BinaryClassifier(nn.Module): """ Define a neural network that performs binary classification. The network should accept your number of features as input, and produce a single sigmoid value, t...
Project_Plagiarism_Detection/source_pytorch/model.py
MIT
1,953
b2ac8b0fbe6ddc4188042674058092066dcb3bce
Python
py
# PROGRAMMER: Abdullah Bahi # DATE CREATED: 6/20/2020 # PURPOSE: Contains configurations for loading data and training the model # # VARIABLES: # - transforms_dict : dictionary of desired transformations on training and validation sets # - train_batch_size : training dataset batch size # ...
config.py
MIT
2,604
3a7bceb4a924e285a14adde02942d67054cf3041
Python
py
# Copyright 2021, Crepaldi Michele. # # Developed as a thesis project at the TORSEC research group of the Polytechnic of Turin (Italy) under the supervision # of professor Antonio Lioy and engineer Andrea Atzeni and with the support of engineer Andrea Marcelli. # # Licensed under the Apache License, Version 2.0 (the "L...
src/Model/gen3_speed_evaluation.py
Apache-2.0
32,507
fd7858295596b0db6d000678131cd13adaad2f01
Python
py
import os from setuptools import setup from torch.utils.cpp_extension import CUDAExtension, BuildExtension, _find_cuda_home os.system('pip uninstall -y tcmm') #os.system('make clean; make -j%d' % os.cpu_count()) CUDA_DIR = _find_cuda_home() #NCCL_DIR= '/home/comp/15485625/downloads/nccl_2.4.8-1+cuda10.1_x86_64' #MPI...
packages/tcmm/setup.py
MIT
1,504
f96b832f284efb30e6dd2fd12ab8212fe741e4a8
Python
py
import pytest import torch import torch.testing from rllib.policy import EpsGreedy from rllib.util.parameter_decay import ExponentialDecay from rllib.util.utilities import tensor_to_distribution from rllib.value_function import NNQFunction @pytest.fixture(params=[0.0, 0.9]) def eps_start(request): return request...
rllib/policy/q_function_policy/tests/test_epsilon_greedy.py
MIT
1,337
b230c848f295a329120d60e201bd785c17a3d8a7
Python
py
import torch import torch.nn as nn from options import HiDDenConfiguration from model.conv_bn_relu import ConvBNRelu from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence class Decoder(nn.Module): """ Decoder module. Receives a watermarked image and extracts the watermark. The input ima...
model/decoder.py
MIT
3,035
3a7c20e6633fef2271501aa4308092abe541e757
Python
py
""" The main file to train a JKNet model using a full graph """ import argparse import copy import torch import torch.optim as optim import torch.nn as nn import numpy as np from dgl.data import CoraGraphDataset, CiteseerGraphDataset from tqdm import trange from sklearn.model_selection import train_test_split from mo...
examples/pytorch/jknet/main.py
Apache-2.0
4,923
3a7c32ccb37a7633b5c7f5c88a67edeae2631a6e
Python
py
from __future__ import division import torch import math import random from PIL import Image, ImageOps try: import accimage except ImportError: accimage = None import numpy as np import numbers import types import collections def _is_pil_image(img): if accimage is not None: return isinstance(img, ...
torchvision/transforms.py
BSD-3-Clause
19,002
4b0675a644fc9cfcd6a0d2473a5cf622c926d3f5
Python
py
import math import torch from enum import Enum from torch import nn from typing import Optional, cast __all__ = ["MultiheadInitType", "ElementwiseTransformType", "SetTransformer", "ISAB", "PMA"] class MultiheadInitType(Enum): """Initialization type for multihead attetion.""" XAVIER = 0 KAIMING = 1 cla...
mi_module_zoo/settransformer.py
MIT
17,865
3a7c4dfc6b5026d5ba0442042e46299529047a51
Python
py
import math import sys import time import torch import torchvision.models.detection.mask_rcnn from .coco_utils import get_coco_api_from_dataset from .coco_eval import CocoEvaluator from . import utils def train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq): model.train() metric_logger ...
utils_cv/detection/references/engine.py
MIT
3,791
3a7c51c68ebc336b9c2595dfb01d0dfeb0c79d74
Python
py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import unittest import numpy as np import torch from common_testing import TestCaseMixin from pytorch3d.commo...
tests/test_rendering_utils.py
MIT,BSD-3-Clause
9,334
3a7c668d91d4b15259b0b38ceb450d322550885e
Python
py
from torch.utils.trainer.plugins.plugin import Plugin import matplotlib.pyplot as plt import math import os class HistoryPlugin(Plugin): def __init__(self, parameters): super(HistoryPlugin, self).__init__([(1, 'epoch')]) self.history = {} self.trainer = None for parameter in para...
src/utils/HistoryPlugin.py
MIT
1,965
3a7c69d7000e0fc6c37733b3e4e2a8d7bea4035e
Python
py
import os import numpy as np import onnxruntime import pytest import torch import tests.base.develop_pipelines as tpipes import tests.base.develop_utils as tutils from pytorch_lightning import Trainer from tests.base import EvalModelTemplate def test_model_saves_with_input_sample(tmpdir): """Test that ONNX mode...
tests/models/test_onnx.py
Apache-2.0
3,859
d7cc7cffaec3f78aa3eb0db89e0dbf152c208cd7
Python
py
#!/usr/bin/env python3 """ Preprocesses datasets """ import json import logging import os import numpy as np import pathlib import PIL.Image from moviepy.video.io.VideoFileClip import VideoFileClip import platalea.hardware import soundfile import torch import torch.nn as nn import torchvision.models as models impor...
platalea/utils/preprocessing.py
Apache-2.0
18,858
3a7c8c189a298eb81350b0d09849d3a37b931159
Python
py
''' Reference: https://github.com/khurramjaved96/incremental-learning/blob/autoencoders/model/resnet32.py https://github.com/hshustc/CVPR19_Incremental_Learning/blob/master/cifar100-class-incremental/modified_resnet_cifar.py ''' import torch import torch.nn as nn import torch.nn.functional as F from convs.modified_line...
convs/modified_cifar_resnet.py
MIT
6,161
3a7c9c2d341ea52eeb439fc90b46e8438b56a054
Python
py
import torch import torchvision #import skimage.io as io import numpy as np import torchvision.transforms as t import torch.nn as nn import os import matplotlib.pyplot as plt import torchvision.models as model #from sklearn.metrics import accuracy_score torch.cuda.set_device(0) #device=torch.device(#"cuda" i...
DeepFeatureExtraction/EXTRACTOR_ResNet50.py
MIT
12,171
1e0f78c23e82116f27c1f4c9b9d0f7c04001dcaa
Python
py
import json import os import time from datetime import timedelta import numpy as np import torch from guacamol.utils.data import remove_duplicates from torch.utils.data import TensorDataset from .rnn_model import SmilesRnn from .smiles_char_dict import SmilesCharDictionary def get_tensor_dataset(numpy_array): ...
guacamol_baselines/smiles_lstm_hc/rnn_utils.py
MIT
6,165
3a7ca51c7bae8b586fe02bad14a0f4accd482f9f
Python
py
# ============================================================================= # IMPORTS # ============================================================================= import argparse import os import numpy as np import torch import espaloma as esp from torch.nn.parallel import DistributedDataParallel as DDP from ...
scripts/phalkethoh_boltzmann/test.py
MIT
3,174
5e3a0ec82bc1120ad7510bcda504b492d1ed1e79
Python
py
import torch class TestInfo(object): def test_info(self): if not torch.cuda.is_available(): return from rflib.ops import get_compiler_version, get_compiling_cuda_version cv = get_compiler_version() ccv = get_compiling_cuda_version() assert cv is not None ...
tests/test_ops/test_info.py
Apache-2.0
345
12d61093e75bf0109d3b559fd9188d4033c8fa0a
Python
py
import torch import itertools from util.image_pool import ImagePool from .base_model import BaseModel from . import networks import numpy as np import copy class InstaGANModel(BaseModel): def name(self): return "InstaGANModel" @staticmethod def modify_commandline_options(parser, is_train=True): ...
instagan/models/insta_depth_model.py
Apache-2.0
17,892
3a7cc5d3b06cedc819450eb5d581489da7b886e2
Python
py
import os, sys import pydiffvg import argparse import torch # import torch as th import scipy.ndimage.filters as filters # import numba import numpy as np from skimage import io sys.path.append('./textureSyn') from patchBasedTextureSynthesis import * from make_gif import make_gif import random import ttools.modules fr...
apps/texture_synthesis.py
Apache-2.0
6,998
3a7ccce083bdccfa56a61bfc27ec049742ed117f
Python
py
""" BertCapModel is using huggingface transformer bert model as seq2seq model. The result is not as goog as original transformer. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.nn as nn import torch.nn.functional as F import...
captioning/models/BertCapModel.py
MIT
4,001
3a7ccec2c40b2a171393059ec1a3af511163c246
Python
py
# Copyright (c) 2017-present, Facebook, Inc. # # 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...
lib/core/test_engine.py
MIT
20,060
3a7ce96dc9526d0dad0dc5060086021159eb3ca5
Python
py
import pytest import torch from mmcls.models import build_loss def test_asymmetric_loss(): # test asymmetric_loss cls_score = torch.Tensor([[5, -5, 0], [5, -5, 0]]) label = torch.Tensor([[1, 0, 1], [0, 1, 0]]) weight = torch.tensor([0.5, 0.5]) loss_cfg = dict( type='AsymmetricLoss', ...
tests/test_losses.py
Apache-2.0
6,545
fdc7c27600c921e791f17eafc7ec0dffbd104b4a
Python
py
import torch.nn as nn import torch.utils.model_zoo as model_zoo import torch __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'https://download.pytorch.org/models/...
training/resnet.py
BSD-3-Clause
8,970
52b0876191c22f148d3d0e92d5108e48a53bdeae
Python
py
import dgl import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.multiprocessing as mp import dgl.nn.pytorch as dglnn import time import math import argparse from torch.nn.parallel import DistributedDataParallel import tqdm import os.path as...
benchmarks/ogbn-papers100M/train_dgl_multi_node.py
Apache-2.0
15,595
3a7cf84a5d2d444f18b4d90fd6bdb4fc01b1fbee
Python
py
import os from data import common import numpy as np import imageio import torch import torch.utils.data as data class Demo(data.Dataset): def __init__(self, args, name='Demo', train=False, benchmark=False): self.args = args self.name = name self.scale = args.scale self.idx_scale...
src/data/demo.py
MIT
1,076
b29ce9fde18928468e93d7a79c1dad18f3b62738
Python
py
import torch import torch.utils.data from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image import numpy as np from src.Models.loss import losses_joint from src.Models.models import Encoder from src.Models.models import Imit...
get_test_stats.py
MIT
6,229
5f9a236e6d19cad2ae599c49f32e09d6db36cf4d
Python
py
# Copyright (c) OpenMMLab. All rights reserved. import copy import mmcv import pytest import torch from mmaction.models import build_localizer def test_ssn_train(): train_cfg = mmcv.ConfigDict( dict( ssn=dict( assigner=dict( positive_iou_threshold=0.7, ...
tests/test_models/test_localizers/test_ssn.py
Apache-2.0
8,037
1e67455a32e0f46e951c9561a64ad558b2542533
Python
py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- """ @Time : 2/14/21 2:28 PM @Author : uyplayer @Site : uyplayer.pw @contact : uyplayer@qq.com @File : W2V.py @Software : PyCharm """ # dependency library from __future__ import print_function import argparse # sklearn from sklearn.preprocessing import LabelEn...
TL/W2V.py
MIT
3,086
6b2f8edaab74e4d54c87cb138486b9b65bd5255d
Python
py
import numpy as np import torch from collections import namedtuple from torch.nn.parallel import DistributedDataParallel as DDP # from torch.nn.parallel import DistributedDataParallelCPU as DDPC # Deprecated from rlpyt.agents.base import BaseAgent, AgentStep from rlpyt.models.qpg.mlp import QofMuMlpModel, PiMlpModel...
rlpyt/agents/qpg/sac_agent.py
MIT
8,709
52fd7d950fef7a57d28ce624f6b5b0bc1a044025
Python
py
import torch from torch_geometric.nn import ARMAConv def test_arma_conv(): in_channels, out_channels = (16, 32) num_stacks, num_layers = 8, 4 edge_index = torch.tensor([[0, 0, 0, 1, 2, 3], [1, 2, 3, 0, 0, 0]]) num_nodes = edge_index.max().item() + 1 edge_weight = torch.rand(edge_index.size(1)) ...
test/nn/conv/test_arma_conv.py
MIT
932
1e542b63be7349884fb2a2f397beea6cc88c4eae
Python
py
from typing import Dict, List, Any import torch from allennlp.common.checks import check_dimensions_match from allennlp.data import TextFieldTensors, Vocabulary from allennlp.models.model import Model from allennlp.modules import FeedForward, InputVariationalDropout from allennlp.modules.matrix_attention.legacy_matri...
allennlp/allennlp/models/esim.py
MIT
9,720
129952df3e374d2bdc73497d68f33e36f8202ef1
Python
py
#!/usr/bin/env python import logging import argparse import numpy import torch import pyro import pyro.infer import pyro.infer.mcmc import pyro.distributions as dist def get_arguments(): parser = argparse.ArgumentParser(description='Bayesian Calibration arguments') parser.add_argument('--logging-level', def...
run.py
BSD-3-Clause
2,941
3a7e05f46664d6bc32449c52a3bf1f392a493974
Python
py
''' Copyright@ Qiao-Mu(Albert) Ren. All Rights Reserved. This is the code to build a neural network. ''' import os import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader from dataloader import HairNetDataset class Net(nn.Modu...
src/model.py
MIT
8,232
d7949f8976ac55a7fdf3f3126d606abd67be2a21
Python
py
#!/usr/bin/env python """ Translator Class and builder """ from __future__ import print_function #from sklearn.linear_model import LinearRegression #from sklearn import linear_model import argparse import codecs import os import math import numpy as np import torch from itertools import count from onmt.utils.misc im...
onmt/translate/translator.py
MIT
49,453
3a7e3ca0bf8de90ae174f40f281b1560b02601e5
Python
py
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms import ipdb class Net(nn.Module): def __init__(self, img_side): super(Net, self).__init__() self.img...
test_synch/optimize/mnist.py
MIT
7,804
12a8e1ec77867f19d79c280b432a64aa1c774de3
Python
py
# -------------------------------------------------------- # Licensed under The MIT License [see LICENSE for details] # -------------------------------------------------------- import os import torch import torch.nn.functional as F from torch.optim import Adam import numpy as np from core import networks from core.uti...
core/agent.py
MIT
16,345
f9ae51b00b3abd82e4b85b8687f4847287b5d049
Python
py
import math import pdb import torch from torch import nn, einsum from einops import rearrange from .mish_activ import Mish # translated from tensorflow code # https://gist.github.com/aravindsrinivas/56359b79f0ce4449bcb04ab4b56a57a2 # positional embedding helpers # 如果是元组,则直接返回。如果不是元组,则返回元组,并且元组内部有两个元素 def pair(x): ...
bottleneck_transformer_pytorch/bottleneck_transformer_pytorch.py
MIT
18,394
3a7e5561b98bbe409e41272bd97616472a6e7f94
Python
py
# AUTOGENERATED! DO NOT EDIT! File to edit: Rapids/01-Rapids-LendingClub-Benchmark-solution-power8.ipynb (unless otherwise specified). __all__ = ['pgdf', 'time_command', 'COMPARE', 'run_times', 'filename', 'DATA_DOUBLE_FACTOR', 'loan_pdf', 'loan_rdf', 'describe_gpu', 'describe_cpu', 'ohe_cpu', 'ohe_gpu', 's...
ORNL/02_rapids.py
Apache-2.0
22,163
3a7e5b8f6b7a542e4b0c67781736597075e5336c
Python
py
from ..losses import GenericPairLoss import torch from ..utils import loss_and_miner_utils as lmu from ..distances import CosineSimilarity class IntraPairVarianceLoss(GenericPairLoss): def __init__(self, pos_eps=0.01, neg_eps=0.01, **kwargs): super().__init__(mat_based_loss=False, **kwargs) ...
src/pytorch_metric_learning/losses/intra_pair_variance_loss.py
MIT
2,100
a98582e0a5b9922e3bdc4d32589bfa1a8978ee0d
Python
py
# Copyright (c) 2021 Horizon Robotics and ALF Contributors. 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...
alf/algorithms/qrsac_algorithm.py
Apache-2.0
8,280
342c3b422f9c5db0c186a5d641ccec10591cff20
Python
py
from typing import List, Optional from pytorch_lightning import LightningModule, LightningDataModule, Callback, Trainer from pytorch_lightning.loggers import LightningLoggerBase from pytorch_lightning import seed_everything import hydra from omegaconf import DictConfig from src.utils import template_utils log = tem...
src/train.py
MIT
3,179
3a7e9b5144aeabdcc8be88594c20f187df46c5ec
Python
py
import torch import torch.nn.functional as F import argparse import cv2 import numpy as np from glob import glob import copy num_classes = 2 img_height, img_width = 224, 224 channel = 3 GPU = False torch.manual_seed(0) class ResBlock(torch.nn.Module): def __init__(self, in_f, f_1, out_f, stride=1): super...
Question_model/answers/res50_pytorch.py
MIT
8,622
3a7ea6509c51a0c471ab4da2e5a72b2a10bf5bb3
Python
py
from machin.frame.buffers import DistributedPrioritizedBuffer from test.util_run_multi import * import random import torch as t import numpy as np class TestDistributedPrioritizedBuffer(WorldTestBase): BUFFER_SIZE = 1 SAMPLE_BUFFER_SIZE = 10 ##############################################################...
test/frame/buffers/test_prioritized_buffer_d.py
MIT
9,914
425b231c0b54d87fa3d6c15ed05dc3b89aabf04c
Python
py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import torch def plot_conditional_samples_ssvae(ssvae, visdom_session): """ This is a method to do conditional sampling in visdom """ vis = visdom_session ys = {} for i in range(10): ys[i] = torch....
examples/vae/utils/vae_plots.py
Apache-2.0
3,263
3a7eaa4ce228b66eed78ea4d779639fce7596c0e
Python
py
# encoding: utf-8 """ @author: xyliao @contact: xyliao1993@qq.com """ import warnings from copy import deepcopy import numpy as np import torch import torch.nn.functional as F from mxtorch import meter from mxtorch.trainer import Trainer, ScheduledOptim from mxtorch.vision.eval_tools import eval_semantic_segmentation ...
chapter9_Computer-Vision/segmentation/main.py
MIT
7,027
28ae6dd1def1c4968f5d72df7c58412b2d5b8dc6
Python
py
""" Implementation of "Attention is All You Need" """ import torch import torch.nn as nn from c2nl.decoders.decoder import DecoderBase from c2nl.modules.multi_head_attn import MultiHeadedAttention from c2nl.modules.position_ffn import PositionwiseFeedForward from c2nl.utils.misc import sequence_mask from c2nl.modules...
c2nl/decoders/transformer.py
MIT
8,008
f9c1d7a6ec78d6d46dd2a6943ed71b8574f6632d
Python
py
#!/usr/bin/env python3 import os from pathlib import Path from torch.jit._decompositions import decomposition_table # from torchgen.code_template import CodeTemplate DECOMP_HEADER = r""" /** * @generated * This is an auto-generated file. Please do not modify it by hand. * To re-generate, please run: * cd ~/pytor...
torchgen/decompositions/gen_jit_decompositions.py
Intel
2,375
7cfbb803f9b8bf8fa07b96fdcf47b07dab9d2c6b
Python
py
"""Specific Pysyft exceptions.""" import syft as sy import torch from tblib import Traceback import traceback from six import reraise from typing import Tuple class PureTorchTensorFoundError(BaseException): """Exception raised for errors in the input. This error is used in a recursive analysis of the args pr...
syft/exceptions.py
Apache-2.0
9,865
3a7ebc16392132f9122a5e1a61d86b7812d13091
Python
py
from __future__ import print_function import os import pickle import argparse import torch import torch.nn as nn import torch.nn.functional as F import torchvision import torch.optim as optim from torchvision import datasets, transforms # from models.wideresnet import * from models import * from losses import alp_loss...
AT/train_plain_cifar10_2.py
MIT
10,994
3a7ed95b2ece314c7feecd97cf35be1364dffdf3
Python
py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import ...
onnxruntime/python/tools/transformers/benchmark_helper.py
MIT
10,218
1e1eaf4800713e325ff1b632b3cd9f258d7a44d8
Python
py
import os from torchvision.datasets import voc class Path(object): @staticmethod def db_root_dir(dataset): if dataset == 'pascal': base_dir = os.path.join(os.getcwd(), "data", "pascal") trainval_dir = os.path.join(base_dir, "VOCdevkit", "VOC2012") if not os.path.isdi...
mypath.py
MIT
694
3a7ef2b7eeff777e9fb7e6abb4bd8b9e9f9cab8b
Python
py
""" A collection of classes for calculation distance metrics on graphs. """ from abc import ABC import networkx as nx import numpy as np import torch from code_transformer.modeling.constants import BIN_PADDING from code_transformer.preprocessing.graph.alg import ( next_sibling_shortest_paths, all_pairs_short...
code_transformer/preprocessing/graph/distances.py
MIT
11,235
5e9c7294a73a4c45905b1d4a747abb3dbb6c811a
Python
py
#encoding:utf-8 # from torch.utils import data ''' 专门为multimodel而写 生成pth ''' import torch as t import numpy as np from config import opt import models import json import fire import csv import tqdm from torch.autograd import Variable def load_data(type_='char'): with open(opt.labels_path) as f: labels_ = j...
test.3.py
MIT
6,313
5f6f88acaa692dd1f6d876b13a75158c88d64762
Python
py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import Dict, List, Tuple import torch from pytext.torchscript.tensorizer.tensorizer import ScriptTensorizer def max_tokens(per_sentence_tokens: List[List[Tuple[str, int, int]]]) -> int: """receive the token...
pytext/torchscript/batchutils.py
BSD-3-Clause
6,111
1e88e87e01c103b9819d0f98a077d3674b4b5125
Python
py
import torch import numpy as np from torch import nn from model.decoder import Decoder from model.encoder import Encoder class VariationalAutoencoder(nn.Module): def __init__(self, latent_dim: int = 128, image_channels: int = 3): super().__init__() self.latent_dim = latent_dim self.encoder = Encoder(in_channel...
model/vae.py
MIT
1,033
3a7f56adf4c1f8649fce63c01a47432e1c63bee1
Python
py
import os import sys import traceback import numpy as np import argparse import threading import codecs import logging logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO, format="%(message)s") from tensorboardX import SummaryWriter # install tensorboardX (pip install tensorboardX) before import...
search.py
Apache-2.0,MIT
6,808
70727ea8d7cc9acef56e96ef064cecccb0792269
Python
py
from torch import nn from .optimizers import get_optimizer import torch from src import models from torch.nn import functional as F import itertools import tqdm from haven import haven_utils as hu import os import numpy as np from src import utils as ut import torch.optim as optim from .base_netC import resnet_met...
src/models/netC.py
Apache-2.0
3,605
3a7f967450a18537611a89d062899d9b530cd9f8
Python
py
import torch import numpy as np # 创建一个没有初始化的张量(5*3的矩阵) x = torch.empty(5, 3) print(x) # 创建一个随机初始化(符合均匀分布的初始化)的张量 x = torch.rand(5, 3) print(x) # 初始化一个全为0的张量,并指定数据类型 x = torch.zeros(5, 3, dtype=torch.long) print(x) # 通过列表创建一个张量(是一个1维的) x = torch.tensor([5.20, 10.24]) print(x) # 创建一个三维的张量 x = torch.Tensor(2, 3, 4) p...
PyTorch_01_Tensors/tensors.py
MIT
1,504
e631e0d8da7f9276a377f163df886b2771985581
Python
py
"""Few-Shot_learning Segmentation""" import numpy as np import torch import torch.nn as nn from nn_common_modules import modules as sm from data_utils import split_batch # import torch.nn.functional as F from squeeze_and_excitation import squeeze_and_excitation as se class SDnetConditioner(nn.Module): """ A ...
other_experiments/more/few_shot_segmentor_model6.py
MIT
13,297
3a7fd16cb7e0952b0609a1e7ff8119aff1d86072
Python
py
### Copyright (C) 2017 NVIDIA Corporation. All rights reserved. ### Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). import numpy as np import torch import os import sys from collections import OrderedDict from torch.autograd import Variable import util.util as ...
models/modelD_stage3.py
MIT
21,396
42954fcf08c6b923da5f55c4dee71e0de6053652
Python
py
# paper: ResT: An Efficient Transformer for Visual Recognition # code: https://github.com/wofmanaf/ResT import torch import torch.nn as nn from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from models.head import * import torch.nn.functional as F up_kwargs = {'mode': 'bilinear', 'align_corners': False...
models/resT.py
Apache-2.0
22,782
3a7fdfaf25aa7d1a0a79bd84702dc24c7e779b9f
Python
py
# Copyright (c) 2020 Huawei Technologies Co., Ltd # Copyright (c) 2019, Facebook CORPORATION. # All rights reserved. # # 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/lice...
test/test_npu/test_network_ops/test_broadcastToD.py
BSD-3-Clause
1,544
3a7ff68abd1c5954077359894ed5dc4e3820d1f1
Python
py
import abc import torch from typing import Any, Callable, List, MutableMapping, Optional, Text, Tuple class AttributionTechnique(abc.ABC): """Abstract class for an attribution technique.""" name: Text sample_size: int # Number of graphs to hold in memory per input. @abc.abstractmethod def...
MolRep/Explainer/Attribution/CAM.py
MIT
2,447
f9ba332b07d5c20b81e6bc47b52842cc77e0e6a6
Python
py
import torchtext.data as data import os import random class MyDataset(data.Dataset): def __init__(self, text_field, label_field, path='data', examples=None, **kwargs): fields = [('text', text_field), ('label', label_field)] if examples is None: path = path examples = []...
newdatasets.py
MIT
1,219
24742f5be0699d08fae3155c9fc4b69a8b715e42
Python
py
from bdb import set_trace import imp from operator import is_ import os from re import I import time import csv import numpy as np from path import Path import argparse import matplotlib.pyplot as plt from tensorboardX import SummaryWriter import cv2 import torch import torch.nn.functional as F from core...
ddptrain.py
MIT
18,279
3a802ad09ed52da27842f8bfa97f12329ac5ff0a
Python
py
# Copyright Amazon.com, Inc. or its affiliates. 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 ...
experiments/experiment_triplet.py
Apache-2.0
5,443
e9133d74be24337b48803d45e8b1400a940342e3
Python
py
import os import glob from torch.utils.data import Dataset from PIL import Image EXTENSION = 'JPEG' NUM_IMAGES_PER_CLASS = 500 CLASS_LIST_FILE = 'wnids.txt' VAL_ANNOTATION_FILE = 'val_annotations.txt' class TinyImageNet(Dataset): """Tiny ImageNet data set available from `http://cs231n.stanford.edu/ti...
API/data_engine/TinyImagenetDataset.py
MIT
4,208
4b968f5e1327ec9877d9ba351eba0d3e6303963b
Python
py
import os import sys import argparse import torch.utils.data as data FILE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(FILE_DIR, '../')) DATA_ROOT = os.path.join(FILE_DIR, '../../data') from datasets import prepare_texas, prepare_purchase import models as models from utils import mkdir...
source/nonimage/run_attacks.py
MIT
3,651
f9699201373d76d15cce26e957cac7169475a485
Python
py
from torchtext.datasets import Multi30k from torchtext.data import Field, BucketIterator, TabularDataset import spacy import numpy as np import random import math def load_data(batch_size, device): spacy_en = spacy.load('en_core_web_sm') def tokenize_en(text): return [tok.text for tok in spac...
Class6/data_reader.py
MIT
2,277
4b49bae89cdf08823fa4946519a998ecddff4c75
Python
py
import pickle import numpy as np import pytest import torch from torch import nn from garage.tf.envs import TfEnv from garage.torch.q_functions import ContinuousMLPQFunction from tests.fixtures.envs.dummy import DummyBoxEnv class TestContinuousNNQFunction: # yapf: disable @pytest.mark.parametr...
tests/garage/torch/q_functions/test_continuous_mlp_q_function.py
MIT
3,315
10956049a727cc056c2b0e4ea9f67c7dc6370ed0
Python
py
# _ _ _ _ _ _ _ _ # /\ \ /\ \ _ / /\ /\ \ /\_\/\_\ _ _\ \ /\ \ # / \ \ \ \ \ /_/ / / / \ \ / / / / //\_\/\__ \ \ \ \ # / /\ \ \ \ \ \ \___\/ / /\ \ \ /\ \/ \ \/ / / /_ \...
eve/utils/legacy.py
MIT
4,011
3a8113b4634a39e3b1e49752a554478da73ef0d4
Python
py
# coding=utf-8 # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
megatron/fused_kernels/__init__.py
MIT
5,822
459bf600a8ce44c751707f518a2eb6104fa24945
Python
py
# --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.4.2 # kernelspec: # display_name: main2 # language: python # name: main2 # --- # + import glob import matplot...
figures/feature_importance.py
Apache-2.0
9,782
ff3bc56b72e4ced0287c01c862d682d60fffd482
Python
py
""" tester模块实现了 fastNLP 所需的Tester类,能在提供数据、模型以及metric的情况下进行性能测试。 .. code-block:: import numpy as np import torch from torch import nn from fastNLP import Tester from fastNLP import DataSet from fastNLP import AccuracyMetric class Model(nn.Module): def __init__(self): su...
phenobert/utils/fastNLP/core/tester.py
MIT
9,054
e92eb4220ada7a625d6ca37b94bf7b22cedcf321
Python
py
''' This script handles the training process. ''' import argparse import math import time import dill as pickle from tqdm import tqdm import torch import torch.nn.functional as F import torch.optim as optim from torchtext.data import Field, Dataset, BucketIterator from torchtext.datasets import TranslationDataset im...
train.py
MIT
11,964
d715414960f02f543f5549248ca7169be9f80ab7
Python
py
#!/usr/bin/python # # Copyright 2018 Google LLC # # 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 ag...
scripts/train_layout6.py
Apache-2.0
46,261
5e287ec84c9791222c196944c6f6238c3845cfbe
Python
py
# This code is modified from https://github.com/jakesnell/prototypical-networks import backbone import torch import torch.nn as nn from torch.autograd import Variable import numpy as np import torch.nn.functional as F from methods.meta_template import MetaTemplate class ProtoNet(MetaTemplate): def __init__(self,...
methods/protonet.py
MIT
4,489
cc24ee4b0d0d82b815533e29f83d8fccc68026d3
Python
py
#!/usr/bin/env python import sys sys.path.append("..") from models import iresnet from collections import OrderedDict from termcolor import cprint from torch.nn import Parameter import torch.nn.functional as F import torch.backends.cudnn as cudnn import numpy as np import math import torch import torch.nn as nn import ...
models/magface_dist.py
Apache-2.0
3,154
5faac7cd7c32d1a2e2e2bb7961e12a68bf889990
Python
py
## we conduct the DA methods following https://github.com/thuml/Transfer-Learning-Library, which gives better results than the common settings. import torch import os import math import time from .base_solver import BaseSolver import torch.nn.functional as F from utils.utils import AverageMeter, to_cuda, accuracy, ac...
code/version3.0/solver/solver_entropy_minimization.py
MIT
4,670
df9f41a0592be96bcc9a19d43963316a3554334a
Python
py
""" Author: Zhiyuan Zhang Date: Dec 2021 Email: cszyzhang@gmail.com Website: https://wwww.zhiyuanzhang.net """ import argparse import os import torch import datetime import logging import sys import importlib import shutil import provider import numpy as np from pathlib import Path from tqdm import tqdm from data_util...
train_partseg.py
MIT
13,443
5f5bfa1432f6a41c800dad80b16e1d70f795cce5
Python
py
import logging import os import re import shutil import unittest from pathlib import Path import numpy as np import torch import Resources.testing as test_resources from Models.erfh5_DeconvModel import DeconvModelEfficient from Pipeline.data_gather import get_filelist_within_folder_blacklisted from Pipeline.data_load...
Tests/test_eval_train_deconv.py
MIT
11,656
3a8201a4b37ee3786d61df1e111f2ac311401ca5
Python
py
import numpy as np import torch from rlpyt.models.mlp import MlpModel from rlpyt.utils.tensor import infer_leading_dims, restore_leading_dims class MuMlpModel(torch.nn.Module): """MLP neural net for action mean (mu) output for DDPG agent.""" def __init__( self, observation_shape, hid...
rlpyt/models/qpg/mlp.py
MIT
3,451
3a8205a76b84a5b89462b388c784e00a76f6a088
Python
py
import torch.nn as nn import torch class CRNN_FC(nn.Module): def __init__(self, imgH, nc, nclass, leakyRelu=False): super(CRNN_FC, self).__init__() assert imgH % 16 == 0, 'imgH has to be a multiple of 16' ks = [3, 3, 3, 3, 3, 3, 3, 2, 2] ps = [1, 1, 1, 1, 1, 1, 1, 0, 0] s...
recognition_model/model_crnn_fc.py
MIT
3,615
3a8207b060ed84b96f3e2ca3a04096860426c608
Python
py
import string from itertools import chain from tqdm import tqdm import sys import numpy as np import random from collections import defaultdict import torch import torch.nn as nn # programming languages from asdl.transition_system import TransitionSystem from asdl.lang.csharp.csharp_grammar import CSharpASDLGrammar f...
edit_model/editor.py
MIT
117,956
3a8223b64fca5bdc00386b77676886a8b02ce109
Python
py
#!/usr/bin/env python3 import os import torch from setuptools import setup, find_packages from torch.utils.cpp_extension import BuildExtension, CUDAExtension cxx_args = ['-std=c++11'] nvcc_args = [ # '-gencode', 'arch=compute_50,code=sm_50', # '-gencode', 'arch=compute_52,code=sm_52', # '-gencode', 'arch...
my_package/DepthFlowProjection/setup.py
MIT
831
dfe392b6dcacc67fbc1297c505498a2f9ce4fb8d
Python
py
from scipy.optimize import linear_sum_assignment as hungarian from sklearn.metrics.cluster import ( normalized_mutual_info_score, adjusted_rand_score, adjusted_mutual_info_score, ) import torch class Confusion(object): """ column of confusion matrix: predicted index row of confusion matrix: ta...
cluster_evaluation.py
MIT
4,858
3a826f536fccfb099b2697c6ca714b75eb61a3aa
Python
py
import numpy as np import torch class EarlyStopping: """Terminates training if validation loss doesn't improve after a given patience. As inspired from https://github.com/Bjarten/early-stopping-pytorch""" def __init__(self, patience=5, verbose=False, delta=0): """ Args: patienc...
utils/early_stopping.py
MIT
1,952
5e2cc2c738672277b97146ab6cf4dbbc2386acd9
Python
py
from os.path import join from torchvision.transforms import Compose, ToTensor from dataset import DatasetFromFolderEval, DatasetFromFolder def transform(): return Compose([ ToTensor(), ]) def get_training_set(data_dir, hr, upscale_factor, patch_size, data_augmentation): hr_dir = join(data_dir, hr)...
data.py
MIT
609
3a8271372f1e466b2c54743a4830c8a7c9a6bd73
Python
py
from collections import OrderedDict from typing import Dict, Optional import copy from torch import nn class IntermediateLayerGetter(nn.ModuleDict): """ Module wrapper that returns intermediate layers from a model It has a strong assumption that the modules have been registered into the model in the ...
torchvision/models/_utils.py
BSD-3-Clause
5,898
3a82831c5d13cc6cb0bbb31d97d3fdd9c34b3b74
Python
py
import os import requests import torch from flask import Flask, jsonify, request from io import BytesIO from PIL import Image from shutil import copyfileobj from tempfile import NamedTemporaryFile from torchvision import transforms from urllib.request import urlopen from catfish_model import CatfishModel, CatfishClass...
chapter8/catfish_docker_cloud/catfish_server.py
MIT
1,648
d7147468d6becd9f24907223a76e71ff84d7d8ae
Python
py
from argparse import ArgumentParser import pytorch_lightning as pl import torch from pytorch_lightning import LightningModule from torch.utils.data import DataLoader from transformers import ( BartForConditionalGeneration, BartTokenizer, get_linear_schedule_with_warmup, ) import jsonlines from src.data.seq...
src/models/bart_seq2seq_kilt.py
MIT
7,320
0392762948f081581d76fd59a3f542253b0aa4cf
Python
py
import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import math from args import args as parser_args DenseConv = nn.Conv2d class GetSubnet(autograd.Function): @staticmethod def forward(ctx, scores, k): # Get the subnetwork by sorting the scores and ...
utils/conv_type.py
Apache-2.0
4,164
3a829ca87d91bafa00ed69c53ac068dc8563c07e
Python
py
import os import math import argparse import random import logging import torch import torch.distributed as dist import torch.multiprocessing as mp from data.data_sampler import DistIterSampler import options.options as option from utils import util from data import create_dataloader, create_dataset from models impor...
codes/train.py
Apache-2.0
7,879
45bca701081e23e766da893227b009f9aaa5f0aa
Python
py
import torch from mmcv.runner import force_fp32 from mmdet.core import images_to_levels from ..builder import HEADS from ..losses import carl_loss, isr_p from .retina_head import RetinaHead @HEADS.register_module() class PISARetinaHead(RetinaHead): """PISA Retinanet Head. The head owns the same structure wi...
mmdet/models/dense_heads/pisa_retinanet_head.py
Apache-2.0
6,220
fde718904591639673323da27f5b3a46106b6a79
Python
py
import gym import torch import tensorboardX from ddpg import DDPG import argparse import os def main(args): env = gym.make(args['env_name']) device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') action_dim = env.action_space.shape[0] max_action = env.action_space.high[0] state_...
evaluate.py
Apache-2.0
2,276
3a82b485c7dc63068f3f7de1b358260b3b28d018
Python
py
# -*- coding: utf-8 -*- import math import torch from torch import nn, Tensor # pylint: disable=arguments-differ class MultiHeadedAttention(nn.Module): """ Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py ...
joeynmt/transformer_layers.py
Apache-2.0
9,136
f96c93f824aaacf928e8909805c6f8f7bd553f4c
Python
py
#!/usr/bin/env python3 import logging import math import time from typing import Optional import numpy as np import torch from reagent.ope.estimators.types import PredictResults, Trainer, TrainingData from sklearn.linear_model import Lasso, LogisticRegression, SGDClassifier from sklearn.metrics import accuracy_score,...
reagent/ope/trainers/linear_trainers.py
BSD-3-Clause
12,700
3a82f5c1fa6251fb75366c739dfcc97e9803b86c
Python
py