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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ CS224N 2018-19: Homework 4 model_embeddings.py: Embeddings for the NMT model Pencheng Yin <pcyin@cs.cmu.edu> Sahil Chopra <schopra8@stanford.edu> Anand Dhoot <anandd@stanford.edu> """ import torch.nn as nn import logging_utils import logging LOGLEVEL = logging.DEBU...
courses/cs224n/hw/a4/model_embeddings.py
MIT
2,087
8052cd0b8f5fac5cd9f510ef3b8d3cec047f3a94
Python
py
import os import math import time import pprint from tqdm import tqdm import dill as pickle import numpy as np from numpy import random import torch import torch.nn as nn import torch.nn.functional as F from utils import Beam, GNMTGlobalScorer, constant, tile, top_k_top_p_filtering from models import RNNEncoder, RNN...
models/seq2seq.py
MIT
8,180
d7b9891fd5e5ff075600b1f0a29b21cc63e6cb45
Python
py
from __future__ import print_function import torch.utils.data as data from PIL import Image import os import os.path import errno import numpy as np import torch import codecs class MovingMNIST(data.Dataset): """`MovingMNIST <http://www.cs.toronto.edu/~nitish/unsupervised_video/>`_ Dataset. Args: roo...
scripts/moving_mnist.py
Apache-2.0
6,064
29d0839fc6efe723a5aa2be08b26bf136e8c2c31
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
50,595
29d0b58226a64ba0f0c0e38a9d35a435964ac3a9
Python
py
# -*- coding: utf-8 -*- # @Time : 2019/8/23 21:58 # @Author : zhoujun import time import torch import torchvision.utils as vutils from tqdm import tqdm from base import BaseTrainer from utils import WarmupPolyLR, runningScore, cal_text_score class Trainer(BaseTrainer): def __init__(self, config, model, crit...
trainer/trainer.py
Apache-2.0
10,129
29d0c6f250e078e9680104a36619da59f559cd8f
Python
py
from typing import List from typing import Optional from typing import Union import pandas as pd from etna import SETTINGS from etna.datasets.tsdataset import TSDataset from etna.loggers import tslogger from etna.models.base import Model from etna.models.base import log_decorator from etna.transforms import PytorchFo...
etna/models/nn/tft.py
Apache-2.0
5,415
52b01513da59536c1b9c981c54b5b6054d7de561
Python
py
from abc import ABC, abstractmethod import numpy as np import torch from typing_extensions import Protocol from l5kit.data import get_agents_slice_from_frames from l5kit.evaluation import error_functions from l5kit.evaluation import metrics as l5metrics from l5kit.rasterization import EGO_EXTENT_LENGTH, EGO_EXTENT_WI...
l5kit/l5kit/cle/metrics.py
Apache-2.0
10,397
29d0fd468ca62fc25dcd886acd2dff12aba3045e
Python
py
# 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 math import torch from fa...
fairseq/sequence_generator.py
BSD-3-Clause
26,593
7c11589894edeba4c6957ef4e7c80b283f8d2c21
Python
py
import random import os import time import hashlib import torch import pandas as pd import numpy as np import pathlib from torch_geometric.utils import remove_self_loops from sklearn.metrics import roc_auc_score, accuracy_score, precision_score, recall_score from sklearn.metrics import mean_squared_error, mean_absolute...
src_2gi_ddi/utils.py
MIT
40,124
cc042c476e87a4120c42fa54376d4dff4154510e
Python
py
from collections import defaultdict import logging import os import sys import time from typing import Type, Union import h5py import numpy as np from sklearn.metrics import f1_score import torch from torch.utils.data import DataLoader from omegaconf import DictConfig, OmegaConf, ListConfig from torch import nn from t...
deepethogram/feature_extractor/inference.py
FSFAP
25,316
29d121df2f7a15607ee47ad426a10c15d5eb44ca
Python
py
import warnings import torch from torch import Tensor from torch.nn.functional import grid_sample, conv2d, interpolate, pad as torch_pad from torch.jit.annotations import BroadcastingList2 from typing import Optional, Tuple, List def _is_tensor_a_torch_image(x: Tensor) -> bool: return x.ndim >= 2 def _assert_i...
torchvision/transforms/functional_tensor.py
BSD-3-Clause
35,317
a95e29fda0dae749efe689b23d6116e35c079bbd
Python
py
import torch def assert_output_has_nan(x: torch.Tensor) -> None: assert torch.isnan(x).any() == False, "Output contains NaN." def assert_output_shape_wrong(x: torch.Tensor, expected_shape: tuple) -> None: assert ( x.shape == expected_shape ), f"Output's shape: {tuple(x.shape)} != Expected shape: {...
tests/utils.py
Apache-2.0
337
f960e17e7a4804bd248a9e4866f9fe09aabb64d9
Python
py
#!/usr/bin/env python3 r""" Sampler modules to be used with MC-evaluated acquisition functions. """ import random from abc import ABC, abstractmethod from typing import Optional import torch from torch import Tensor from torch.nn import Module from torch.quasirandom import SobolEngine from ..exceptions import Unsup...
botorch/acquisition/sampler.py
MIT
9,031
29d13649d380a662958b5027aa3eb910ceba2f46
Python
py
import math import torch import torch.nn as nn from torch.optim.optimizer import Optimizer from .types import Betas2, OptFloat, OptLossClosure, Params __all__ = ('Yogi',) class Yogi(Optimizer): r"""Implements Yogi Optimizer Algorithm. It has been proposed in `Adaptive methods for Nonconvex Optimization`__....
torch_optimizer/yogi.py
Apache-2.0
5,363
29d14aef7010ae5516ad2fa86f742b3e2b5869df
Python
py
import json import logging import sys import pandas as pd import numpy as np import torch from task_config import SuperGLUE_LABEL_MAPPING from snorkel.mtl.data import MultitaskDataset sys.path.append("..") # Adds higher directory to python modules path. logger = logging.getLogger(__name__) TASK_NAME = "SWAG" d...
superglue_parsers/swag.py
Apache-2.0
4,132
29d15b423dae1b9b0a06da7395efc6f6e9935574
Python
py
import math import numpy as np import torch from numba import jit from scipy import sparse from pagnn.types import SparseMat @jit(nopython=True) def conv1d_shape(in_channels, kernel_size, stride=1, padding=0, dilation=1): return math.floor((in_channels + 2 * padding - dilation * (kernel_size - 1) - 1) / stride ...
src/pagnn/utils/array_ops.py
MIT
3,606
b2b4bc2ee12a24e2c69934872bb74985ba2f8a2a
Python
py
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import copy import types import logging import torch from nni.common.graph_utils import build_module_graph from nni.compression.pytorch.quantization.literal import QuantType, BN_FOLD_OP, BN_FOLD_TAG from nni.compression.pytorch.quantization.obser...
nni/compression/pytorch/compressor.py
MIT
40,636
7049504d721bad8a466de16979f53549fcba3028
Python
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # pylint: disable-msg=import-error """ data_util.py is writen for creating iterator and save field """ import logging import hazm import torch import numpy as np import pandas as pd import pickle as pkl from torchtext import data from torchtext.vocab import Vectors from ...
src/emoji_prediction/utils/data_util.py
MIT
13,448
7cb8cf86734ad59253c64dbcfc657dec5778bd2d
Python
py
import logging from typing import Type, Tuple, Dict, List import itertools from collections import OrderedDict import torch import dace from dace import data as dt from daceml.autodiff.backward_pass_generator import BackwardPassGenerator from daceml.autodiff.base_abc import AutoDiffException, BackwardResult from dac...
daceml/autodiff/pytorch.py
BSD-3-Clause
5,718
29d19be2319a47e009a5737f9a5530030ff375ef
Python
py
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from model.utils.config import cfg from model.deconv.deconv import _Deconv import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import ...
lib/model/deconv/resnet.py
MIT
20,109
fd6910cc71d7dbbf3054b36ccb43f3dd3ad84dc6
Python
py
# Copyright (c) 2022, 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/nlp/modules/common/megatron/language_model.py
Apache-2.0
24,152
29d1ac3adf36379f451279751cd3dbafaf6b9170
Python
py
# Copyright 2020 Toyota Research Institute. All rights reserved. import cv2 import numpy as np import random import torchvision.transforms as transforms from PIL import Image import os from packnet_sfm.utils.misc import filter_dict ####################################################################################...
packnet_sfm/datasets/augmentations_woodscape_fisheye.py
MIT
7,596
29d1b3475a7706f7f63e68db785dc9f7a93fe99b
Python
py
import copy import random from functools import partial import numpy as np from mmdet.cv_core.parallel import collate from mmdet.cv_core.utils import Registry, build_from_cfg from torch.utils.data import DataLoader from .samplers import GroupSampler # only linux # 用于查询或修改当前系统资源限制设置,可以通过代码控制进程内存,不知道纠结有多少影响? TODO imp...
mmdet/datasets/builder.py
MIT
4,115
4265459142e02f66beaeef6e720e2a241513a0ed
Python
py
"""PyTorch compatible samplers. These determine the order of iteration through a dataset. Authors: * Aku Rouhe 2020 * Samuele Cornell 2020 * Ralf Leibold 2020 """ import torch import logging from operator import itemgetter from torch.utils.data import ( RandomSampler, WeightedRandomSampler, Distribu...
speechbrain/dataio/sampler.py
Apache-2.0
22,878
345c01e9dcac525d1b3d8db26818885f6b23da93
Python
py
import torch import torch.nn as nn from torch.utils.data import DataLoader from torchvision import transforms as T import torch.nn.functional as F from torchvision import models from torchvision.datasets import ImageFolder import pytorch_lightning as pl import torchmetrics from tqdm import tqdm import matplotlib.pyplot...
ComputerVision/TransferLearning/code/train.py
MIT
7,817
29d1e09bcfd8c82d5ec6f7e5032130dca7144749
Python
py
import abc import torch import torchaudio import numpy as np from omegaconf.listconfig import ListConfig from omegaconf.dictconfig import DictConfig import torchvision.transforms as transforms from torchvision.transforms import Compose, ToTensor, Normalize from torchaudio.transforms import FrequencyMasking, TimeMaskin...
cvap/data/audio/transform.py
MIT
9,230
f9763e77d1e73ff7c094ce284c22f2c096072fc2
Python
py
# Cheney - Mon Sept 18 2017 # PyTorch implementation for Lp-WGAN # Reference: WGAN from __future__ import print_function import argparse import random import os import gc import resource import numpy as np import torch import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import t...
negative.py
BSD-3-Clause
14,862
5ec61626761dca118087b4129504aa9a7e6e66e5
Python
py
from __future__ import print_function import numpy as np import os import sys import cv2 import random import pickle import torch import torch.backends.cudnn as cudnn from torch.autograd import Variable import torch.optim as optim from torch.optim import lr_scheduler import torch.utils.data as data import torch.nn.ini...
lib/ssds_train.py
MIT
26,254
7c2540edabda758fbc14518b444fbf1ba17ef849
Python
py
import numpy as np from numba import jit from collections import deque import itertools import os import os.path as osp import time import torch import cv2 import torch.nn.functional as F from models.model import create_model, load_model from models.decode import mot_decode from tracking_utils.utils import * from trac...
src/lib/tracker/multitracker.py
MIT
17,994
dfb10db68d9511398fc0443648afe2cb75caf1a9
Python
py
import os from collections import defaultdict import numpy as np import torch import tqdm from .agent import SACAgent from .config import get_args def test(args, agent, env): score_list = [] for _ in range(args.test_times): obs = env.reset() score = 0 for __ in range(args.max_episode...
drl/sac/main.py
MIT
4,132
5f831f19c3da8a0c10e19ef1fa1554ecf2a10b66
Python
py
from __future__ import print_function from PIL import Image import os import os.path import numpy as np import sys import pickle import torch import torch.utils.data as data from itertools import permutations class VisionDataset(data.Dataset): _repr_indent = 4 def __init__(self, root, transforms=None, trans...
dataset/cifar.py
MIT
9,888
b27ae40be0df32ab7d9ef1a9e06b83a9ca31b99c
Python
py
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import torch from torch import nn from torch.nn import functional as F from models.unet.unet_model import UnetModel class ConvBlock(nn.Modu...
models/uncertainty/unet_vae/vae_2.py
MIT
4,539
cc03b4f8d2fb16e67da129603ca2d034d19a7fcb
Python
py
from collections import namedtuple import numpy as np import torch # a snapshot of state to be stored in replay memory Transition = namedtuple('Transition', ('observation_list', 'quest_list', 'possible_words', 'word_indices', 'reward', 'is_final')) class PrioritizedReplayMemory(object): def __init__(self, capa...
command_generation_memory.py
MIT
5,513
e65c98892d9101b9ed885e6c69716950f9394e30
Python
py
#!/usr/bin/env python3 # use pytorch for dataloader # https://github.com/pytorch/examples/blob/master/imagenet/main.py import argparse import os import random import shutil import time import warnings import numpy as np import hashlib import torch import torch.nn as nn import torch.utils.data import torchvision.trans...
python/cvi_toolkit/eval_on_board/eval_imagenet_pytorch.py
Apache-2.0
9,276
3afbfc757af33d83d7edb49a03059d6f61b3a266
Python
py
# WarpCTC PyTorch bindings (c) 2018 by Thomas Viehmann <tv@lernapparat.de> # All rights reserved. Licensed under the # Apache License, Version 2.0, January 2004 # see LICENSE in root directory from setuptools import setup, find_packages, Command, distutils from torch.utils.cpp_extension import BuildExtension, CppExte...
pytorch_binding/setup.py
Apache-2.0
2,630
12d3d8e67303355241623ea4f2976767ffc593ad
Python
py
'''VGG11/13/16/19 in Pytorch.''' import torch import torch.nn as nn cfg = { 'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512,...
models/vgg.py
MIT
1,469
10780c8dcfaa5dfc05518ae4c9e17ffbfd79333c
Python
py
import sys sys.path.append('../') import torch import torch.nn as nn import math, random, sys import argparse from fast_jtnn import * import rdkit from tqdm import tqdm def load_model(vocab, model_path, hidden_size=450, latent_size=56, depthT=20, depthG=3): vocab = [x.strip("\r\n ") for x in open(vocab)] voc...
fast_molvae/sample.py
MIT
1,880
29d29d03e546e5d8fe1a0349404663dcdda4be9d
Python
py
# -*- coding: utf-8 -*- import os import numpy as np import logging import pickle import torch import torch.nn as nn from torch import optim from torch import multiprocessing as mp from rlmodule import MultiDiscretePolicy, Value, Memory, UserAction2, VanillaTransition # from estimator import RewardEstimator from uti...
vanilla_ppo.py
MIT
31,898
29d29fb624eae1b8c155e6a18734fd91542a347c
Python
py
import torch import torch.nn as nn from torch.nn import init import math import numpy as np from .correlation_package.modules.correlation import Correlation from .submodules import * 'Parameter count , 39,175,298 ' class FlowNetC(nn.Module): def __init__(self,args, batchNorm=True, div_flow = 20): ...
networks/FlowNetC.py
Apache-2.0
4,893
29d2a032983b9960fdf273f9bff0ccebc85ae09c
Python
py
import math import torch import torch.nn as nn from src.modules.base_generator import GeneratorAbstract class MBConv(nn.Module): """MBConvBlock used in Efficientnet. Reference: https://github.com/narumiruna/efficientnet-pytorch/blob/master/efficientnet/models/efficientnet.py Note: Drop co...
src/modules/mbconv.py
MIT
5,255
4ba3f823cd11e449ff4b66492b7ea5572840ed06
Python
py
import torch.nn as nn from mmcv.cnn import build_conv_layer, build_norm_layer from ..builder import BACKBONES from .resnet import ResNet,ResNetSimple @BACKBONES.register_module() class ResNet_Tiny(ResNetSimple): """ResNet backbone for CIFAR. Compared to standard ResNet, it uses `kernel_size=3` and `stride=1`...
mmpose/models/backbones/resnet_tiny.py
Apache-2.0
3,746
03c67fe4ab8a2e2326d2eb9cab6f0e6fc526463f
Python
py
"""Computer vision example on Transfer Learning. This computer vision example illustrates how one could fine-tune a pre-trained network (by default, a ResNet50 is used) using pytorch-lightning. For the sake of this example, the 'cats and dogs dataset' (~60MB, see `DATA_URL` below) and the proposed network (denoted by ...
pl_examples/domain_templates/computer_vision_fine_tuning.py
Apache-2.0
16,964
703f1c9b024194a10432b8cbf3333c526856f491
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...
torchmetrics/regression/mape.py
Apache-2.0
3,583
d71cc8f6719deadaa3efb5a0931aac5c62868be0
Python
py
import torch from random import randrange from math import floor from torch.nn.utils.rnn import pack_padded_sequence, PackedSequence from .config import PAD def _limit_lengths(seqs, max_length=None, max_tokens=None): max_length = max_length or float('inf') lengths = [min(s.nelement(), max_length) for s in seq...
seq2seq/tools/__init__.py
MIT
2,351
29d2f3075fedadfd803750b971278af1518c0e94
Python
py
import json import torch from diora.logging.configuration import get_logger class ParsePredictor(object): def __init__(self, net, word2idx): super(ParsePredictor, self).__init__() self.net = net self.word2idx = word2idx self.idx2word = {v: k for k, v in word2idx.items()} ...
pytorch/diora/analysis/cky.py
Apache-2.0
3,464
29d30662c53dab67b6a92643f2a07f47ddb88106
Python
py
#!/usr/bin/env python3 from typing import Iterable, Union import torch class NGD(torch.optim.Optimizer): r"""Implements a natural gradient descent step. It **can only** be used in conjunction with a :obj:`~gpytorch.variational._NaturalVariationalDistribution`. .. seealso:: - :obj:`gpytorch.vari...
gpytorch/optim/ngd.py
MIT
1,392
03d1bf20735527abfc3f32bd2fbd23f227a0f78a
Python
py
import torch.nn as nn import cv2 import torch from copy import deepcopy import numpy as np from torch.autograd import Variable from torch.autograd import Function as F from parameters import Parameters import math p = Parameters() ############################################################### ## ## visualize ## ###...
util.py
MIT
10,996
29d3314f24829e89a982f37176b128ebd28877db
Python
py
import numpy as np import pytest import torch from PIL import Image import clip @pytest.mark.parametrize('model_name', clip.available_models()) def test_consistency(model_name): device = "cpu" jit_model, transform = clip.load(model_name, device=device) py_model, _ = clip.load(model_name, device=device, j...
tests/test_consistency.py
MIT
802
29d343d01391bdaf7772dfb2be29e0ef653ec313
Python
py
import pytest import torch from syft.frameworks.torch.pointers import PointerTensor from syft.exceptions import InvalidTensorForRemoteGet def test___str__(workers): bob = workers["bob"] tensor = torch.Tensor([1, 2, 3, 4]) assert isinstance(tensor.__str__(), str) tensor_ptr = tensor.send(bob) as...
test/torch/tensors/test_native.py
Apache-2.0
4,022
7c71ca2cbedf7a16cb8cf62c327f27e8823857bb
Python
py
from typing import Tuple import torch from torch import Tensor from .geometry import get_theta, unit def project_ideal(focal_length: float, view_points: Tensor, model: str) \ -> Tensor: ''' Ideal projection ''' n = unit(view_points) theta = get_theta(n, normed=True) if model == 'equi...
omnicalib/simulation.py
MIT
2,643
e661b14becdd3bd802d58d0f7c8fd84cd9ee25ce
Python
py
from pathlib import Path from typing import Union from pytorch_lightning.plugins.environments import ClusterEnvironment from pytorch_lightning.plugins.io.checkpoint_plugin import CheckpointIO from pytorch_lightning.plugins.io.torch_plugin import TorchCheckpointIO from pytorch_lightning.plugins.io.xla_plugin import XLA...
pytorch_lightning/plugins/__init__.py
Apache-2.0
3,566
29d3926b6d294b6968145fd4dd194c16532f2f5b
Python
py
import gradio import numpy as np import torch from PIL import Image from fba.anonymizer import build_anonymizer from fba import utils from fba.config import Config import gradio.inputs def anonymize(img: Image.Image, truncation_value: float): img = img.convert("RGB") img = np.array(img) img = np.rollaxis(im...
app.py
MIT
1,219
29d3ae95f692773a0f832986b963d6bbf4e5a686
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import argparse import numpy as np import os from os import path import itertools from scipy.stats import entropy import collection...
src/zoo/dialog/test_noise.py
MIT
12,355
5f1143b097426197ed44cdba6add04d23b55ee0a
Python
py
from math import sqrt import numpy as np import torch as t import torch.nn as nn from gensim.models.keyedvectors import KeyedVectors from torch.autograd import Variable class Embeddings(nn.Module): def __init__(self, path, vocab_size, max_len, h_size): super(Embeddings, self).__init__() self.voc...
nn/embedding/embedding.py
MIT
2,362
29d3ea957df9c0aae268444adcd8460d4784fb39
Python
py
import torch import torch.nn as nn class MLP(nn.Module): def __init__(self, in_sz, h_szs, out_sz, hiddens_nonlinearity, final_nonlinearity): # in_sz (int, input sz) # h_szs (list of hidden layer szs) # out_sz (int, output sz) # hiddens_nonlinearity ('relu', 'tanh') # final_nonlinea...
src/test/py/ltprg/game/synthetic_nom_ref/network_components.py
MIT
1,959
03d07e0479ec9a2f385b354e6eaa5757efb5d761
Python
py
import torch_geometric from models import CompareFeaSt, CompareSAGE from transforms import InletGeodesics, RemoveFlowExtensions, HeatSamplingCluster, FeatureDescriptors from .template import Experiment def fit(device): # Neural network model = CompareFeaSt() # Training data dataset = 'single_arteries...
experiments/compare.py
MIT
891
29d42dc89b7d89530d1a8365375730d6ce12e6dd
Python
py
import torch import torch.nn as nn import numpy as np from pruners.Pruner import Pruner from worldmodel.VAE import Flatten # Prunes p% of remaining weights # prunes only weights # sparsity in layer depends on layer size # supposed to use with linear layers only!!! class ERPruner(Pruner): def __init__(self, net, ...
rl/pruners/ERPruner.py
MIT
1,913
10f82e2a1338fddcd458b353bc9ca444132ab662
Python
py
''' Copyright 2019 The Microsoft DeepSpeed Team ''' import os import torch import warnings import hashlib import torch.distributed as dist from torch.nn.modules import Module from torch.distributed.distributed_c10d import _get_global_rank from tensorboardX import SummaryWriter from deepspeed.runtime.utils import see...
deepspeed/runtime/engine.py
MIT
71,958
f965eb688d16db78153d63f1402865bbad9ce4f1
Python
py
import os import pickle import numpy as np import torch from osim.env import ProstheticsEnv from osim.http.client import Client from pros_ai import get_policy_observation from robo_rl.obsvail import get_obsvail_parser, get_logfile_name from robo_rl.sac import SAC, SigmoidSquasher from tensorboardX import SummaryWriter...
obsvail/pros_play.py
MIT
4,474
29d4d9974783bd693508ff8e753ff2e41c8e601e
Python
py
import math from typing import Any, Dict, List, Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F from fairseq import utils from fairseq.models import ( FairseqEncoder, FairseqEncoderDecoderModel, FairseqIncrementalDecoder, register_model, register_model_architectu...
fairseq/models/position_transformer.py
MIT
46,990
5e6a6c3321fc0ecb2b28ff487f365c6b5f8d0983
Python
py
import torch import torch.nn as nn import numpy as np # import use_package # import qiqi_package as qiqi import torch.utils.data as Data import sys import torchvision import torchvision.transforms as transforms import time import math # 起始位置 x = torch.empty(5, 3) print(x) x = torch.rand(5, 3) print(x) x = torch.zer...
Chinese_5/Day_1/01.py
Apache-2.0
1,639
12ffa3dc8d4f0042efd8303592bc20c5865c1b78
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import pathlib import pickle import warnings from typing import List, Optional, Sequence, Tuple, Union import torch from ...
mbrl/models/gaussian_mlp.py
MIT
18,616
29d4f69e26e3d8bba2c88220799aede1b3fd391e
Python
py
import argparse import json import math import logging from urllib.request import urlopen import sys import os import subprocess import json import yaml import glob from braceexpand import braceexpand from types import SimpleNamespace import os.path from omegaconf import OmegaConf import hashlib import time import ...
pixray.py
MIT
86,560
4b2f85675a92ab9b3557069840f11e4bb172a85c
Python
py
import torch from torch.optim.lr_scheduler import CosineAnnealingLR, LambdaLR import numpy as np import matplotlib.pyplot as plt import pdb from models.worker.macro_cnn_worker import MacroCNN class Trainer : def __init__(self, args, data, controller, worker): self.args = args self.trainData = data.train self....
trainer/trainer.py
MIT
14,399
422366dce9f2d623ff876d1a67b5cc8e1a1e0dc3
Python
py
#!/usr/bin/python3 #coding=utf-8 import os import cv2 import json import torch import numpy as np import transform from torch.utils.data import Dataset class Config(object): def __init__(self, **kwargs): self.kwargs = kwargs self.mean = np.array([[[115.75, 120.83, 93.49]]]) s...
fine/dataset.py
MIT
5,556
6b073aa9899108871c661e8a13a095e19ecf43b5
Python
py
from argparse import ArgumentParser, Namespace from pathlib import Path try: from spatial_correlation_sampler import SpatialCorrelationSampler except ModuleNotFoundError: from ptlflow.utils.correlation import IterSpatialCorrelationSampler as SpatialCorrelationSampler import torch import torch.nn as nn from .p...
ptlflow/models/irr/pwcnet_irr.py
Apache-2.0
4,862
5f2c17520efb5036448178d4b90f153917d09bf3
Python
py
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from .utils import * #################################################################### class seqOnly(nn.Module): def __init__(self, args): super(seqOnly, self).__init__() self.input_size = args.in...
structureimpute/models/seqOnly.py
MIT
3,105
ff27e819da4539fb43ee1268786d61b89a85f887
Python
py
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # from __future__ import absolute_import, division, print_function import numpy as np import torch from torch import nn from torch.cuda.amp import GradScaler, autocast from torchreid import metrics from torchreid.engine.engine import E...
torchreid/engine/image/multihead.py
MIT
13,107
29d572202f6bb8335888ba2b18a297f239e85c75
Python
py
import argparse import logging from tqdm import trange import torch import torch.nn.functional as F import numpy as np from torch import nn from torch.autograd import Variable from transformers import GPT2Config from transformers import GPT2LMHeadModel, GPT2Tokenizer, BertTokenizer from DataLoader import * from Model i...
GPT2-coarse-to-fine.py
MIT
17,255
29d57d6df1669fdb7bb7318e9c71ff113ff3c6bc
Python
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.data as utils import torchvision.transforms as transforms from pygments.formatters import img from scipy import io import numpy as np import mathematical_operations as mo from datetime im...
venv/drafts/old_models/4/model.py
MIT
10,479
29d580455c0fa63e6da6276e9137afd6126cc4c4
Python
py
import re import glob import math from tqdm import tqdm import numpy as np import torch import random import requests, zipfile, io import os from .pytorch_pretrained_bert.tokenization import BertTokenizer from .pytorch_pretrained_bert.modeling import BertForSeq2SeqDecoder from .biunilm import seq2seq_loader import t...
text2text/abstractor.py
MIT
7,341
29d58828ee4285d6934ac46e632fdbdac09a0eca
Python
py
# # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # import copy from typing import Optional, Any, List import torch import numpy as np import av from torch import Tensor import random import argparse from PIL import Image from torchvision.transforms import functional...
data/video_reader/base_video_reader.py
AML
8,266
29d58c053e27e29d22ade318582b16d97b3537ee
Python
py
# coding=utf-8 # Copyright 2021 The Fairseq Authors, Microsoft Research, and The HuggingFace Inc. team. 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...
src/transformers/models/wavlm/modeling_wavlm.py
Apache-2.0
79,902
7c99a5d7808ccd4a2ca5ad9f6e04647f77900c3e
Python
py
import torch import numpy as np from model.mgcvae import ASubmodel, BQSubmodel from model.dataset import get_timesteps_data from model.model_utils import mutual_inf_mc, sigmoid_anneal from model.components import GMM2D import model.dynamics as dynamic_module import torch.distributions as td import model.anneal_scheduli...
mats/model/mats.py
MIT
46,410
e60d6dd8d460a3d0e6c6c4e04c97178151da3bfa
Python
py
from collections import OrderedDict import torch 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 same order as they are used. ...
torchvision/models/_utils.py
BSD-3-Clause
2,476
4b337a53f7e4ee69c796d51124cfb67107ee6442
Python
py
#!/usr/bin/env python3 import gym import ptan import time import random import numpy as np import argparse from tensorboardX import SummaryWriter import torch import torch.nn as nn import torch.nn.utils as nn_utils import torch.nn.functional as F import torch.optim as optim from lib import common import os GAMMA = ...
z_externals/handson_second_edition/Chapter12/04_pong_r2.py
MIT
8,388
fdc96576a24429eeb592dda74fb88fc3bbd4d597
Python
py
# Copyright 2019 Lorna Authors. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
nets/densenet_test.py
Apache-2.0
8,708
e60ec184f92b25f653c70f66324a4dc5f7a8762f
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...
network_architecture/generic_modular_residual_UNet.py
Apache-2.0
24,357
5f6c03f318a588c453876307874fce92a339eab4
Python
py
import torch import torch.nn as nn import torch.nn.functional as F class ActionEncoder(nn.Module): def __init__(self, horizon, state_embed_size, road_state_num, road_embed_size, skill_embed_size=9, state_num=4, action_num=2, hidden_size=400): super(ActionEncoder, self).__init__() ...
Pre-skills/action_encoder.py
MIT
2,482
29d61805b933a24c322ecb6b07f162fc49aa43dc
Python
py
# Copyright 2020 The HuggingFace Team. 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 applicabl...
src/transformers/trainer_seq2seq.py
Apache-2.0
10,369
5e533a62a65947ee8a0830a0f1526518111e1e03
Python
py
import math import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo from modeling.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d def fixed_padding(inputs, kernel_size, dilation): kernel_size_effective = kernel_size + (kernel_size - 1) * (dilation - 1) pa...
modeling/backbone/xception.py
MIT
10,425
29d642d9917d843b0b6453ff76b09b68ae89d16a
Python
py
import random import warnings from itertools import islice from typing import List, Iterator, Optional import humanize from tqdm import trange from torch.utils.data import Dataset, DataLoader from .subject import Subject from .sampler import PatchSampler from .dataset import SubjectsDataset class Queue(Dataset): ...
torchio/data/queue.py
Apache-2.0
12,399
5f9126e9ef892714fea710452156c980b5663928
Python
py
# global import torch from typing import Union, Tuple, List # local import ivy def can_cast(from_: Union[torch.dtype, torch.Tensor], to: torch.dtype) -> bool: if isinstance(from_, torch.Tensor): from_ = from_.dtype from_str = str(from_) to_str = str(to) if ivy.dtype_bits(to) < ivy.dtype_bits(...
ivy/functional/backends/torch/data_type.py
Apache-2.0
4,309
29d65839b23f56babae1a7e76e29a0b52ea60922
Python
py
import json from os.path import abspath, dirname, exists, join import argparse import logging from tqdm import trange import tqdm import torch import torch.nn.functional as F import numpy as np import socket import os, sys import re import logging from functools import partial from demo_utils import download_model_fold...
interact.py
MIT
8,494
29d65c9afc18a48776cd149cfa81e957f41e7b17
Python
py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # 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 req...
transformers/tests/modeling_xlnet_test.py
MIT
14,912
cc1ddfd8c1f59afd84e326ec3cc4b3c440e4614f
Python
py
# coding: utf-8 import argparse import time import math import os, sys import itertools import numpy as np import torch import torch.nn as nn import torch.optim as optim from DEQModel.data_utils import get_lm_corpus from DEQModel.models.trellisnets.deq_trellisnet import DEQTrellisNetLM from DEQModel.modules import ra...
DEQModel/train_trellisnet.py
MIT
15,315
29d67684a33f0c3c1488378c32fb34290c1e2afb
Python
py
#!/usr/bin/python # -*- encoding: utf-8 -*- import torch import torch.nn as nn import torch.utils.model_zoo as modelzoo import torch.nn.functional as F import torchvision import torch.utils.checkpoint as ckpt from modules import InPlaceABNSync as BatchNorm2d class ConvBNReLU(nn.Module): def __init__(self, ...
models/xception.py
MIT
9,132
29d67faf667c9116ad0ea81f1108c1c1138023ff
Python
py
from sys import exit from os import path, walk, makedirs from numpy import inf, array, where, partition, std as np_std from torch.optim import lr_scheduler, SGD, Adam, AdamW from torch import nn, no_grad, cuda, flatten, utils, cat, stack from torch.multiprocessing import set_start_method from tqdm import tqdm from li...
src/lib/pcapAE.py
MIT
25,763
29d6c9817c830af063ac3c96752b17774282362e
Python
py
import os from PIL import Image from torch.utils.data import Dataset from torchvision import transforms cls_to_idx = { 'plane': 0, 'car': 1, 'bird': 2, 'cat': 3, 'deer': 4, 'dog': 5, 'frog': 6, 'horse': 7, 'ship': 8, 'truck': 9 } def get_train_transforms(): normalize = transforms.Normalize(mean=(0.491, 0.482...
data.py
MIT
1,886
5f4e7516a2880c1bce4f56ac334dffcdd256d442
Python
py
# Copyright 2022 Huawei Technologies Co., Ltd # # 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...
official/cv/pwcnet/src/utils/ckpt_convert.py
Apache-2.0
1,606
4b7b01fd3ab0945b2ff3a1a185e267cd91dfc8a6
Python
py
""" This code is adapted from: https://github.com/ZJULearning/RMI The implementation of the paper: Region Mutual Information Loss for Semantic Segmentation. """ # python 2.X, 3.X compatibility from __future__ import print_function from __future__ import division from __future__ import absolute_import import torch im...
loss/rmi.py
BSD-3-Clause
9,614
1086a0b001499679c2075883e1a0b64606d088df
Python
py
# -*- coding: utf-8 -*- """ Created on Mon Oct 12 17:50:52 2020 @author: Mat Tun """ import numpy as np import os import argparse import time import cv2 import copy from imitrob_dataset import imitrob_dataset from torch.utils.data import DataLoader from object_detector import find_objects from cuboid_PNP_solver import...
trainer.py
BSD-3-Clause
17,788
29d70e51663931890544b360713c3e5d2d2c704e
Python
py
import torchvision.models as models print('Checking models...') print(models.resnet18()) print(models.alexnet()) print(models.vgg16()) print(models.squeezenet1_0()) print('Checking pretrained models...') # print(models.resnet18(pretrained=True)) # print(models.alexnet(pretrained=True)) print(models.squeezenet1_0(pret...
dl/pytorch/tests/vision.py
Apache-2.0
334
ff00ff9481a8189a826e010a9c13fa05e2eac21f
Python
py
import csv import gzip import importlib import logging import math import os import sys from collections import defaultdict from glob import glob from os import makedirs from pathlib import Path from typing import Dict, List, Callable import matplotlib.pyplot as plt import numpy as np import pandas as pd import seabor...
utils.py
MIT
14,945
1ece16f8d4756282bfaf610cb8b0e42ebc4195d3
Python
py
import numpy as np from collections import deque import torch import torch.nn.functional as F from opendr.perception.object_tracking_2d.fair_mot.algorithm.lib.models.decode import ( mot_decode, ) from opendr.perception.object_tracking_2d.fair_mot.algorithm.lib.tracking_utils.kalman_filter import ( KalmanFilte...
src/opendr/perception/object_tracking_2d/fair_mot/algorithm/lib/tracker/multitracker.py
Apache-2.0
15,434
29d74bedf2e313c8e16e6ea74243a46101e45a52
Python
py
import os import time import numpy as np import torch.multiprocessing import architectures as archs import batchminer as bmine import criteria as criteria import metric from modules.xbm import XBM from utilities import logger from utilities import misc from scripts._share import set_seed, get_dataloaders, train_one_ep...
scripts/standard.py
MIT
8,359
29d74c9eadc50886b640b2ea421749c7cdfbcb9f
Python
py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a cop...
src/transformers/configuration_utils.py
Apache-2.0
43,115
fd8786692caaef62f0a199793585af4817f45833
Python
py
from __future__ import print_function, division import torch import torch.nn as nn import torch.nn.parallel import torch.utils.data from torch.autograd import Variable import torchvision.utils as vutils import torch.nn.functional as F import numpy as np import copy def make_iterative_func(func): def wrapper(vars)...
utils/experiment.py
MIT
4,519
340f9215b0da4d3b7ea888296353270b2d3e2076
Python
py
import torch from torch import nn from torch.nn import utils from .init_filters import NN_CONV_LAYERS, NN_LINEAR_LAYERS def _check_module(model): if not isinstance(model, nn.Module): raise RuntimeError( f'apply_spectral_norm expected an nn.Module, got {torch.typename(model)}' ) _DEFA...
boardom/models/spectral_norm.py
BSD-2-Clause
1,434
42b0c3eafae6a68975be3af8b8e98fad49c71fd1
Python
py
from __future__ import absolute_import import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from model.utils.config import cfg from .proposal_layer import _ProposalLayer from .anchor_target_layer import _AnchorTargetLayer from model.utils.net_utils import _smooth_l1_lo...
lib/model/rpn/rpn.py
MIT
5,622
28d1fd7cea747bbea49adf82b783b930fcdc8eb2
Python
py