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
from __future__ import division import re from collections import OrderedDict import torch from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import DistSamplerSeedHook, Runner, obj_from_dict from mmdet import datasets from mmdet.core import (CocoDistEvalmAPHook, CocoDistEvalRecallHo...
mmdet/apis/train.py
Apache-2.0
8,771
2997bf3daa455424363a21e8817ae61e4f8758b3
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from core.models.discriminator import Discriminator from core.loss.diffaug import get_default_transforms class GANLoss(nn.Module): def __init__( self, image_size, channels_in=3, perceptual=False): ...
core/loss/gan_loss.py
Apache-2.0
1,793
7cde7174215fa76aebdba2443ae421e91b308f42
Python
py
from functools import partial import torch.nn as nn from catalyst.dl.utils import criterion class DiceLoss(nn.Module): def __init__( self, eps: float = 1e-7, threshold: float = None, activation: str = "Sigmoid" ): super().__init__() self.loss_fn = partial( ...
catalyst/contrib/criterion/dice.py
Apache-2.0
1,085
fcf9fa6c91a1320a0651daf957446dcdc8714ef2
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. from typing import List from dataclasses import dataclass import io import torch import polymetis import polymetis_pb2 from polymetis.utils.da...
polymetis/polymetis/python/polymetis/robot_client/metadata.py
MIT
4,285
299805614913400c1d10c24d46721c5c55060f75
Python
py
# from __future__ import division import os import numpy as np import torch import torch.nn as nn from torch.nn.functional import interpolate from ...nn import ConcurrentModule, SyncBatchNorm from .base import BaseNet __all__ = ['FCN', 'get_fcn', 'get_fcn_resnet50_pcontext', 'get_fcn_resnet50_ade', 'get_fc...
experiments/segmentation/encoding/models/sseg/fcn.py
MIT
7,774
b29e66cc02ef0f83a7f511ee9b184e18e82084f5
Python
py
import logging from typing import Callable, List import torch.nn as nn from .predict import predict from chemprop.data import MoleculeDataLoader, StandardScaler def evaluate_predictions(preds: List[List[float]], targets: List[List[float]], num_tasks: int, ...
chemprop/train/evaluate.py
MIT
3,843
42198ee902aae45a3aa8fa373912b7760d2bcbaa
Python
py
import argparse import functools import json import os import random import re from typing import Dict import numpy as np import torch SEPARATOR = {"stars": "".join(["*"] * 100), "dashes": "".join(["-"] * 100), "dots": "".join(["."] * 100)} def get_device(device_type: str) -> torch.device: if device_type == "cp...
auxiliary/utils.py
MIT
3,399
29982d98e4ec4d0ddd39d12438506be48be976a9
Python
py
"""NTM Read and Write Heads.""" import torch from torch import nn import torch.nn.functional as F import numpy as np def _split_cols(mat, lengths): """Split a 2D matrix to variable length columns.""" assert mat.size()[1] == sum(lengths), "Lengths must be summed to num columns" l = np.cumsum([0] + lengths)...
ntm/head.py
BSD-3-Clause
4,105
29982fee0d8f47caac19a07df273f9b1e783bd93
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 def create_var(tensor, requires_grad=None): if requires_grad is None: return Variable(tensor).cuda() else: return Variable(tensor, requires_grad=requires...
fast_jtnn/nnutils.py
MIT
2,081
f9a417c0af7e4280f48bde5dc48e5f1e6cce8e6a
Python
py
# -*- coding: utf-8 -*- # @Time : 2020/9/15 # @Author : Shanlei Mu # @Email : slmu@ruc.edu.cn r""" KGAT ################################################## Reference: Xiang Wang et al. "KGAT: Knowledge Graph Attention Network for Recommendation." in SIGKDD 2019. Reference code: https://github.com/xiangwang1...
recbole/model/knowledge_aware_recommender/kgat.py
MIT
12,523
29987a80a09ecde09ab5a2e09f5e4c1d7286af88
Python
py
import torch import torch.nn as nn import torch.nn.functional as F def _sum_tensor_scalar(tensor, scalar, expand_size): if scalar is not None: scalar = scalar.expand(expand_size).contiguous() else: return tensor if tensor is None: return scalar return tensor + scalar ...
seq2seq/models/modules/linear.py
MIT
2,189
5eccf1defb40a750b88843bd6b078c46ce760207
Python
py
import numpy as np import random import copy from collections import namedtuple, deque from model import Actor, Critic import torch import torch.nn.functional as F import torch.optim as optim BUFFER_SIZE = int(1e6) # replay buffer size BATCH_SIZE = 128 # minibatch size GAMMA = 0.99 # discount fact...
ddpg_agent.py
MIT
8,254
29988b39e4b45057a1848d573c7fe48e94ea6706
Python
py
import torch import torch.nn as nn from layers import Pooling, Concat, GCN, EventLSTM, MLP, TimeAttention ########################################### # TEMPORAL GCN ARCHITECTURES ############## ########################################### class DyGED_CT(nn.Module): def __init__(self, adj_size, n_feature, n_hidde...
source/models.py
MIT
4,084
29989a7ad5c8166dd9bed4b38c0a1542ee42e66e
Python
py
""" Copyright (c) Microsoft Corporation Licensed under the MIT license. """ import os from typing import Union import torch import json import copy from .constants import * from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, MIN_LOSS_SCALE, ) from .config_utils import ( ...
deepspeed/runtime/config.py
MIT
42,713
4b7e99ae99b7a05066a28555096bce938ea412a5
Python
py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os import mmcv import torch from mmedit.apis import init_model, restoration_face_inference from mmedit.utils import modify_args def parse_args(): modify_args() parser = argparse.ArgumentParser(description='Restoration demo') parser.a...
demo/restoration_face_demo.py
Apache-2.0
1,876
45f053045f780ff9acb87c4fb3915d02511d0468
Python
py
# Imports import numpy as np import torch from phimal_utilities.data import Dataset from phimal_utilities.data.burgers import BurgersDelta from DeePyMoD_SBL.deepymod_torch.library_functions import library_1D_in from DeePyMoD_SBL.deepymod_torch.DeepMod import DeepModDynamic from DeePyMoD_SBL.deepymod_torch.training im...
paper/figures/Burgers_noise/cluster/run_cluster.py
MIT
1,782
2998ab8c3e29680ca63d48f313e78fcb2d0845b3
Python
py
import torch from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score class Meter: """ This class is used to keep track of the metrics in the train and dev loops. """ def __init__(self, target_classes): """ :param target_classes: The classes for whom the met...
evaluation/tools/utils.py
MIT
3,624
2998bd0cca8971d44fcba2eed2ab87f4396853e4
Python
py
import math import torch import torch.nn as nn from torch.nn import functional as F from torch.autograd import Function from collections import OrderedDict from einops import rearrange, repeat from einops.layers.torch import Rearrange class FeedForward(nn.Module): def __init__(self, dim, hidden_dim, dropout=0.1)...
models/vit.py
MIT
5,063
e95a9589e279b5f6e2426eff0be7743d049d739c
Python
py
from typing import Dict, Tuple, Callable import numpy as np import torch from torch import nn class CNN(nn.Module): def __init__(self, network_params: Dict, activation: bool = True): super().__init__() input_size = network_params["input_size"] output_size = network_params["output_size"]...
classifier/classes/modules/base/CNN.py
MIT
8,081
249bf0c3253546a18b4dd0b2400700dc028e6b4a
Python
py
# # transform_a.py # # Author(s): # Matteo Spallanzani <spmatteo@iis.ee.ethz.ch> # # Copyright (c) 2020-2021 ETH Zurich. # # 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.ap...
systems/CIFAR10/VGG/preprocess/transform_a.py
Apache-2.0
1,496
d7366cae1b60899fea74c8094b835c7c3cb3cdbd
Python
py
from __future__ import print_function, division import warnings warnings.filterwarnings("ignore") import os.path import pandas as pd import torch import torch.nn as nn import numpy as np import torchvision from torchvision import datasets, models, transforms import dlib import os import argparse def rect_to_bb(rect): ...
predict.py
CC-BY-4.0
9,260
5e0ac5086d6f08e93f258b6f00758345fb0c6bd0
Python
py
# Copyright 2020 Nagoya University (Tomoki Hayashi) # Copyright 2021 Carnegie Mellon University (Jiatong Shi) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Muskit singing voice synthesis model.""" from contextlib import contextmanager from distutils.version import LooseVersion import logging from typ...
muskit/svs/muskit_model.py
Apache-2.0
30,756
ff64c3cb8586fa697cd00ca44db44e3556c5617b
Python
py
from torch.nn import init ### initalize the module def init_weights(net, init_type='normal'): #print('initialization method [%s]' % init_type) if init_type == 'kaiming': net.apply(weights_init_kaiming) else: raise NotImplementedError('initialization method [%s] is not implemented' % init_t...
nnunet/unet_nested/utils.py
Apache-2.0
1,099
29991169ab2b0ae789624e18ff1c5994a9638fa9
Python
py
# -------------------------------------------------------- # Visual Detection: State-of-the-Art # Copyright: Hanbo Zhang # Licensed under The MIT License [see LICENSE for details] # Written by Hanbo Zhang # -------------------------------------------------------- import torch import torch.nn as nn from torch.autograd...
model/op2l/rois_pair_expanding_layer.py
MIT
2,362
b2afa6f16dccf8ffcd603cc5fd69c26dcea93165
Python
py
""" Copyright (c) 2019-present NAVER Corp. MIT License """ # -*- coding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F from basenet.vgg16_bn import vgg16_bn, init_weights class double_conv(nn.Module): def __init__(self, in_ch, mid_ch, out_ch): super(double_conv, self).__i...
craft.py
MIT
2,759
a97446f5509818d09ca6f25d1828866393ed3cc0
Python
py
import numpy as np import torch from torchvision import datasets import torchvision.transforms as transforms import matplotlib.pyplot as plt from skimage.measure import compare_psnr, compare_ssim import skimage.io as sio from glow.glow import Glow from dcgan.dcgan import Generator import json import os import warnings ...
solvers/inpainter.py
MIT
21,413
e9cfe90b66d9caf0ea7a960c41dc70171ad91e5b
Python
py
import torch from . import samplers def make_data_sampler(dataset, shuffle, distributed, is_train=True): # Only do weighted sampling for training if distributed: # if is_train: # return samplers.DistributedWeightedSampler(dataset, shuffle=shuffle) # else: return samplers.Dis...
datasets/build_samplers.py
Apache-2.0
1,624
2999783cf059803651e101f86706b68bbf9ffd85
Python
py
import time import os import numpy as np import cv2 import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.backends.cudnn as cudnn from torchvision import datasets, transforms import datasets.dataset from core.utils import * from cfg.cfg import parse...
app/libs/action_localization/spatio-temporal-libs/test_images.py
MIT
11,297
10a201d1a7da6f638bec5fbfcefdc2981b0fbbae
Python
py
""" # Author : GS Oh # Experiment : The gaussian experiments presented in the HCNAF paper # Note : Define the gaussian experiments """ # GS: if condition == 1, then generate 8 gaussians, else 4 gaussians import torch import sklearn import numpy as np def sample_dataset(num_samples, args, flag_sample_targ...
HCNAF_Gaussians/exp_hcnaf_gaussians.py
Apache-2.0
2,326
2999d1111ac470322bfb52b6065edf3e6aa75d98
Python
py
import math import torch from .module import Module from ..parameter import Parameter from ..utils.rnn import PackedSequence class RNNBase(Module): def __init__(self, mode, input_size, hidden_size, num_layers=1, bias=True, batch_first=False, dropout=0, bidirectional=False): ...
torch/nn/modules/rnn.py
MIT
24,197
5e4b785971bcbe364b3d84b0a730833a8d40bab8
Python
py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -------------------------------------------------------------------------- from . import _utils, _io, _logger from ._graph_execution_manager import...
orttraining/orttraining/python/training/ortmodule/_training_manager.py
MIT
16,130
d7606eee404e10ff8d71d1a24d250e9880f46fbe
Python
py
from collections import Counter, OrderedDict from functools import wraps import numpy as np from transformers import BertTokenizer import torch def _check_build_bert_vocab(func): @wraps(func) def _wrapper(self, *args, **kwargs): if self.bert_tokenizer is None: self.build_vocab() re...
utils/vocab.py
Apache-2.0
11,960
299a0959db3c993461200773dd9b4e74edb15a46
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...
examples/run_squad.py
Apache-2.0
35,374
f94fb22098d54cd865808a4365327a0de142b459
Python
py
import torch import torch.nn as nn from typing import Union, Dict, Optional from schnetpack import units as spk_units import schnetpack.nn as snn from schnetpack import properties import numpy as np __all__ = ["CoulombPotential", "DampedCoulombPotential", "EnergyCoulomb", "EnergyEwald"] class CoulombPotential(nn.M...
src/schnetpack/atomistic/electrostatic.py
MIT
12,651
b215714960c369d455f8a54940b0ab7171ffa37e
Python
py
#!/usr/bin/env python3 import time from functools import partial import numpy as np import torch from torch import roll, zeros # <1> DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # <2> GRID_SHAPE = (2048, 2048) def timer(fxn, max_time=5): N = 0 total_time = 0 fxn() # prime...
07. Chapter_7/pytorch/diffusion_pytorch.py
MIT
2,508
fdf631152f85d367f82eea0450da0a5968dd11b1
Python
py
"""Test `diameter_learning.nets.layers.diameter` code """ import shutil from itertools import product import math import torch import numpy as np import matplotlib.pyplot as plt import matplotlib from diameter_learning.settings import TEST_OUTPUT_PATH from diameter_learning.nets.layers import ( CenterOfMass2DEx...
test/nets/layers/test_diameter.py
MIT
12,548
a93982e289398a8723dd07ad40d7c57a4952f2ce
Python
py
# encoding: utf-8 """ @author: liaoxingyu @contact: sherlockliao01@gmail.com """ import copy import torch from torch import nn import pdb from .build import META_ARCH_REGISTRY from ..backbones import build_backbone from ..backbones.resnet import Bottleneck from ..heads import build_reid_heads from ..model_utils impor...
fastreid/modeling/meta_arch/HAA_BASELINE.py
MIT
10,364
4b0eaacedd3a6279683517888035e30e65e3f864
Python
py
# adapted from Trainer.py of huggingface transformers import json import logging import os import random from typing import Callable, Dict, List, NamedTuple, Optional, Tuple import numpy as np import torch from torch import nn from torch.utils.data.dataloader import DataLoader from torch.utils.data.dataset import Da...
orttraining/orttraining/test/python/orttraining_transformer_trainer.py
MIT
16,408
b2228bff28241b1490b797633ea4febaa8f9d319
Python
py
# -*- coding: utf-8 -*- from config import opt import models import datasets import torch from torch.utils.data import DataLoader import torch.optim as optim from utils import save_pr, now, eval_metric def collate_fn(batch): data, label = zip(*batch) return data, label def test(**kwargs): pass def train(**kwar...
Algorithm-code/RelationExtraction_CNN+ATT/main_att.py
MIT
4,048
299a517bd6f7babf0441b6f38e04f2144c0ea5e3
Python
py
""" This module contains neural networks for predicting device performance, based on tabular data and m2py labels """ import torch import torch.nn as nn class OPV_df_NN(nn.Module): """ expects tabular data predicting 4 OPV device metrics: PCE, Voc, Jsc, and FF """ def __init__(self, in_dims, out...
m2py/networks/morphology_networks.py
Apache-2.0
5,561
299a61cb72b97d1d4e986311af1b8fb2ccfb5dd4
Python
py
"""Visualizes CNN activation maps to see where the CNN focuses on to extract features. Reference: - Zagoruyko and Komodakis. Paying more attention to attention: Improving the performance of convolutional neural networks via attention transfer. ICLR, 2017 - Zhou et al. Omni-Scale Feature Learning for Pers...
tools/visualize_actmap.py
MIT
6,447
ff8a71d98ccdfa98a86f81df5c4c9d4b1865e94a
Python
py
import argparse import pickle import torch import torch.nn as nn import torch.optim as optim from pathlib import Path from torch.utils.data import DataLoader from transformers.modeling_bert import BertConfig from pretrained.tokenization import BertTokenizer as ETRITokenizer from gluonnlp.data import SentencepieceTokeni...
BERT_pairwise_text_classification/train.py
MIT
5,914
299a77b4e0ec3d47b00621046760bba0b6d49ce2
Python
py
import logging import math import numpy as np import torch import torch.distributed as dist from . import default_hooks as default def _orthogonalize(matrix, epsilon=0): """ Applies Gram-Schmidt procedure to orthogonalize a given 2D tensor. If epsilon is 0, this is equivalent to `torch.qr(matrix, out=(m...
torch/distributed/algorithms/ddp_comm_hooks/powerSGD_hook.py
Intel
35,365
6b0d747d460d2cfc2661319d5599b8fa44e70694
Python
py
import torch import torchvision import torchvision.transforms as T import foolbox as fb from tqdm import tqdm from .base import Adversary from .dict2obj import Config from .config import * class ModelNotDefineError(Exception): pass class LossNotDefineError(Exception): pass class OptimNotIncludeError(Exception): pa...
src/loadopts.py
MIT
12,698
299a94919523925ec8d24a6a734b860bf807bcb9
Python
py
import torch from torch import nn from torch.nn import init import torch.nn.functional as F import math from torch.autograd import Variable import numpy as np config_vgg = {'convert': [[128,256,512,512,512],[64,128,256,512,512]], 'deep_pool': [[512, 512, 256, 128], [512, 256, 128, 128], [True, True, True...
KRN_edge.py
MIT
10,393
299ac5a5e4661d2adc9d19acb8af6c6cdd6fcb92
Python
py
from torch.utils.data import Dataset class AvazuDataset(Dataset): def __init__(self, num_sample=NUM_SAMPLE): pass def __len__(self): pass def __getitem__(self): pass
ctr_data/avazu.py
MIT
218
5f67fce84244aa0ddfdd38ddae2ee9ab125397f8
Python
py
import torch from tqdm import tqdm from tqdm.notebook import tqdm as tqdm_notebook from nfractal.utils.dev import isnotebook """ Base Sampler Class """ class Sampler(): def sample(self): raise NotImplementedError("Sampler is an abstract class") """ Uniform Sampler Class This class samples from...
nfractal/samplers.py
MIT
4,679
299acf51ebdf5debe00380fe690f301df4821c4d
Python
py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import torch from torch.optim.optimizer import Optimizer class AdagradRMSProp(Optimizer): """ Implements a mash-up of the Adagrad algorithm and RMSProp. For the precise update equation see equations 10 and 11 in refer...
pyro/optim/adagrad_rmsprop.py
Apache-2.0
2,924
299ad49f18182f1fc39107d1776aa5b9917b4b87
Python
py
from asyncio.constants import LOG_THRESHOLD_FOR_CONNLOST_WRITES import time from typing import Any, Dict, List, Optional, Tuple, Type, Union import gym import numpy as np import torch as th from tqdm import trange from stable_baselines3.common import distributions from stable_baselines3.common.base_class import BaseA...
stable_baselines3/common/on_policy_algorithm_multi_level.py
MIT
29,709
f92fc40f0360817892502705bedfadc116eca18c
Python
py
import torch import torch.nn as nn from fastai.layers import ConvLayer, PixelShuffle_ICNR, ResBlock from torch import Tensor arch_name = "cloudnet_plus" class ContractionBlock(nn.Module): def __init__(self, ni, residual=False): super().__init__() if residual: self.conv1 = ResBlock(ni...
cloud/models/cloudnetplus.py
MIT
7,561
6547b6037ca9d4ed3c6d00893cf5748f974f3070
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...
tests/trainer/connectors/test_signal_connector.py
Apache-2.0
2,101
a957cac4df51814b152442df18828db1ac082a2a
Python
py
from pathlib import Path import numpy as np import pandas as pd import pytorch_lightning as pl import skimage.io import torch from omegaconf import OmegaConf from torch.utils.data import DataLoader, RandomSampler from torch.utils.data.dataset import Dataset as TorchDataset from ls_axon_segmentation.enums import Class...
ls_axon_segmentation/data_module/lm_data_module.py
MIT
8,640
28fb394880d2e8625364c2319feb2eeddcd0f689
Python
py
#! /usr/bin/env python # coding=utf-8 # Copyright (c) 2019 Uber Technologies, 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 # # Unles...
ludwig/encoders/sequence_encoders.py
Apache-2.0
98,152
1e9af5b6baea4ccb754036f6edf2aa549b47498c
Python
py
# coding=utf-8 # Copyright 2020 Google AI, Google Brain, the HuggingFace Inc. team and Microsoft Corporation. # # 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/lic...
examples/research_projects/bert-loses-patience/pabee/modeling_pabee_albert.py
Apache-2.0
14,134
5e17352dc19b54c9f0008d7a9263c1b1ca1d4538
Python
py
import os import numpy as np import h5py import json import torch from imageio import imread from PIL import Image from tqdm import tqdm from collections import Counter from random import seed, choice, sample import cv2 import torchvision.transforms def create_input_files(dataset, json_path, image_folder, captions_per...
SAT_tutorial/utils.py
MIT
10,219
129af4543b940947b707cdf6fcec12c449fc85d7
Python
py
import sys import datetime import torch import torch.optim as optim import torch.nn.functional as F import torchvision import torchvision.transforms as transforms import torchvision.datasets as datasets import matplotlib.pyplot as plt from model import VAE from plot_utils import display_and_save_batch from arguments ...
Implementations/Variational-Autoencoder/train.py
MIT
8,464
299b3bd16befa94655ba670ad5c807d622fe123f
Python
py
import SinGAN.functions as functions import SinGAN.models as models import os import torch.nn as nn import torch.optim as optim import torch.utils.data import math import matplotlib.pyplot as plt from SinGAN.imresize import imresize from tqdm import tqdm import numpy as np def train(opt,Gs,Zs,reals,NoiseAmp): real...
SinGAN_pytorch/SinGAN/training.py
MIT
14,878
ff9944113bfebce8d4cf1808aaa1c3a5c4dfdbff
Python
py
############################################################################### # Language Modeling on Wikitext-2 # # This file generates new sentences sampled from the language model # ############################################################################### import argparse import torch import data parser = ...
experiments/ptb_wikitext/model/generate.py
MIT
3,111
299b7d88495edad6c98bdbf351d7de39a94e46aa
Python
py
import torch from torchvision import datasets from torchvision import transforms from torch.utils.data import DataLoader from torch.utils.data import SubsetRandomSampler from torch.utils.data import sampler class UnNormalize(object): def __init__(self, mean, std): self.mean = mean self.std = std ...
L16/helper_data.py
MIT
8,382
299b84794e248ff181c4edd8fede898930b48be2
Python
py
#!/Users/fa/anaconda/bin/python import sys sys.path = ['../feedbackmodels'] + sys.path from feedbackmodels import models as mod sys.path = ['../utils', '../monolingual-word-aligner'] + sys.path import utils import FBSimilarityMeasures as fb import numpy as np import gensim from gensim.models import Word2Vec from sklea...
featuremodels/models.py
MIT
11,455
299b8be17ec020b493e41e40a07bccc399a56d46
Python
py
import numpy as np from PDE_find import Diff, Diff2, FiniteDiff import Data_generator as Data_generator import scipy.io as scio from requests import get from inspect import isfunction import math import pdb import random import matplotlib.pyplot as plt import torch.nn as nn import torch from torch.nn import...
codes/setup.py
MIT
17,367
299ba674316d26eb2e16e2077beaba7a65639556
Python
py
""" Copyright (C) 2018 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). """ from torch.utils.serialization import load_lua from torch.utils.data import DataLoader from networks import Vgg16 from torch.autograd import Vari...
MUNIT/utils.py
Apache-2.0
19,599
299bc48e2d2f913e98a2f3e0eeacb77ae6b0d121
Python
py
from __future__ import absolute_import, division, print_function import torch from torch.distributions import constraints from torch.nn import Parameter import pyro import pyro.distributions as dist from pyro.contrib.gp.models.model import GPModel from pyro.contrib.gp.util import conditional from pyro.params import p...
pyro/contrib/gp/models/vgp.py
MIT
6,828
299be17a889b1868ffb29ad1e5b6436e6828f4e8
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from layers.Transformer_EncDec import Decoder, DecoderLayer, Encoder, EncoderLayer, ConvLayer from layers.SelfAttention_Family import FullAttention, AttentionLayer from layers.Embed import DataEmbedding import numpy as np class Transformer(nn.Module):...
models/seq2seq/Transformer.py
Apache-2.0
2,945
10f053f042cda2444b9d78863f0c75527fa9321b
Python
py
""" This example is largely adapted from https://github.com/pytorch/examples/blob/master/imagenet/main.py """ import os import random from argparse import ArgumentParser, Namespace from collections import OrderedDict import torch import torch.backends.cudnn as cudnn import torch.nn.functional as F import torch.nn.para...
pl_examples/domain_templates/imagenet.py
Apache-2.0
9,022
299c078d172119f6dd05c4948065096f758fbb7f
Python
py
#!/usr/bin/env python #coding:utf-8 """ Tencent is pleased to support the open source community by making NeuralClassifier available. Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the Licens...
dataset/dataset.py
Apache-2.0
15,424
299c35aed88f4416c0c665b9023b32c3dc07817b
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/plugins/training_type/tpu_spawn.py
Apache-2.0
11,820
299c362e7181aba25d7084076afaa34c8f1e9717
Python
py
# -*- coding: utf-8 -*- # @Time : 2019/8/23 21:56 # @Author : THU from torch import nn from torchocr.networks.losses.DetBasicLoss import BalanceCrossEntropyLoss, MaskL1Loss, DiceLoss class DBLoss(nn.Module): def __init__(self, alpha=1.0, beta=10, ohem_ratio=3, reduction='mean', eps=1e-6): """ ...
CAIL2020/cocr/torchocr/networks/losses/DBLoss.py
Apache-2.0
2,232
299c3eb18122e58cdbbb5ec4cd261afe0cc78ee4
Python
py
# Owner(s): ["oncall: jit"] import unittest import os import random import enum import copy from functools import reduce import operator import torch from torch.nn import functional from torch.testing._internal.common_utils import run_tests, ProfilingMode, GRAPH_EXECUTOR # TEST_WITH_ROCM from torch.testing._interna...
test/test_jit_cuda_fuser.py
Intel
153,327
299c738c570ab0b57166ff8af8b1b347a6cbca15
Python
py
# Higher order DGNet # by Sølve Eidnes, 2021 # See "Order theory for discrete gradient methods" (https://arxiv.org/abs/2003.08267) # # This code is based on # DGNet: Deep Energy-based Modeling of Discrete-Time Physics (2020) # by Takashi Matsubara, Ai Ishikawa, Takaharu Yaguchi # https://github.com/tksmatsubara/d...
experiment-spring/dgnet_compare_training.py
MIT
13,540
7c8b0ddd1f5884ab26af8d3942c1cf06e02327a7
Python
py
from agent.ddpg import * from agent.replay_buffer import * import torch class MADDPG(object): def __init__(self, **kwargs): """ Initializes multiple agents using DDPG algorithm. Parameters ---------- kwargs : """ self.num_agents = kwargs.get("num_agents", 2)...
Collaboration-and-Competition-using-MADDPG/maddpgcollaboration/agent/maddpg.py
MIT
3,153
299c93a76301a303c60bfe9ba5c1432ff610556f
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable def one_hot(index, classes): out_idx = torch.arange(classes, device=index.device) out_idx = torch.unsqueeze(out_idx, 0) index = torch.unsqueeze(index, -1) return (index == out_idx).float() class Fo...
ml3d/torch/modules/losses/focal_loss.py
MIT
1,716
299c9af1de9114f6a5a90ccd0eeb05ca798e8ff3
Python
py
from torch.autograd import Function from .backend import _backend __all__ = ['trilinear_devoxelize'] class TrilinearDevoxelization(Function): @staticmethod def forward(ctx, features, coords, resolution, is_training=True): """ :param ctx: :param coords: the coordinates of points, Floa...
pvcnn/modules/functional/devoxelization.py
MIT
1,467
e9dd014e393a468b8b5b40b8654860fc7ab87eea
Python
py
# coding=utf-8 """Test _utils module.""" from __future__ import absolute_import, division, print_function import os import shutil from future.standard_library import install_aliases import numpy as np import pytest import torch from iftorch._utils import dataloader, reverse_mapping from iftorch.save_utils import ( ...
tests/test_utils.py
Apache-2.0
3,930
2480220ed8f92016852f7f33be4ef6a40522f934
Python
py
import argparse import os from os import path import copy import numpy as np import torch from torch import nn from ganstab.gan_training import utils from ganstab.gan_training.checkpoints import CheckpointIO from ganstab.gan_training.distributions import get_ydist, get_zdist, interpolate_sphere from ganstab.gan_trainin...
interpolate_class.py
MIT
3,080
d7cc03de3103802b9000d803e45b842f92851d3f
Python
py
import torch from torch import nn from torch.autograd import Variable from torch.autograd import Function import torchtext from torchtext import data import io import os import numpy as np from data.indep_bernoulli.load_data import load_data # Data processing # ------------------------------------------------------...
utils.py
MIT
7,162
299cf0a30fdc262b45f8619846e2c7a4efa342cc
Python
py
import os import torchvision from matplotlib import pyplot as plt import torch import glob import os from shutil import copyfile from io import BytesIO from PIL import Image import time import heapq from heapq import heappush from heapq import heappop from torchvision import datasets import sys import gc gc.collect()...
AJCAI2021/predict_age.py
MIT
2,747
b2fea4c5f43afc0275bc0660327fe50b81100f35
Python
py
import copy import os from PIL import Image import torch import torch.utils.data import torchvision from pycocotools import mask as coco_mask from pycocotools.coco import COCO from . import transforms as T class FilterAndRemapCocoCategories(object): def __init__(self, categories, remap=True): self.cate...
src/notebooks/coco_utils.py
MIT
9,320
299d5189880b068d20a3e49ea7fbfa8ce0d2cfc7
Python
py
import numpy as np import torch import kornia.geometry as tgm import pickle import os from PIL import Image from torchvision import transforms from torch.nn import functional as F import cv2 from pathlib import Path from tqdm import tqdm import argparse import pandas as pd def alignmentError(wB, hB, wA, hA, XA, YA, ...
evaluation/evalCorr/getResults.py
MIT
11,688
299d55f7ac04b9ef653d4f4d4d2251a531a84c51
Python
py
import argparse import json import os import random import time import numpy as np import torch.distributed as dist import torch.utils.data.distributed # from apex.fp16_utils import FP16_Optimizer # from apex.parallel import DistributedDataParallel from warpctc_pytorch import CTCLoss from data.data_loader import Audi...
train.py
MIT
19,036
10f8b77ff14c51e0a67c45667bf0715b78e57685
Python
py
""" Implementation of "Attention is All You Need" """ import torch import torch.nn as nn import numpy as np import onmt from onmt.modules.position_ffn import PositionwiseFeedForward MAX_SIZE = 5000 class TransformerDecoderLayer(nn.Module): """ Args: d_model (int): the dimension of keys/values/queries...
onmt/decoders/transformer.py
MIT
11,272
24d39b4c1fc3524ad4cebe3d11276d5e817f30b6
Python
py
import os import logging import torch from corrupter import BernCorrupter, BernCorrupterMulti from read_data import index_ent_rel, graph_size, read_data from config import config, overwrite_config_with_args from logger_init import logger_init from data_utils import inplace_shuffle, heads_tails from select_gpu import se...
pretrain.py
MIT
2,134
299da192c30bc4582ebc3556b2730d4e69f9ecd2
Python
py
#!/usr/bin/env python import torch from torch.utils.data import DataLoader import pickle from rdkit import Chem from tqdm import tqdm import data_struct as ds from data_struct import MolData, Vocabulary from data_struct import Variable, decrease_learning_rate from model import RNN import sys def Transfer(restore_from ...
transfer_learning.py
MIT
2,648
299da65890836a8b2e93d6dbf149bbb3dbdd43c4
Python
py
from random import choice from loguru import logger import torch import pandas as pd from torch.utils.data import Dataset class CustomDataset(Dataset): """Custom dataset that reads one bitext chunk at a time. Parameters ---------- bitext_file : str or list of str Path to the bitext file (*.c...
seq2seq/data.py
MIT
4,085
299dcbd7d7ab93aa767cb646fa7a28927d46a98a
Python
py
# 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, software # distributed under th...
tests/helpers/boring_model.py
Apache-2.0
6,311
128ed292aec430c17ec9df1106e50802c6e5125d
Python
py
import os import logging import argparse import numpy as np from tqdm import tqdm import torch from torch.serialization import default_restore_location from seq2seq import models, utils from seq2seq.data.dictionary import Dictionary from seq2seq.data.dataset import Seq2SeqDataset, BatchSampler from seq2seq.beam impor...
translate_beam.py
MIT
11,405
299e060e10af4eb8d6b3c1b973210da6c5d28261
Python
py
''' This file is a part of the official implementation of 1) "DISCO: accurate Discrete Scale Convolutions" by Ivan Sosnovik, Artem Moskalev, Arnold Smeulders, BMVC 2021 arxiv: https://arxiv.org/abs/2106.02733 2) "How to Transform Kernels for Scale-Convolutions" by Ivan Sosnovik, Artem Moskalev, Arnold Smeu...
models/basis/base.py
MIT
1,950
299e44527a4213867f38e0a0c524d1ee3fe30722
Python
py
#!/usr/bin/env python3 -u # 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 logging import os from fairseq.dataclass.initialize import add_defaults, hydra_init from fairseq_cli.train i...
fairseq_cli/hydra_train.py
MIT
2,664
299e562ddece1d8050680565f1ddccf46fc77a83
Python
py
# coding=utf-8 # Copyright 2019 HuggingFace 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 ag...
tests/test_modeling_common.py
Apache-2.0
34,946
b284ee6ec2e9c8a56ed385c90c55d7aeb6662cb9
Python
py
""" algorithm: """ import torch import torch.nn as nn from utils import v_wrap, set_init, push_and_pull, record,push import torch.nn.functional as F import torch.multiprocessing as mp from shared_adam import SharedAdam import gym import os import random import numpy as np import time from a3c.NN import DiscreteNet os...
ReDRL/Red_a3c.py
MIT
6,985
299ec32f708eb3df417e9cf256720d509bbe157c
Python
py
import time import torch from util import MovingAverage def aggreg_multi_gpu(model, dataloader, hc, dim, TYPE=torch.float64, model_gpus=1): """"Accumulate activations and save them on multiple GPUs * this function assumes the model is on the first `model_gpus` GPUs so that it can write the activa...
multigpu.py
MIT
4,968
299ed197e32cbc4f93569ee37eddcbe5784b3c07
Python
py
import torch import numpy as np def point_form(boxes): """ Convert prior_boxes to (xmin, ymin, xmax, ymax) representation for comparison to point form ground truth data. Args: boxes: (tensor) center-size default boxes from priorbox layers. Return: boxes: (tensor) Converted xmin, ymin, ...
utils/box_utils.py
MIT
13,257
299eecea612eef1ab8c36bcbf82b533fe88d7ca1
Python
py
# Copyright (c) 2015-present, Facebook, Inc. Modified By Wenhao Wang, Weipu Zhang. # All rights reserved. import warnings warnings.filterwarnings('ignore') from models_balance.gem import GeneralizedMeanPoolingP import sys import os import pdb import argparse import time from collections import OrderedDict, defaultdict ...
Test/final/V5_baseline_CC_ref/extract_feature_r.py
MIT
10,057
fceb5376a5936d9d9c146f0424dd0981a466c797
Python
py
import math import pytest import torch from torch.nn.functional import pad from pyro.ops.gaussian import Gaussian, gaussian_tensordot from tests.common import assert_close def random_gaussian(batch_shape, dim, rank): """ Generate a random Gaussian for testing. """ log_normalizer = torch.randn(batch_...
tests/ops/test_gaussian.py
MIT
3,614
1eb2a2f0b1ffa46becf20243eb07e86d02752ac7
Python
py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """ Functions for training and evalu...
federated/train.py
BSD-3-Clause-Attribution
14,037
e9a8cea4db971d2f645a0ebf49cf10ba7a9a9097
Python
py
import torch from collections import OrderedDict from os import path as osp from tqdm import tqdm from basicsr.archs import build_network from basicsr.losses import build_loss from basicsr.metrics import calculate_metric from basicsr.utils import imwrite, tensor2img from basicsr.utils.registry import MODEL_REGISTRY fr...
basicsr/models/hifacegan_model.py
Apache-2.0,MIT
11,782
1ec6f673cd2d1dcb24a2b6a9ad9b6eef472f3505
Python
py
import logging from os import listdir from os.path import splitext from pathlib import Path import numpy as np import torch from PIL import Image from torch.utils.data import Dataset class BasicDataset(Dataset): def __init__(self, images_dir: str, masks_dir: str, scale: float = 1.0, mask_suffix: str = ''): ...
train/data_loading.py
MIT
3,100
ff28a21b9985b1618d5ecffb5884442b7344df3c
Python
py
import torch.nn as nn class InnerConvBlock(nn.Module): def __init__( self, input_dim, filters, kernel_size, strides=1, relu_activation=True, batch_normalization=True, ): super(InnerConvBlock, self).__init__() self.relu_activation = relu_a...
src/model/pytorch/base_layers.py
MIT
2,646
e95f19c4b470654cc2b1b9e10449cc4184156f4f
Python
py
import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F from torch.nn import Parameter import math def myphi(x,m): x = x * m return 1-x**2/math.factorial(2)+x**4/math.factorial(4)-x**6/math.factorial(6) + \ x**8/math.factorial(8) - x**9/math.factorial(...
net_sphere.py
MIT
6,209
1e6b31e2ab67feb061c0165f015e51ac4fbea5ea
Python
py
""" train.py Main interface to train the GNNs that will be later explained. """ import argparse import os import pickle import random import shutil import time import matplotlib import matplotlib.colors as colors import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg as Figure...
train.py
Apache-2.0
37,322
52e49b83dcac3c965fc00f7d03032917386a9080
Python
py