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
# -*- coding: utf-8 -*- """Tests for distributed multiplication operators.""" # Standard library imports import functools # PyTest imports import pytest # PyTorch imports import torch # Local imports from distributed_dot_product.utils.comm import get_rank, get_world_size from distributed_dot_product.multiplicatio...
distributed_dot_product/tests/test_multiplication.py
MIT
6,470
10a3abf1c658dcf35069663a0d639bedf55df841
Python
py
# -*- coding: utf-8 -*- """ @date: 2022/4/25 下午4:06 @file: tiny_autocoder.py @author: zj @description: """ import torch from zcls2.config.key_word import KEY_OUTPUT from simpleir.configs.key_words import KEY_FEAT from simpleir.models.tiny_autocoder import TinyAutoCoder if __name__ == '__main__': img = torch.r...
tests/model/tiny_autocoder.py
Apache-2.0
629
3a01a8bec27e4bf406bfcb9fa8d3b0e28cf4bb1f
Python
py
# Copyright 2018-2020 Xanadu Quantum 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 # Unless required by applicable law or...
tests/test_measurements.py
Apache-2.0
51,356
3a01ad468fa98be1639c99483531c384392a9d9e
Python
py
import torch import torch.nn as nn from asym_rlpo.data import Episode from .base import PO_A2C_ABC class AsymA2C(PO_A2C_ABC): model_keys = { 'agent': [ 'action_model', 'observation_model', 'history_model', 'policy_model', ], 'critic': [ ...
asym_rlpo/algorithms/a2c/asym_a2c.py
MIT
1,067
4598390cb291c2400fbbbe0ab94439176bfe0d3f
Python
py
import torch import numpy as np device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class ReplayBuffer: """Fixed-size buffer to store experience tuples.""" def __init__(self, state_size, action_size, buffer_size, batch_size, priority=False): """Initialize a ReplayBuffer object. ...
ReplayBuffer.py
MIT
2,803
42888070da99f044f3ece1749ee0b3d6c561fe16
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from i2a.utils import get_conv_output_dims from functools import reduce class EncoderCNNNetwork(nn.Module): def __init__(self, input_shape): super(EncoderCNNNetwork, self).__init__() input_channels = input_shape[0] input_dim...
i2a/rollout_encoder.py
MIT
5,994
b29288adbac51f27ff23a7d0b80230959f2cd4bb
Python
py
import torch import torch.utils.data from torchvision import datasets import numpy as np # Assumes that tensor is (nchannels, height, width) def tensor_rot_90(x): return x.flip(2).transpose(1, 2) def tensor_rot_180(x): return x.flip(2).flip(1) def tensor_rot_270(x): return x.transpose(1, 2).flip(2) def rotate_si...
code/digit/rotation.py
MIT
1,964
106c9c1d74179285d512cd268021b0fcd5b3d548
Python
py
import os import pickle import cv2 import numpy as np import torch from torch.utils.data import DataLoader from collections import OrderedDict import matplotlib.pyplot as plt from tsnecuda import TSNE from scipy.ndimage import gaussian_filter1d from .abstract.abstract_hook import HookBase from lib.datatool...
lib/core/hook/stae_hooks.py
Apache-2.0
6,159
3a020e2d66b6551b60bba9ac8c88d142d33a886e
Python
py
# Authors: YiFan Sun <peter@megvii.com>, Changmao Cheng <chengchangmao@megvii.com> from typing import Tuple import torch from torch import nn from torch.nn.functional import cross_entropy class ClassificationCircleLoss(nn.Module): """Circle loss for class-level labels as described in the paper `"Circle Loss:...
cvpods/modeling/losses/circle_loss.py
Apache-2.0
2,636
3a02126b25c63266f7ba91e8b43a23ad85504abe
Python
py
import torch as th import torch.nn as nn from leibniz.unet.senet import SELayer class DirectBlocks(nn.Module): extension = 1 least_required_dim = 1 def __init__(self, dim, step, relu, conv, reduction=16): super(DirectBlocks, self).__init__() self.dim = dim self.step = step ...
src/blks/direct.py
Unlicense
1,174
3a0252ad9ae269d4fdc006c8a697b413236bc9fe
Python
py
""" Copyright (c) 2018 Intel 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/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writin...
pytorch_toolkit/face_recognition/datasets/vggface2.py
Apache-2.0
5,447
12f3afaa318a244c3a234735e5aeb33f3ad11435
Python
py
import argparse import os import numpy as np import math import itertools import torchvision.transforms as transforms from torchvision.utils import save_image from torch.utils.data import DataLoader from torchvision import datasets from torch.autograd import Variable from mnistm import MNISTM import torch.nn as nn ...
.history/implementations/pixelda/pixelda_20190101223306.py
MIT
19,208
5e54504c0f499aec31cf2392c5aa6b29e26b4ab7
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/utilities/apply_func.py
Apache-2.0
10,975
d7d09251f60870daa3b6dc2ac1202cdb0bcada6c
Python
py
# Copyright (c) 2018-2021, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of condit...
elegantrl/envs/isaac_integration/tasks/cartpole.py
Apache-2.0
9,286
3a0299d28d1437633bd4c0e5f3a29803402d6f6e
Python
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import pycocotools.coco as coco # from pycocotools.cocoeval import COCOeval from utils.cocoeval import COCOeval #from utils.voc_metric.pascalvoc import cal_voc_map import numpy as np import torch import json im...
src/lib/datasets/dataset/foodsoft2_100.py
MIT
9,803
3a02d926ef164371e544c89299c5dacfc603562f
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. import gc import math import time import random import torch from torch import optim from tqdm import tqdm from pythia.common.meter import Meter from pythia.common.registry import registry from pythia.common.report import Report from pythia.common.dataset_loader impo...
pythia/trainers/base_trainer.py
BSD-3-Clause
19,121
fce1d74c5c3055a287c39f56a064116ef4b377d3
Python
py
import torch import torch.nn as nn # All neural network modules, nn.Linear, nn.Conv2d, BatchNorm, Loss functions import torch.optim as optim # For all Optimization algorithms, SGD, Adam, etc. import torch.nn.functional as F # All functions that don't have any parameters from torch.utils.data import ( DataLoader,...
BaseLine.py
MIT
3,122
1098c885d74b0eddf7b1498fd8477df6129af6a3
Python
py
"""Train a model on SQuAD. Author: Rohit Musti (rmusti@redhat.com) Chris Chute (chute@stanford.edu) """ import numpy as np import random import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.optim.lr_scheduler as sched import torch.utils.data as torchdata ...
exp-x/exp3_train.py
MIT
9,091
03cce0894afae1d81db800d92c87e32094e88ce3
Python
py
import torch import torch.nn as nn from torch import optim from multiprocessing import cpu_count import numpy as np import argparse import os import time from networks import LightSpeech from dataset import DataLoader, collate_fn from dataset import LightSpeechDataset from loss import LigthSpeechLoss import utils impo...
train.py
MIT
7,034
42041606268ad302f087868f48ad7bc5cdd816ba
Python
py
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
transfer_model/__main__.py
Xnet,X11,RSA-MD
3,227
d72d7164825aa591bd47096b978490df721d40bc
Python
py
from collections import defaultdict from functools import partial import logging import os import zipfile import gzip from urllib.request import urlretrieve import torch from tqdm import tqdm import tarfile from .utils import reporthook from collections import Counter logger = logging.getLogger(__name__) class Vo...
torchtext/vocab.py
BSD-3-Clause
22,463
3a03317b6931071b90bfbfd4e4061939a46ef6a0
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 class DoubleMnist: def __init__(self, loader, label_mapping): self.loader = loader self.label_mapping = label...
lib/EGG_research/egg/zoo/language_bottleneck/mnist_classification/data.py
MIT
3,937
28cd5a439c1b7a4bf42787cceecfd34f964888a1
Python
py
import numpy as np import cv2 import torch import sys sys.path.append('..') import src.oflibpytorch as of from src.oflibpytorch.utils import to_numpy, to_tensor, show_masked_image # # # # Usage / Visualisation # shape = (601, 601) # flow = of.Flow.from_transforms([['rotation', 601, 601, -30]], shape) # flow_def = of....
docs/doc_code.py
MIT
16,116
3a036e3e2268de948ccd5cd3caa23d801bfb1f12
Python
py
import math import time import numpy import ray import torch import models #import asyncio import time @ray.remote class SelfPlay: """ Class which run in a dedicated thread to play games and save them to the replay-buffer. """ def __init__(self, initial_checkpoint, Game, config, s...
self_play.py
MIT
18,571
4bc41a402bf659aaf007ab766d8ee7205feb4c97
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. # # 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 ...
eval_linear.py
Apache-2.0
13,339
5e465c1dd4af2f2e28b5c3adf536306d919b7a86
Python
py
# Copyright (c) 2020 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/data_structures.py
Apache-2.0
17,069
f94c92c92f87db77e48f986b5291fcc3a8621bb4
Python
py
import os import torch import numpy as np import json import h5py __all__ = ['Checkpoint', 'RemoveCOMMotion', 'BiasPotential', 'FileLogger', 'TensorboardLogger', 'TemperatureLogger', 'MoleculeStream', 'PropertyStream'] class SimulationHook: """ Basic class for simulator hooks """ ...
src/schnetpack/simulate/hooks.py
MIT
13,448
3a03f0a9d45de3e95b9e81c3730fc1d5a8daad73
Python
py
# -*- coding: utf8 -*- # Copyright 2019 JSALT2019 Distant Supervision 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...
fairseq/data/handwriting/aligner.py
MIT
126,392
3a03f994ae06997794ab27fdc15e1904e5b2dcaa
Python
py
import pytest import torch import numpy as np from bgflow import XTBEnergy, XTBBridge try: import xtb xtb_imported = True except ImportError: xtb_imported = False pytestmark = pytest.mark.skipif(not xtb_imported, reason="Test requires XTB") @pytest.mark.parametrize("pos_shape", [(1, 3, 3), (1, 9)]) def ...
tests/distribution/energy/test_xtb.py
MIT
2,495
3a03fb2091ad2f4baac62be920ed328b1c28a7c1
Python
py
# train.py import os import pandas as pd import albumentations import torch from sklearn import metrics from sklearn.model_selection import train_test_split import dataset import engine from model import get_model if __name__ == "__main__": data_path = "../input_image/" device = "cuda" epochs = 10 ...
Image_Problem/Classification/src/train.py
MIT
2,019
34176fe079d0064f465bd6b86e727ee9e43a6323
Python
py
# Copyright 2021 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/accelerate/data_loader.py
Apache-2.0
19,589
24a7ad08af431fdc7cc492e6f7e7c438b7c9629b
Python
py
import time from torch.utils.data import DataLoader, Dataset from torch.optim import lr_scheduler from modelZoo.K_FPN import load_preTrained_model import torch.nn as nn from modelZoo.DyanOF import creatRealDictionary from modelZoo.K_FPN import keyframeProposalNet from utils import * from JHMDB_dloader import * import s...
test_jhmdb.py
MIT
5,731
3a0403c047095f2e40cb73f209def893f63b29d5
Python
py
# Copyright Ping Luo and Jiamin Ren and Zhanglin Peng and Ruimao Zhang and Jingyu Li # This file was taken from the SwitchNorm repository at # https://github.com/switchablenorms/Switchable-Normalization/blob/5472286952ba5519a7d3229d9ad899a5c1b2e5b1/devkit/ops/switchable_norm.py # by Ping Luo and Jiamin Ren and Zhangli...
c_unet/utils/normalization/SwitchNorm3d.py
MIT
3,943
3a040d081e6f79ba5ff57856fab66d42aa2de089
Python
py
from collections import namedtuple import torch AttrTensor_ = namedtuple('AttrTensor', ['data', 'lengths', 'word_probs', 'pc']) class AttrTensor(AttrTensor_): """A wrapper around the batch tensor for a specific attribute. The purpose of having a wrapper around the tensor is to include attribute specific ...
deepmatcher/batch.py
BSD-3-Clause
4,255
3a0416951f2a7d5b9be5eac182fc33297d12da17
Python
py
import os import argparse import torch import numpy as np import PIL.Image as Image import torchvision.models as models from torch import nn from tqdm import tqdm import torchvision.datasets as datasets import torch.utils.data as data from torch.utils.data import Dataset from torch.utils.data import DataLoader from to...
inference.py
MIT
3,671
28fe002505ece2724f60bc0ac5ce64d98d207c35
Python
py
import datetime import os import time import torch import torch.utils.data import transforms as T from torch import nn import torchvision import numpy as np import scipy.io import random from PIL import Image import matplotlib.image as mpimg from tqdm import tqdm from coco_utils import get_coco import presets import ut...
semseg/multimodel_train.py
MIT
25,192
1e2b7172b7c6b44b2333421db842ebd9029e089b
Python
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Copyright (c) 2019, Linear Labs Technologies 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...
BLOX/DataSet/DataSet.py
Apache-2.0
5,057
ff7fbeeb27176867e5317aed286f027f9e3ece30
Python
py
import torch import torch.nn as nn from torch.distributions.normal import Normal class Flow1d(nn.Module): def __init__(self, n_components): super(Flow1d, self).__init__() self.mus = nn.Parameter(torch.randn(n_components), requires_grad=True) self.log_sigmas = nn.Parameter(torch.zeros(n_com...
1d/model.py
MIT
771
fcfd02f55e35d0081d961e1c741c60e6cebbe72e
Python
py
import numpy as np import torch import torch.utils.data as data import torchvision import torchvision.transforms as transforms from PIL import Image, ImageFile from random import random from os.path import join, dirname from data.dataset_utils import * import pandas as pd import os Image.LOAD_TRUNCATED_IMAGE...
data/fgdr_dataset.py
MIT
5,018
1077e2a792eef8b911992c4d7e9353fd9f74175d
Python
py
"""Classification and regression loss functions for object detection. Localization losses: * WeightedL2LocalizationLoss * WeightedSmoothL1LocalizationLoss Classification losses: * WeightedSigmoidClassificationLoss * WeightedSoftmaxClassificationLoss * BootstrappedSigmoidClassificationLoss """ from abc import ABC...
second/pytorch/core/losses.py
MIT
18,115
103574944a1703e5e9634de90536c0b5d6474e42
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. # # 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 ...
cfvpy/models.py
Apache-2.0
2,631
65064c67e02746c32e42cab1930723641f7eba8e
Python
py
import numpy as np import torch def mask(shape, lengths, dim=-1): assert dim != 0, 'Masking not available for batch dimension' assert len(lengths) == shape[0], 'Lengths must contain as many elements as there are items in the batch' lengths = torch.as_tensor(lengths) to_expand = [1] * (len(shape)-1)...
utils/functional.py
MIT
7,108
b2a9fcbaee3bcb14979405678026bdbfe9962062
Python
py
import os from tqdm.auto import tqdm from pathlib import Path from random import shuffle from math import isclose, ceil from itertools import combinations_with_replacement import gzip import pickle import numpy as np import pandas as pd import matplotlib.pyplot as plt import skimage.transform import torch import tor...
experiments/runs/mnist25-6-6-6-5relu/run3.py
MIT
9,383
3a04bbf5da32cc59714519e51ba40965efaf023e
Python
py
# coding=utf-8 # Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and 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.or...
transformers/modeling_distilbert.py
MIT
39,828
7098529c9ea0299efceb77a70bd767020a1f3241
Python
py
# ======================================================== # CONFIDENTIAL - Under development # ======================================================== # Author: Kaicheng Yu with email kaicheng.yu@epfl.ch # All Rights Reserved. # Last modified: 2019/11/21 下午1:44 # NOTICE: All information contained herein is, a...
nasws/operations/elastic_utils.py
MIT
4,482
3a04d60c28e0ec10eeca3a1d6a3ae303ae644d67
Python
py
import torch from codebase.utils.cluster.management.basic_dial_batching import ImagePathFolder, BasicDialTrainBatchLoader, \ list_collate_batcher class MixedDomainTrainBatchLoader(BasicDialTrainBatchLoader): ''' Batch loader that produces batches with images sampled from all domains ''' def __in...
codebase/utils/cluster/management/mixed_domain_batching.py
MIT
4,060
12954c01f1aace6c1a214c2a6159a6a3ce6d456b
Python
py
import torch from sklearn.metrics import ( accuracy_score, precision_score, recall_score, f1_score, roc_auc_score ) class BinaryBase: def __init__(self, threshold=0.5, use_sigmoid=True): self.threshold = threshold self.use_sigmoid = use_sigmoid def __call__(self, preds, target...
cv_utils/image_classification/metrics/binary.py
MIT
1,799
d7bfa18c700a1f96e27bbbc9dff3fc58412cea37
Python
py
from __future__ import print_function from PIL import Image, ImageFilter import os import os.path import numpy as np import sys if sys.version_info[0] == 2: import cPickle as pickle else: import pickle from torchvision.datasets.vision import VisionDataset from torchvision.datasets import DatasetFolder,ImageFo...
utils/imagenet.py
BSD-3-Clause
10,807
3a04eeaa2a406190c9310e2a88115b59f073231d
Python
py
import torch import requests import sys import os import logging import torchvision.transforms as T import torch.nn as nn import numpy as np from torch import nn from dataclasses import dataclass from functools import partial from typing import Dict from torch import Tensor from .ModuleTransfer import ModuleTransfer fr...
glasses/utils/PretrainedWeightsProvider.py
MIT
11,003
3a050361f70bc91e45a0b203fd827720829996ec
Python
py
import torch import pytorch_lightning as pl import wandb def get_trainer(cfg, engine): callbacks = list() callbacks.append(pl.callbacks.EarlyStopping(patience=cfg.training.early_stopping.stopping_patience, monitor=cfg.training.early_stopping.monitor)) callba...
project_1_2/src/trainer.py
MIT
1,448
5f170a4409021c27e785d20eca98422d9229f8aa
Python
py
from collections import namedtuple import cv2 import numpy as np import torch from aabb import AABB from coding import encode from utils import compute_scale_down, prob_true DataLoaderItem = namedtuple('DataLoaderItem', 'batch_imgs,batch_gt_maps,batch_aabbs') class DataLoaderIAM: """loader for IAM dataset""" ...
src/dataloader.py
MIT
6,182
3a05254b16a033819dabb2e41fef6a2d4b2104b7
Python
py
import math import torch import torch.nn as nn from torch.nn.parameter import Parameter from torch.nn.modules.module import Module import torch.nn.functional as F class GraphConvolution(Module): """ Simple GCN layer, similar to https://arxiv.org/abs/1609.02907 """ def __init__(self, in_features, out_f...
src/models/layers.py
MIT
7,015
3a053a3ecbe0bca64e85bc5f218eecbbaa4b63be
Python
py
from typing import Dict import torch from torch import dtype UNITS: Dict[str, int] = { "b": 1, "kb": 10 ** 3, "kib": 2 ** 10, "mb": 10 ** 6, "mib": 2 ** 20, "gb": 10 ** 9, "gib": 2 ** 30, "tb": 10 ** 4, "tib": 2 ** 40, } MEMORY_BYTES: Dict[dtype, int] = { torch.bool: 1, to...
koila/constants.py
MIT
598
3a053af792e72cd4fc74f011b50210e7d4541764
Python
py
import copy import unittest import numpy as np import torch from pytorch_adapt.adapters import SymNets from pytorch_adapt.containers import Models, Optimizers from pytorch_adapt.hooks import ( SymNetsCategoryLossHook, SymNetsDomainLossHook, SymNetsEntropyHook, SymNetsHook, validate_hook, ) from py...
tests/hooks/test_symnets.py
MIT
9,131
3a053f3dea09918b2e2402a5503e2886c9a0da99
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/parallel.py
Apache-2.0
5,316
3a05455b87990032acd52d982de0a21589c2943d
Python
py
import argparse import math import os import numpy as np import pandas as pd import torch from torch import nn from torch import optim from torch.autograd import Variable from torch.nn import functional as F from torch.utils.data import DataLoader from tqdm import tqdm from build_vocab import WordVocab from dataset i...
smiles_transformer/pretrain_trfm.py
MIT
7,351
3a054a91258abde1e38ce732d4f3ff90e448d809
Python
py
import torch from NeuralBlocks.trainers import Trainer from fastprogress import progress_bar from NeuralBlocks.trainers.ganloss import GANLoss from NeuralBlocks.trainers.logger import Logger class GANTrainer(Trainer): def __init__(self, G_model, D_model, dataloader, ...
trainers/gan_trainer.py
MIT
2,534
52bd8aaadf830738ae2d2c33710d7b0c2094875d
Python
py
import torch import torchvision import torchvision.transforms as transforms import torchvision.models as models import matplotlib.pyplot as plt import numpy as np import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import scipy.io as sio from scipy.stats import ks_2samp from scipy.stats im...
Perceptual_Optimization/compute_Perceptual_Differences.py
MIT
4,999
2487ecfab4e6c5453c2b1f24b119d3ff8233f603
Python
py
import os import sys from itertools import chain import numpy as np import pandas as pd import torchvision.models import torch.nn.functional as F import torch.optim as optim from torch import nn from torch.utils.data import DataLoader from torchsample.callbacks import CSVLogger, LearningRateScheduler from callbacks...
nn_semisupervised_densenet_169.py
MIT
6,367
fce710bcd67d71248db9e87e1f370df5a95a2749
Python
py
import torch class MCTSvisualiser: ''' Class that aims to visualize MCTS. It generates .gv file that describe the tree. Then dot from Graphviz can be used to transform the .gv file into a pdf file with the tree grpahical representation on it. ''' def __init__(self, env, indent = ' '): se...
visualization/visualise_mcts.py
MIT
5,552
3a057c94e0dee4072b33ad42851cd10b9c0c9ec2
Python
py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch import torch.nn.functional as F from pytext.config import ConfigBase from pytext.config.component import Component, ComponentType from pytext.utils import loss as loss_utils, precision from pytext.utils.cuda impo...
pytext/loss/loss.py
BSD-3-Clause
17,249
d7a925e527e38ba3519968e90a10c2c81bb4b486
Python
py
from nn import NN import random import numpy as np import torch class Game: def __init__(self, seed, n, K, K2, K3): self.n = n self.K = K self.K2 = K2 self.K3 = K3 self.seed = seed np.random.seed(seed) torch.manual_seed(seed) self.xhat = np.random.rand...
1l/nnGame.py
MIT
1,431
3a05d9a21e69b3b187245d208ef6b23b587fe679
Python
py
import torch import torch.nn as nn from torch.nn import init import functools from torch.optim import lr_scheduler ############################################################################### # Helper Functions ############################################################################### def get_norm_layer(norm...
networks/gan_networks.py
MIT
18,270
e93bfbc475b5ad75cb58dd0845ab04983d7cc6ae
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...
pretrain_gpt2.py
MIT
4,001
3a05e9ebd3f8d43d50ab028ef4d8e2066d67f9a2
Python
py
import random import math import os import numpy as np import sys from PIL import Image from utils import show from metrics import AEBatch, SEBatch import time import torch import scipy.io as scio class Estimator(object): def __init__(self, setting, eval_loader, criterion=torch.nn.MSELoss(reduction="sum")): ...
eval/Estimator.py
MIT
3,848
fdfb57ee4a7b10a82b16fa818dcf93084714285c
Python
py
from .common import * from torch.utils.data import DataLoader, Dataset import torch import random class GabProcessor(DataProcessor): """ Data processor using DataProcessor class provided by BERT """ def __init__(self, configs, tokenizer=None): super().__init__() self.data_dir = configs....
loader/gab.py
MIT
4,905
ffb64a8538a24d5a4a41edb4b715869a25557ad3
Python
py
import fastai from fastai.vision import * from fastai.callbacks import * from fastai.utils.mem import * from torchvision.models import vgg16_bn from glob import glob import os import sys from PIL import Image import nibabel as nib def ensure_dir(file_path): """ if the directory doesn't exist in the path given, t...
src/file_converter.py
MIT
4,891
e9300c0e1e7e7493d28de2a5ae6c9d985c51212e
Python
py
import torch import torch.nn as nn from torch.nn import functional as F from .retrieve import SEG_MODELS_REGISTRY def conv3x3(in_planes, out_planes, stride=1): return nn.Conv2d( in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False ) class Bottleneck(nn.Module): expansion =...
realtime_hand_3d/segmentation/models/pspnet.py
MIT
9,778
429f8b50d30b1d5343ba6ecf5b69449453f88e44
Python
py
import argparse import json import os from catalyst import dl from catalyst.dl import utils from catalyst.contrib.dl.callbacks.neptune_logger import NeptuneLogger import numpy as np import pandas as pd from pathlib import Path from sklearn.metrics import mean_squared_error from sklearn.model_selection import Stratifie...
nn_trainer.py
MIT
6,909
fcac9c7951ed185568080142121e5940713af0b1
Python
py
# from:https://github.com/ildoonet/pytorch-gradual-warmup-lr from torch.optim.lr_scheduler import _LRScheduler from torch.optim.lr_scheduler import ReduceLROnPlateau class GradualWarmupScheduler(_LRScheduler): """ Gradually warm-up(increasing) learning rate in optimizer. Proposed in 'Accurate, Large Minibatch ...
torchreid/optim/warm_up.py
MIT
3,075
3a064f1f095bbe67edfbd3d2447f42c396eb6328
Python
py
""" run.py Written by Eirik Vesterkjær, 2019 Apache License Entry point for training or testing ESRDGAN Sets up environment/logging, and starts training/testing Usage: python run.py < --train | --test | --use > [ --cfg path/to/config.ini ] [ -h ] """ import argparse import logging import os import time import t...
src/run.py
Apache-2.0
6,116
3a0650f12aaf3e1b3e20c62bc9e8cb77c49c1f20
Python
py
import torch # device on which to train DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') # train size VAL_SIZE = 0.2 # embedding sizes EMB_DIMS = 5 # number of epochs for Training: N_EPOCHS = 24 # start learning rate START_LR = 0.001 # start learning rate END_LR = 0.001 # start learning ra...
config.py
MIT
336
3a0668e398fd6d15409df0e4f4b434919771b4e2
Python
py
import scipy.special import torch # Using exp(-x)I_v(k) for numerical stability (vanishes in ratios) class ModifiedBesselFn(torch.autograd.Function): @staticmethod def forward(self, nu, inp): self._nu = nu self.save_for_backward(inp) inp_cpu = inp.data.cpu().numpy() return tor...
src/pythae/models/svae/svae_utils.py
Apache-2.0
611
3a06781e682fa81e8b5bae59532756701c83e14f
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/models/language_modeling/megatron_finetune_model.py
Apache-2.0
25,964
65447d2c7966bf6ca168d2f652c91bb665380162
Python
py
import os from copy import deepcopy import pytest import torch from torch.optim import SGD, Adadelta, Adagrad, Adam, RMSprop from pythae.customexception import BadInheritanceError from pythae.models.base.base_utils import ModelOutput from pythae.models import WAE_MMD, WAE_MMD_Config from pythae.trainers import BaseT...
tests/test_WAE_MMD.py
Apache-2.0
20,993
5f74ad88918954f448ebce8ee0b5f783031f126b
Python
py
import torch import torch.nn as nn from utils.config import * from models.BertEncoder import BertEncoder from models.GraphMemory import GraphMemory from models.VisualMemory import VisualMemory from models.Decoder import Decoder from models.ContextRNN import ContextRNN from models.ImageEncoder import ImageEncoder from m...
s2s-ft/multimodalKB/models/MultimodalKB_GlobalLocal.py
MIT
24,623
3a069e7c8bc4641f98e36c5b017f8115de5f0dcd
Python
py
# coding=utf-8 # Copyright (c) 2019, 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...
src/models/GPT_3/generate/generate_qa_desc_refined.py
MIT
24,971
3a06a7ce2c512d7f913717a43659e63670935c39
Python
py
# Copyright 2021 MosaicML. All Rights Reserved. """Logs metrics to dictionary objects that persist in memory throughout training. Useful for collecting and plotting data inside notebooks. """ from __future__ import annotations import copy from typing import Any, Dict, List, Tuple, Union import numpy as np from tor...
composer/loggers/in_memory_logger.py
Apache-2.0
5,785
e9c9febcd3e23a80eaad0327faf28f2d7aa84225
Python
py
from torch import nn from transformers import AutoModel, AutoTokenizer, AutoConfig, T5Config import json from typing import List, Dict, Optional, Union, Tuple import os class Transformer(nn.Module): """Huggingface AutoModel to generate token embeddings. Loads the correct class, e.g. BERT / RoBERTa etc. :...
sentence_transformers/models/Transformer.py
Apache-2.0
6,683
654516f9d6a2ee0ca8b1738a1fdabbe78452f954
Python
py
import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from mushroom_rl.algorithms.value import DQN from mushroom_rl.core import Core from mushroom_rl.environments import * from mushroom_rl.policy import EpsGreedy from mushroom_rl.approximators.parametric.torch_approximator import * from mus...
examples/acrobot_dqn.py
MIT
3,854
3a06ca720fced1cdc06da91cdbc337003bba52f3
Python
py
import torch from torch.optim.optimizer import Optimizer, required from torch.autograd import Variable import torch.nn.functional as F from torch import nn from torch import Tensor from torch.nn import Parameter def l2normalize(v, eps=1e-12): return v / (v.norm() + eps) class SpectralNorm(nn.Module): def __...
spectral_normalization.py
MIT
2,277
3a06e863ad69658984edc25e3a2ae2072b854bca
Python
py
import torch import pytest import torchaudio from fastai.basic_data import Path from audio import AudioConfig, AudioDataBunch, AudioList, audio_learner from audio.learner import audio_predict from audio.util import create_sin_wave import pytest @pytest.fixture(scope='session') def audio_db(): sig, sr = create_...
tests/test_prediction.py
MIT
1,166
3a06ec03d173e5cf7535c07bc6c0b9e45c460700
Python
py
# Copyright (c) 2020 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/dynamic_action_repeat_agent.py
Apache-2.0
15,477
3a06ec55eb04e33dadca343b9311815e6a7b4c89
Python
py
#!/usr/bin/env python3 import logging import os import tempfile import unittest import numpy as np import onnx import torch from caffe2.python.onnx import backend as caffe2_backend from fairseq import models from pytorch_translate import char_source_hybrid # noqa from pytorch_translate import char_source_model # no...
pytorch_translate/test/test_onnx.py
BSD-3-Clause
21,189
b2eb0c210dfab1e25d9211c9052d39fabffbb317
Python
py
import torch import torch_geometric from torch import nn from torch.nn import functional as F from torch_geometric.nn import MessagePassing, global_sort_pool from torch_geometric.utils import add_self_loops, degree class DGCNN(nn.Module): """ Uses fixed architecture """ def __init__(self, dim_feature...
gnn-comparison/models/graph_classifiers/DGCNN.py
MIT
5,157
fce566de3400b7a7442011f779897cbac8268f0c
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from .box_head.box_head import build_roi_box_head from .mask_head.mask_head import build_roi_mask_head from .keypoint_head.keypoint_head import build_roi_keypoint_head from .ke_head.ke_head import build_roi_ke_head class CombinedROIH...
maskrcnn_benchmark/modeling/roi_heads/roi_heads.py
BSD-2-Clause
4,199
3a07252f0c23586e1ea39598ab4204ec4b156f82
Python
py
# from __future__ import print_function import os,sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0,parentdir) from rich import print from rich import pretty pretty.install() from rich import traceback traceback.i...
train_script/train_on_single_KITTI2015val.py
MIT
12,034
3a0730617f9ebbc1200705b5ff0ea34c88dd1f63
Python
py
import numpy as np import torch.nn as nn import torch from base_layer import BaseLayer import os import pickle class GeneratorLossPathReg(BaseLayer): def __init__(self, pl_decay=0.01, pl_weight=2.0, opt=None): super(GeneratorLossPathReg, self).__init__() self.pl_decay = pl_decay self.pl_wei...
chapter7/stylegan2_pytorch/generator_loss_pathreg.py
MIT
1,668
3a07325533035867afe9d2d24dd47ad13c8c1a55
Python
py
# Copyright 2021 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 agreed to in writing, ...
third_party/rlkit_library/rlkit/core/logging.py
Apache-2.0
12,103
5f8011dfb2929c0cfd11194f67950cde60ed606a
Python
py
import numpy as np import scipy.signal import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions.normal import Normal from torch.distributions.utils import _standard_normal, broadcast_all from torch.distributions.exp_family import ExponentialFamily from numbers import Number from torc...
spinup/algos/pytorch/mbfq/core.py
MIT
17,230
ff615304c0a196254799e59fc746ef3695a54be3
Python
py
from pathlib import Path import tqdm import torch import numpy as np from cherry.envs import build_env from cherry.agents import get_model, build_agent from utils.helpers import add_verbosity_parser, read_yaml, copy_yaml, \ get_repo_hexsha, validate_config, get_logger, write_model class Trainer: def __init__...
cherry/runner/trainer.py
MIT
2,349
3a0757c6ad35e8a32a663682154ff4d9ce9e6a1a
Python
py
import torch import torch.nn as nn class KeyPointModel(nn.Module): def __init__(self): super(KeyPointModel, self).__init__() self.conv1 = nn.Conv2d(3, 6, 3, 1, 1) self.bn1 = nn.BatchNorm2d(6) self.relu1 = nn.ReLU(True) self.maxpool1 = nn.MaxPool2d((2, 2)) self.conv...
simple_keypoint/regression/model.py
Apache-2.0
1,356
700068b711cddb7b31b7a6f768a77efc02502e6a
Python
py
import os import random import torch import imageio import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from mpl_toolkits.mplot3d import Axes3D from pytorch3d.io import load_obj from pytorch3d.structures import Meshes, Textures from pytorch3d.re...
utils.py
MIT
4,123
3a07737c05f084e5bae9bb8f327299d596c38f86
Python
py
# code for training the LinearUNet model import torch import numpy as np from learning.learning import Trainer from utils.smooth_scaler import * #from qso_fitting.models.utils import QuasarScaler from utils.QuasarScaler import QuasarScaler from torch.utils.data import DataLoader from utils.errorfuncs import WavWeights ...
learning/learning_unet.py
BSD-3-Clause
21,799
3a0789d63b60232a3d721e6d4391e67972acaa6c
Python
py
import os from typing import Dict, List, Tuple import gym import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from net.replay import ReplayBuffer from net.utils import initial_seed from net.noise import NoisyLinear initial_...
5_noise.py
MIT
7,584
4b6e7faee1848aa872880cda9dbe4e5227fe0793
Python
py
import torch.nn as nn import torch import math def conv_bn(inp, oup, stride): return nn.Sequential( nn.Conv2d(inp, oup, 3, stride, 1, bias=False), nn.BatchNorm2d(oup), nn.ReLU6(inplace=True) ) def conv_1x1_bn(inp, oup): return nn.Sequential( nn.Conv2d(inp, oup, 1, 1, 0, b...
online_demo/mobilenet_v2_tsm.py
Apache-2.0
6,912
1e3f468e8bb8dfe1e89fcd336d30095a15be6ee0
Python
py
from pytorch_lightning.callbacks.gpu_stats_monitor import GPUStatsMonitor from pytorch_lightning.utilities import rank_zero_warn class GpuUsageLogger(GPUStatsMonitor): def __init__(self, *args, **kwargs): rank_zero_warn("`GpuUsageLogger is now `GPUStatsMonitor`" " and it will be rem...
pytorch_lightning/callbacks/gpu_usage_logger.py
Apache-2.0
400
3a0793887f7ab1445c15b8a9d056d32b0e1649d4
Python
py
import torch from transformers import AdamW from utils.data import MyDataset from model import * from tqdm import tqdm import os Batch_size=16 model_name="hfl/chinese-xlnet-base" #device=torch.device("cpu") device=torch.device("cuda:0" if torch.cuda.is_available() else "cpu") best_accuracy = 0.0 #set random seed def s...
BERT_BiLSTM/main.py
MIT
4,100
3a07950e6b24710a37871e7bae7ec9ca6b8ca7f5
Python
py
r"""Functional interface""" import warnings import math import numpy as np import torch import torch.nn.functional as F from torch.nn import ParameterList from ..utils.signaltools import resample # from torch._C import _infer_size, _add_docstr # from torch.nn import _reduction as _Reduction # from torch.nn.modules imp...
torchcomplex/nn/functional.py
MIT
18,614
3a079789b72ab2451554952a951799f94ca2b778
Python
py
import torch # import torch.nn as nn import argparse # import torch.optim as optim import torch.backends.cudnn as cudnn from torch.utils.data import DataLoader from torch.autograd import Variable import os import time import random from utils.dataset import HyperDatasetValid, HyperDatasetTrain # Clean Data set from mo...
main.py
Apache-2.0
16,087
7c94b2d787fd45b41d27ca373bbfd514937caa14
Python
py