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
""" 3D scattering quantum chemistry regression ========================================== Description: This example trains a classifier combined with a scattering transform to regress molecular atomization energies on the QM7 dataset. Here, we use full charges, valence charges and core charges. A linear regression is ...
examples/3d/scattering3d_qm7_torch.py
BSD-3-Clause
12,151
b2879021de266c5187da107df991a793f2b865be
Python
py
import sys import random import numpy as np import torch import torch.nn.functional as F # digit_text = ['null', 'eins', 'zwei', 'drei', 'vier', 'fuenf', 'sechs', 'sieben', 'acht', 'neun']; digit_text_german = ['null', 'eins', 'zwei', 'drei', 'vier', 'fuenf', 'sechs', 'sieben', 'acht', 'neun']; digit_text_english = [...
utils/text.py
MIT
1,557
3a706d6823444c0558c5336ef05fde606a670b5b
Python
py
from __future__ import print_function import numpy as np import torch import torch.nn as nn from config import * from torch.nn.utils.weight_norm import weight_norm import torch.nn.functional as F from torch.autograd import Variable from torch.distributions.categorical import Categorical class QuestionParser(nn.Module...
model.py
MIT
17,079
429d429a31efbb9cdd79f7c244e7164044add530
Python
py
# coding=utf-8 # Copyright 2021 Google AI 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.apache.org/licenses/LICENSE-2.0 # ...
src/transformers/models/canine/modeling_canine.py
Apache-2.0
70,017
3a707ff05a2e4796303a97699e0c921a1791fc62
Python
py
import json import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.nn._functions.packing import PackPadded from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence, PackedSequence from utils import to_gpu class ML...
yelp/models.py
BSD-3-Clause
21,906
3a7085a70b48508ecffcf14a6e25282455a9bb36
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. import gc import unittest import tests.test_utils as test_utils import torch from mmf.common.sample import SampleList from mmf.models.mmf_transformer import MMFTransformer, MMFTransformerModalityConfig from mmf.modules.encoders import ( EncoderFactory, Identi...
tests/models/test_mmf_transformer.py
BSD-3-Clause
16,774
f94b8b8001291db8c0cfa61f6a01e7df90776b1b
Python
py
import torch import torch.nn.functional as F from mmcv.cnn import xavier_init from mmdet.models.builder import NECKS from torch import nn class UpBlock(nn.Module): """Upsample block for DRRG and TextSnake.""" def __init__(self, in_channels, out_channels): super().__init__() assert isinstance...
mmocr/models/textdet/necks/fpn_unet.py
Apache-2.0
2,839
3a709be9225c1a1cd982991d1d7d5906f86c79f4
Python
py
import argparse import time import numpy as np import networkx as nx import torch import torch.nn as nn import torch.nn.functional as F # self-defined from datasets import load_mouse_mammary_gland, load_tissue from models import GraphSAGE class Trainer: def __init__(self, params): self.params = params ...
out/production/cci/train.py
MIT
3,996
3a709f03bade296a28c44639e3f7b66fb2e5dec8
Python
py
import torch.utils.data as data import os import sys import random import numpy as np import cv2 from PIL import Image import random from .utils import RandomResampler, SymmetricalResampler, SymmetricalSequentialResampler cv2_loader = True cv2.setNumThreads(0) #fix the opencv resize stuck issue def pil_loader(ro...
BERT/datasets/covid.py
MIT
19,405
7cfbfebd732da5cade9a380feac28d96aeaf4928
Python
py
import torch import random import numpy as np from cogdl.tasks import build_task from cogdl.datasets import build_dataset from cogdl.models import build_model from cogdl.utils import build_args_from_dict def get_default_args(): cuda_available = torch.cuda.is_available() args = { "dataset": "cora", ...
tests/models/ssl/test_generative_models.py
MIT
4,971
3a70c16df35b26166b918ef2219e3d695dfe37dd
Python
py
#!/usr/bin/env python import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.autograd import Variable from tensorboardX import SummaryWriter import argparse, os, sys, subprocess import setproctitle, colorama import numpy as np from tqdm import tqdm from glob import glob from os.path imp...
zmf_main_py37.py
Apache-2.0
23,398
1079ab8a2062dbcbba9d5cd05eabbdfdd77dde04
Python
py
from torch.nn import Module, ModuleList from torch.nn.functional import relu from modeling.modules import PretrainedEmbeddingLayer, MLP, CellLayer, SequentialModel, AttendedState import torch from modeling.activation_factory import ActivationFactory class MultiAttentionRNN(Module): def __init__(self, embeddings, ...
emotions/semeval2018/modeling/multi_attention_rnn.py
Apache-2.0
2,225
d7dd67875053219268cad4d91b33afcc6a64f8f5
Python
py
# -*- coding: utf-8 -*- """ @author: Abderrahmen Amich @email: aamich@umich.edu """ import torch import torchvision import torchvision.transforms as transforms import torch.nn as nn import torch.nn.functional as F from easydict import EasyDict def get_transform(): ''' @return: torch transforms to use in CI...
cifar.py
MIT
4,135
7cc760cdd6adeeedd9b625a3ffdad77ff129ff5f
Python
py
import pytest import kornia as kornia import kornia.testing as utils # test utils import torch from torch.testing import assert_allclose from torch.autograd import gradcheck class TestPyrUp: def test_shape(self): inp = torch.zeros(1, 2, 4, 4) pyr = kornia.geometry.PyrUp() assert pyr(inp...
test/geometry/transform/test_pyramid.py
Apache-2.0
4,471
3a71083bad5646637dcb327197164217fc196eda
Python
py
import numpy as np import pickle as pkl import networkx as nx import scipy.sparse as sp from scipy.sparse.linalg.eigen.arpack import eigsh import sys import torch import torch.nn as nn def parse_skipgram(fname): with open(fname) as f: toks = list(f.read().split()) nb_nodes = int(toks[0]) nb_feature...
utils/process.py
MIT
7,425
cc07ad2835fab5fd8ca41185f13e09175cf772ea
Python
py
# Copyright (c) 2019-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 required by a...
kaolin/ops/gcn.py
ECL-2.0,Apache-2.0
7,593
d7bfcca3638f7e1a93bb9710d02bf722b107654a
Python
py
import torch from build_model import build_fairmot, load_model with torch.no_grad(): input_data = torch.randn(1, 3, 608, 1088, dtype=torch.float32, device='cuda') net = build_fairmot() model = load_model(net, "../../weights/fairmot_dla34.pth") model = model.to(torch.device('cuda')) model.eval() ...
Software/trt_impl/build_onnx_engine.py
MIT
914
5e8507091cef65f5af7208c160c6fc2beeeacc24
Python
py
import csv from logging import Logger import os import sys from typing import List import numpy as np from tensorboardX import SummaryWriter import torch from tqdm import trange import pickle from torch.optim.lr_scheduler import ExponentialLR from .evaluate import evaluate, evaluate_predictions from .predict import p...
chemprop/train/run_training.py
MIT
10,907
7cc04c9d71e66c51e05eac1884a3f1eef9134108
Python
py
import re import numpy as np import os import torch import openpyxl from dpsniper.classifiers.feature_transformer import FlagsFeatureTransformer from dpsniper.attack.ml_attack import MlAttack from dpsniper.classifiers.torch_optimizer_factory import AdamOptimizerFactory, SGDOptimizerFactory from dpsniper.classifiers.c...
dpsniperOutSample/run.py
MIT
7,173
3a71274b6cd1b5793963671146cfccb5c1412873
Python
py
from _collections import OrderedDict from pytracking.tracker.transt.config import cfg import cv2 import numpy as np import torch class BaseTracker: """Base class for all trackers.""" def __init__(self, params): self.params = params self.visdom = None def predicts_segmentation_mask(self):...
TransT-fusion/pytracking/tracker/base/basetracker.py
MIT
3,574
10dd28332a721025ce5e05a8323eafd31e878c02
Python
py
#!/usr/bin/env python3 """This is an example to train a task with DDPG algorithm written in PyTorch. Here it creates a gym environment InvertedDoublePendulum. And uses a DDPG with 1M steps. """ import gym import torch from torch.nn import functional as F from garage import wrap_experiment from garage.envs import Gar...
examples/torch/ddpg_pendulum.py
MIT
2,533
3a71479bf64fb1f8593dc4ca22ab502275d06993
Python
py
# Copyright 2020 The OATomobile 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 applica...
oatomobile/datasets/carla.py
Apache-2.0
29,235
3a714810a73ad152628ad891988a5d5d656e1eb1
Python
py
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping from pytorch_lightning.profiler import SimpleProfiler from pytorch_lightning.loggers import WandbLogger import pytorch_lightning as pl from typing import List import utils.callbacks import importlib import os def init_lit_model(hparams: dict) -> p...
project/utils/init_utils.py
MIT
6,494
d74ec8c7f5c6a127f52677632b5fe34c4cf591d3
Python
py
# Copyright (c) 2020-2021 impersonator.org authors (Wen Liu and Zhixin Piao). All rights reserved. import unittest import torch from easydict import EasyDict from iPERCore.services.options.options_setup import setup from iPERCore.tools.trainers.lwg_trainer import LWGTrainer class TrainerTestCase(unittest.TestCase):...
tests/test_trainers/test_lwg_trainer.py
Apache-2.0
927
3a7153436ae67662dec67ed19869b8b6f3935f7f
Python
py
# author: Vinit Sarode (vinitsarode5@gmail.com) 03/23/2020 import open3d as o3d import argparse import os import sys import logging import numpy import numpy as np import torch import torch.utils.data import torchvision from torch.utils.data import DataLoader from tensorboardX import SummaryWriter from tqdm import tqd...
examples/test_pcn.py
MIT
4,342
3a7154c9317954917387be6e20044d09cddfe9e7
Python
py
from __future__ import print_function, division import os from PIL import Image import numpy as np from torch.utils.data import Dataset from myinfo import Path from torchvision import transforms from dataloaders import custom_transforms as tr class VOCSegmentation(Dataset): """ PascalVoc dataset """ NU...
dataloaders/datasets/pascal.py
MIT
4,492
fcb0af646f5cda293a4102fda553e3708e5379b5
Python
py
""" Copyright (c) 2019-2020 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 w...
examples/classification/main.py
Apache-2.0
21,464
fd8790a82bd5bfd7b5db5c2e44ee46d62cd28b33
Python
py
# Owner(s): ["oncall: distributed"] import itertools import math import sys from copy import deepcopy import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import CPUOffload from torch.distributed.fsdp import FlatParameter from torch.distributed.fsdp import FullyShardedDa...
test/distributed/fsdp/test_fsdp_summon_full_params.py
Intel
17,330
b288c567947aa5bf70287cfabd991ab2829604cf
Python
py
# camera-ready from datasets import ToyDatasetEvalKL # (this needs to be imported before torch, because cv2 needs to be imported before torch for some reason) from model import ToyNet import torch import torch.utils.data import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import numpy a...
1dregression/1/mlmcmcL16_eval.py
MIT
3,199
802c80b8dfd74f269e82679f5e631fdad3df0037
Python
py
import torch import torch.fx from torch import nn, Tensor from .utils import _log_api_usage_once def stochastic_depth(input: Tensor, p: float, mode: str, training: bool = True) -> Tensor: """ Implements the Stochastic Depth from `"Deep Networks with Stochastic Depth" <https://arxiv.org/abs/1603.09382>`_ ...
network/stochastic_depth.py
BSD-3-Clause
2,232
e9e00c6908773d9f6dbd07111ec1c1e5e72b4863
Python
py
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
test/torch/distribution/test_torch_isqf.py
Apache-2.0
8,781
3a71894072e203ec378232b8b7d84b9cb96f741a
Python
py
# Uncomment to run tests locally # import sys # import os # sys.path = [os.getcwd()] + sys.path import torch import numpy as np from sklearn.ensemble import ExtraTreesRegressor import itertools import mushroom_rl from mushroom_rl.environments.environment import MDPInfo from mushroom_rl.policy.td_policy import TDPolic...
tests/algorithms/helper/utils.py
MIT
15,243
10538f1d9e5664c5041844b332b40c7b8641ef7f
Python
py
import tqdm from torchvision.utils import save_image from datasets import inverse_data_transform from evaluation.fid_score import get_fid, get_fid_stats_path from .abc_runner import * from .sample_runner import * __all__ = ['FidRunner'] class FidRunner(SampleRunner): @torch.no_grad() def run(self): ...
runners/fid_runner.py
MIT
3,210
1023a07e2660f251ba03f050cafb2560fd0a912d
Python
py
import torch import torch.nn as nn import torch.nn.functional as F class HMN(nn.Module): def __init__(self,pooling_size,dim): super(HMN,self).__init__() self.dim=dim self.pooling_size=pooling_size self.maxout2=nn...
maxout_and_experts.py
MIT
2,477
7074b483b2804fc2f04b87cdf5fe18428d3bf800
Python
py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain ...
src/transformers/models/megatron_bert/modeling_megatron_bert.py
Apache-2.0
79,206
3a71c0b956ef958781097d56bae227d126674b5a
Python
py
# Copyright 2019 The Texar 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 ...
texar/torch/modules/pretrained/xlnet_utils.py
Apache-2.0
14,306
7cb071088b5238e6f63e60e59361597b309212b7
Python
py
import functools import torch.nn as nn from csrank.modules.object_mapping import DenseNeuralNetwork from csrank.modules.scoring.feta import FETAScoring from csrank.objectranking.object_ranker import SkorchObjectRanker from csrank.rank_losses import HingedRankLoss class FETAObjectRanker(SkorchObjectRanker): """A...
csrank/objectranking/feta_object_ranker.py
Apache-2.0
2,767
10de5469b79e38acacdb28fa68e5653456f57384
Python
py
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 import torch from torch.distributions import Transform, constraints from pyro.distributions.conditional import ConditionalTransformModule from pyro.distributions.torch_transform import TransformModule from pyro.distributions.util impo...
pyro/distributions/transforms/generalized_channel_permute.py
Apache-2.0
11,422
a91eaaa78390c6435d0bda83257de98ce6241b7c
Python
py
import os import torch import numpy as np import torch.nn as nn from torch.autograd import Variable from commons.utils import run_lstm, seq_conditional_weighted_num, SIZE_CHECK from models.syntaxsql.net_utils import to_batch_seq class KeyWordPredictor(nn.Module): '''Predict if the next token is (SQL key words): ...
models/syntaxsql/modules/keyword_predictor.py
MIT
6,987
5fa92e3419c68c003d746659e91c8105815d7ca6
Python
py
import numpy as np import torch from torch.utils.data import DataLoader, TensorDataset def generate_training_data(T=24): """ :param T: what is the T ? @Thomas :return: """ netDemandFull = 1e3 * np.loadtxt('netDemandFull.csv') # convert to KW netDemand = netDemandFull[76, :] # Pick a node with...
CaseStudy_Synthetic/processData.py
MIT
2,725
7c2da594ce216928447c9cb6fb37de4c2a27337b
Python
py
import os.path as osp from pytorch_lightning import LightningModule import torch import torch.nn as nn import torch_optimizer as optim import torchmetrics.functional as F from typing import List, Tuple, Union from kosmoss import CONFIG, DATA_PATH class ThreeDCorrectionModule(LightningModule): def __init__(se...
src/kosmoss/parallel/mlp.py
MIT
4,931
3a720bc0c6c0d5da9d4043630cfbcec7c93643d1
Python
py
import copy import glob import os import time import pdb from collections import deque import gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from a2c_ppo_acktr import algo from a2c_ppo_acktr.arguments import get_args from a2c_ppo_acktr.envs import...
main.py
MIT
12,409
ffb2457ff8eb24f6b1931bb8ece1f7b212c21db7
Python
py
import torch from torch.utils.data import DataLoader import torch.nn as nn import torch.nn.functional as F import pretrainedmodels import config from models import * class ModelInfo: def __init__(self, factory, pretrained_settings, args, batch_s...
wienerschnitzelgemeinschaft/src/Dmytro/src/experiments.py
MIT
24,920
3a7224f2948a91d84eef29676d17cacf09d7171c
Python
py
from typing import Dict, Optional import torch from torch import Tensor from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D from kornia.color import rgb_to_grayscale class RandomGrayscale(IntensityAugmentationBase2D): r"""Apply random transformation to Grayscale according to a probabi...
kornia/augmentation/_2d/intensity/grayscale.py
ECL-2.0,Apache-2.0
2,416
b22bae86b2a172039a1ba2e5e91e90a703e4bd98
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 ...
torchbeast/monobeast.py
Apache-2.0
22,325
4250a5af4c397dbde8c4fd45b5e780cf09b9f21d
Python
py
import logging import math import os import time import datetime import traceback from typing import Dict, Optional, List, Tuple, Union, Iterable, Any import torch import torch.optim.lr_scheduler from allennlp.common import Params from allennlp.common.checks import ConfigurationError, parse_cuda_device from allennlp...
allennlp/training/trainer.py
Apache-2.0
40,270
3a725ee054e17986c9b4a21cf3f79c5ea3fb9f20
Python
py
# coding: utf-8 from __future__ import print_function import time start = time.time() from collections import Counter, defaultdict import random import sys import argparse import numpy as np import torch from torch import nn from torch import optim from torch.autograd import Variable from torch.nn import functional as...
msda_src/tagging/tagging_moe.py
MIT
15,258
4b7d5f8f2eb6292406688c69236bd0a3d205ab8c
Python
py
from abc import ABCMeta, abstractmethod import numpy as np import torch from torch.autograd import Variable from torch.nn import CrossEntropyLoss import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from typing import Optional import time from pdb import set_trace as st class Attacker(...
attacks.py
MIT
24,531
3a7279c035b01432df73c180dce542d600cab1a8
Python
py
#!/usr/bin/env python3 import numpy as np import torch from itypes import TorchStruct device = torch.device('cuda:0') print() s = TorchStruct(dims="hwc") s.x = torch.tensor([[[1, 2, 3], [4, np.nan, np.inf]]], device=device) s.y = TorchStruct(dims="hwc") s.y.z = torch.tensor([[7, 8, 9], [10, np.nan, np.inf]], device=...
examples/struct/torch_struct.py
MIT
1,533
3a7284d6039a72e165fd350f3e5413a6beadb76f
Python
py
import torch import torchvision.transforms as transforms import torchvision.transforms.functional as F from torch._utils_internal import get_file_path_2 import unittest import math import random import numpy as np from PIL import Image try: import accimage except ImportError: accimage = None try: from scip...
test/test_transforms.py
BSD-3-Clause
52,229
3a72a6150e642a296c9b0f7dcdcdb2555f2abe8c
Python
py
"""Test configurations for `backpack.core.derivatives` for CONVOLUTIONal layers Required entries: "module_fn" (torch.nn.Module): Module class of layer. "module_kwargs" (dict): Dictionary used for layer initialization. "input_kwargs" (dict): Parameters required by torch.nn.Module class "size": Requ...
test/core/derivatives/convolution_settings.py
MIT
4,114
5f83f3a029392715198a744196ac12ca42dbc44c
Python
py
# Copyright (c) Meta Platforms, Inc. and 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 math from functools import lru_cache from typing import Callable, Dict, Iterable, Optional, Sequence, Tuple import to...
src/beanmachine/ppl/experimental/inference_compilation/ic_infer.py
MIT
22,001
28a4583c181233fe4b48ea333798cbeae22b7f3a
Python
py
# Copyright 2018-2021 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 applicabl...
pennylane/transforms/classical_jacobian.py
Apache-2.0
7,509
a96a1dcceb96735b40e704177c57512756eb8038
Python
py
import time import numpy as np import torch import torch.optim as optim from torch.optim.lr_scheduler import StepLR from torch.utils.data import DataLoader from models import * from utilw import data_generator class Model: def __init__(self,config): self.model = None self.config = config ...
train.py
MIT
4,611
3a72e678b3cd858beb2abd553299c2ca82bac96f
Python
py
# -*- encoding: utf-8 -*- # ---------------------------------------------- # filename :nommer.py # description :NomMer: Nominate Synergistic Context in Vision Transformer for Visual Recognition # date :2021/12/28 17:45:26 # author :clark # version number :1.0 # --------------------------...
models/nommer.py
Apache-2.0
20,770
345848d8a13a91c362e9d1b834f9d240e231a7e7
Python
py
import torch from torch import nn, optim import torch.nn.functional as F from torch import nn from torch.autograd import Variable from utils.OT import SinkhornDistance import numpy as np from models.resnet import ResNet18 import random def mixup_process(out, y, lam): indices = np.random.permutation(out.size(0)) ...
cifar10_100/models/resnet18_classifier.py
MIT
2,702
f9376e9b6e7afb602acf0c499f2e005845a1e29e
Python
py
import numpy as np import json import torch import torch.optim as optim import torch.nn as nn import torchvision import torchvision.transforms as transforms from torch.autograd import Variable import torch.utils.data as data import argparse import logging import os import copy from math import * import datetime from m...
experiments.py
MIT
41,917
4ba11051174bd2d19a5b9861c067fe9c09ba5263
Python
py
import torch import torchvision from torch.utils.tensorboard import SummaryWriter from torchvision import datasets, transforms # Writer will output to ./runs/ directory by default writer = SummaryWriter('./GeometricVisualization/runs') transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((...
mytensorboard.py
MIT
888
24e3e6bb65d9486d3dbf23ef6ca82405fa373da8
Python
py
#!/usr/bin/env python3 from ruamel.yaml import YAML, dump, RoundTripDumper # import os import math import argparse import numpy as np import time import sys import torch from rpg_baselines.envs import vec_env_wrapper as wrapper from scipy.spatial.transform import Rotation # from flightgym import QuadrotorEnv_v1 def...
flightrl/examples/test_vec_env.py
MIT
2,912
3a7326e19540fd74c4437499d4a8d9bea2fd1e5b
Python
py
import argparse import os import numpy as np import math 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 import torch.nn as nn import torch.nn.functional as F import torch...
implementations/lsgan/lsgan.py
MIT
6,581
3a73299aeb31aa85c7796a548f18dd27d0193e0f
Python
py
import abc import copy from collections import defaultdict from typing import Dict, Optional, Tuple import torch from torch import nn from torch.nn.utils import parametrize from .utils import FakeSparsity, module_to_fqn, fqn_to_module SUPPORTED_MODULES = { nn.Linear } class BaseSparsifier(abc.ABC): r"""Bas...
torch/ao/sparsity/sparsifier/base_sparsifier.py
Intel
10,866
7c482b0f93dabc6e8a2fd002c84904aa07457188
Python
py
""" Proof-of-concept for porting mmcv DataContainer concept to netharn. Depending on how well this works these features might be useful as a standalone module or to contribute to torch proper. References: https://github.com/open-mmlab/mmcv/blob/master/mmcv/parallel/data_container.py https://github.com/open-mml...
netharn/data/data_containers.py
Apache-2.0
34,643
3a733a7ac7fc93b89ab73b91f7d4fb1def2026e7
Python
py
from loguru import logger import cv2 import torch from yolox.data.data_augment import preproc from yolox.exp import get_exp from yolox.utils import fuse_model, get_model_info, postprocess, vis from yolox.utils.visualize import plot_tracking from yolox.tracker.byte_tracker import BYTETracker from yolox.tracking_utils...
tools/demo_track.py
MIT
13,475
3a7352a40e9a353fed807437ad283e3e012d0b1e
Python
py
import os import torch import pickle from progress.bar import Bar from utils import AverageMeter, adjust_learning_rate class Trainer(object): """docstring for Trainer""" def __init__(self, Model, Optimizer, Loss, Metrics, File, vis, opts): super(Trainer, self).__init__() ...
trainer.py
MIT
5,041
3a73575d0df51eba6b00d6431f48f95099a0f2a9
Python
py
################################################################################ # Copyright (c) 2021 ContinualAI. # # Copyrights licensed under the MIT License. # # See the accompanying LICENSE file for terms. ...
avalanche/evaluation/metrics/topk_acc.py
MIT
13,096
a9676bf1bc14421428bd122ff2f5f98f043e9a07
Python
py
import torch sigmoid = torch.nn.Sigmoid() x1 = torch.tensor(1.0, requires_grad=True) w1 = torch.tensor(0.5, requires_grad=True) w2 = torch.tensor(1.0, requires_grad=True) w3 = torch.tensor(1.0, requires_grad=True) w4 = torch.tensor(0.5, requires_grad=True) w5 = torch.tensor(0.5, requires_grad=True) y1 = x1*w1 y1.r...
ML_Lecture5_SelfStudy5/ex3_lecture.py
MIT
1,406
5fc5c313d53b8a6957eda61209ca090d4bb2f062
Python
py
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import Dataset, DataLoader import numpy as np from torchvision.models.resnet import resnet18, resnet34, resnet50 from sklearn.manifold import TSNE from sklearn.decomposition import PCA import os import...
deepcca/conv_dcca_mnist.py
MIT
22,407
346a87f2c15035f316eaf807c1e2145427162ddd
Python
py
import os from unittest.mock import patch import pytest from pytorch_lightning import Trainer from pytorch_lightning.utilities.exceptions import MisconfigurationException from tests.base import EvalModelTemplate import tests.base.develop_pipelines as tpipes try: import torch_xla # TODO: The tests are aborted...
tests/models/test_tpu.py
Apache-2.0
5,088
5ec2e7e7d9492b22f7e4c5dc9842804cecd3807e
Python
py
import numpy as np import torch import torch.nn as nn from .. import UnsupervisedModelWrapper from cogdl.wrappers.tools.wrapper_utils import evaluate_node_embeddings_using_logreg class DGIModelWrapper(UnsupervisedModelWrapper): @staticmethod def add_args(parser): # fmt: off parser.add_argume...
cogdl/wrappers/model_wrapper/node_classification/dgi_mw.py
MIT
3,262
3a7377c6ec11ee484adcd525118b48f3ecf55a06
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/environments/random_alf_environment.py
Apache-2.0
8,440
a94a203c1e608a027a29e7e95461506e6b4ed76e
Python
py
# Copyright 2018-2019 Open-MMLab. All rights reserved. # Licensed under the Apache License, Version 2.0. import logging import os import sys import os.path as osp import time import torch import torch.optim from . import hooks from .log_buffer import LogBuffer from .priority import get_priority from .hooks import (...
siam_tracker/runner/runner.py
MIT
13,270
45c18a871d5cc5cbf91aa6837c67eb392898da41
Python
py
# -*- coding: utf-8 -*- """ Adversarial robustness objective, and corresponding weights_manager. Copyright (c) 2019 Xuefei Ning, Junbo Zhao """ # pylint: disable=missing-docstring,invalid-name,no-self-use import sys import weakref import functools import contextlib from collections import OrderedDict import os import ...
examples/plugins/robustness/1_robustness.py
MIT
29,491
e9c3767fd5ee5f23e8ee8c956a0a606823485033
Python
py
# coding=utf-8 # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
megatron/training.py
Apache-2.0
26,785
4b6135916371757f3086aab8214a4653e0903496
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import os import unittest from pathlib import Path from typing import Callable, Optional, Union import numpy as ...
tests/common_testing.py
BSD-3-Clause
6,445
3a73bfeb186f312a890a01a7e15d8f549ee007ae
Python
py
import numpy as np import pytest import torch from rfvision.core import BitmapMasks, PolygonMasks def dummy_raw_bitmap_masks(size): """ Args: size (tuple): expected shape of dummy masks, (H, W) or (N, H, W) Return: ndarray: dummy mask """ return np.random.randint(0, 2, size, dtyp...
tests/test_utils/test_masks.py
Apache-2.0
25,988
3a73c9f5ec19fe1797f218b3128976db9f971e62
Python
py
import torch import numpy as np import os from datetime import datetime import data import metrics import plots from pytorch_spa_nn import SpaNn torch.set_printoptions(linewidth=180, precision=8, edgeitems=12) np.set_printoptions(linewidth=180) def continue_training_from_checkpoint(checkpoint, max_epochs, new_check...
pytorch_train_network.py
MIT
17,511
e94d774c397e31cf1c9a159a36f319984b8ac998
Python
py
import numpy as np import torch import torch.nn as nn import logging import gym.spaces as spaces from rlberry.agents import AgentWithSimplePolicy from rlberry.agents.utils.memories import Memory from rlberry.agents.torch.utils.training import optimizer_factory from rlberry.agents.torch.utils.models import default_poli...
rlberry/agents/torch/ppo/ppo.py
MIT
15,226
3a73e2e45fb47b58d1b43f4ce327e17ac3853016
Python
py
import math import torch import torch.nn as nn from src.org.campagnelab.dl.funnel.transformer.EncoderDecoder import clones import torch.nn.functional as F def attention(query, key, value, mask=None, dropout=None): "Compute 'Scaled Dot Product Attention'" d_k = query.size(-1) scores = torch.matmul(query, k...
src/org/campagnelab/dl/funnel/transformer/Attention.py
MIT
2,810
3a73e7363bd851973e958f9b8b115711f2bbdf9e
Python
py
import torch import numpy as np from collections import namedtuple def prepare_data(x_particles, t_particles, x_sample, t_sample): t_grid, x_grid = np.meshgrid(t_sample, x_sample, indexing='ij') rand_idx = np.random.permutation(t_grid.size) grid_data = torch.tensor(np.concatenate((t_grid.reshape(-1, 1), x...
src/temporal_normalizing_flows/preprocessing.py
MIT
961
3a74107160edb4eb30c0078bcd05d1835e48d85e
Python
py
import argparse from torch.utils.data import DataLoader from bert_pytorch import parse_args from .model import BERT from .trainer import BERTTrainer from .dataset import BERTDataset, WordVocab import random import torch import numpy as np def train(): # Make all randomness deterministic random.seed(1337) ...
torchbenchmark/models/BERT_pytorch/bert_pytorch/__main__.py
BSD-3-Clause
2,191
1e91d38e24368168d6d3ac1b1a4a1a6dd976ed63
Python
py
import torch from torch.autograd import Function from torch.nn.modules.module import Module from torch.autograd import Variable import os from torch.autograd.function import once_differentiable torch_ver = torch.__version__[:3] if torch_ver=="0.4": from torch.utils.cpp_extension import load build_path = o...
lib/model/roi_align.py
Apache-2.0
7,818
3a7425f02d417e49533a06517c4ca67e26f4f254
Python
py
# -*- coding: utf-8 -*- # # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # # pylint: disable= no-member, arguments-differ, invalid-name # # Pre-trained models on MUV import torch.nn.functional as F from ...model_zoo import GCNPredictor, GATPredictor, WeavePr...
python/dgllife/model/pretrain/moleculenet/muv.py
Apache-2.0
8,227
3a743740107a4c4b7070fe0d3040242984d1830b
Python
py
import inspect import torch def batch_callable(f): if not callable(f): return False return 'batch' in inspect.signature(f).parameters.keys() def padshape(x, target_dim, dim=-1): """ Insert singleton dimensions in position `dim` until the tensor as dimensionality `target_dim`. """ ...
nitorch/nn/generators/utils.py
MIT
882
3a7443f43b768237c23e34864d64da7cc47a4027
Python
py
import torch.nn as nn class ClassificationHead(nn.Module): def __init__(self, embedding_size, output_size): super().__init__() self.embedding_size = embedding_size # self.head = nn.Sequential( # nn.Linear(embedding_size, 256), # nn.ReLU(inplace=True), # ...
models/ClassificationHead.py
Apache-2.0
631
ff0c3d99185fc7c1079cff96ab58a1bbd2aaa03a
Python
py
from torch.nn import Module, Linear, GRUCell, LayerNorm import torch as T class GruAttDecoder(Module): """ Attention based GRU decoder that attends a custom sequence. Another difference from the classical gru decoder is that here I manually loop over steps instead of relying on the internals provided ...
mlmo/layers/decoders/gru_att_decoder.py
MIT
6,766
457b21790fffa79342106afd49082903fb56a82e
Python
py
import torch from torch.nn.functional import cross_entropy, interpolate __all__ = [ "cross_entropy2d", "multi_scale_cross_entropy2d", "bootstrapped_cross_entropy2d", ] def cross_entropy2d(input, target, weight=None, size_average=True): n, c, h, w = input.size() nt, ht, wt = target.size() # H...
neodroidvision/segmentation/evaluation/experimental/cross_entropy_2d.py
Apache-2.0
2,492
fcaba251404a7313c3cc2298a433ef9308d505a3
Python
py
import torch import torch.nn as nn import pytorch_lightning as pl from .set_transformer import ISAB, PMA class SetEncoder(pl.LightningModule): def __init__(self,cfg): super(SetEncoder, self).__init__() self.linear = cfg.linear self.bit16 = cfg.bit16 self.norm = cfg.norm asse...
src/nesymres/architectures/set_encoder.py
MIT
3,933
7c2bdfb2f270cc4897caaf42e49883b40c4977f6
Python
py
import torch import torch.nn as nn import torch.nn.functional as F class _conv(nn.Conv2d): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias): super(_conv, self).__init__(in_channels = in_channels, out_channels = out_channels, kernel_size = ke...
ops.py
MIT
3,429
24ac7d9cc953362751e6fad4a29ca54150db4407
Python
py
import random import warnings from collections import OrderedDict from functools import wraps from typing import Any, Callable, Generator, Iterator, List, Optional, cast import torch from torch.utils.data import DataLoader from torch.utils.data.sampler import BatchSampler from ignite.engine.engine import Engine from ...
ignite/engine/deterministic.py
BSD-3-Clause
11,440
4286b5acc662fd2660f8982bfdc20c9afc1ce64e
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from models.output_layer import * from models.utils import * from models import base class Model(base.SRNNBase): def __init__(self, d_data, d_emb, d_mlp, d_rnn, d_lat, n_layer, dropout=0., **kwargs): super(Model, self).__init__(d_data, ...
speech/models/srnn.py
MIT
1,506
ff9f96568344d5689396640c6f895fc6921a014d
Python
py
import os import torch import torch.nn as nn import tree import senreps import numpy as np from init import create_data, parse_corpus from DC import DC from senreps import fetch_fake_pos_tags from torch import Tensor from transformers import * from collections import defaultdict device = torch.device("cuda:0" if torch...
Assignment1/train_pos.py
MIT
6,973
7cbf143420692fa28783604b744b15bf8a21afb1
Python
py
''' Author: Shuailin Chen Created Date: 2020-11-27 Last Modified: 2021-06-20 ''' # 2020-10-16 将softmax层移除,因为ptorch里面的计算交叉熵的函数内部已经集成了softmax # 统一设置所有的 drop out 概率 # Rodrigo Caye Daudt # https://rcdaudt.github.io/ # Daudt, R. C., Le Saux, B., & Boulch, A. "Fully convolutional siamese networks for change detection". In 2...
mmseg/models/siambackbones/siamunet_diff.py
Apache-2.0
7,758
3a74a0cc447e624218300f2640f44735a4c06170
Python
py
"""Training GCMC model on the MovieLens data set by mini-batch sampling. The script loads the full graph in CPU and samples subgraphs for computing gradients on the training device. The script also supports multi-GPU for further acceleration. """ import os, time import argparse import logging import random import stri...
examples/pytorch/gcmc/train_sampling.py
Apache-2.0
21,160
3a74ab72b18631b095a93d5a45673e9d25288787
Python
py
# -*- coding: utf-8 -*- """Main module.""" import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Normal, kl_divergence as kl from scvi.models.distributions import ( ZeroInflatedNegativeBinomial, NegativeBinomial, Poisson, ) from scvi.models.m...
scvi/models/vae.py
MIT
17,064
3a74aeb83c84d25408ec4fc7154a7ce108337413
Python
py
#! /home/jan/anaconda3/bin/python3 import functions import csv import os import itertools import functions from classes import MLP, MLP_w_torchlrp, AlexNet import subprocess import os import sys import time import torch import random import pathlib import argparse import torchvision import matplotlib.pyplot as plt #f...
src/main.py
MIT
2,584
1ed626b396df69b65a0d5b4fe26a0998e39a89bd
Python
py
import math import cmath import warnings import torch import torch.backends.cudnn as cudnn from torch._six import PY37 from ..nn.modules.utils import _single, _pair, _triple, _quadruple, _list_with_default from collections import OrderedDict from typing import Dict, Optional _builtin_table: Optional[Dict[int, str]]...
torch/jit/_builtins.py
Intel
6,064
10a0b159dbee3c50c2b2878b76a3c5ae7e6249a3
Python
py
#! /usr/bin/python # -*- encoding: utf-8 -*- import torch import torch.nn as nn class OhemSphereLoss(nn.Module): def __init__(self, in_feats, n_classes, thresh=0.7, scale=14, *args, **kwargs): super(OhemSphereLoss, self).__init__(*args, **kwargs) self.thresh = thresh self.scale = scale ...
sphere_loss.py
MIT
2,314
fdcbd1e92e12f505926fe595b15d2e228e410dbe
Python
py
# encoding: utf-8 import math import torch as th import torch from torch import nn class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=...
models/resnet.py
MIT
6,370
b277335647ce2db81c9e28b6a5f2c8455c875169
Python
py
import math import numpy as np import torch from torch import optim from torch import nn import torch.utils.data from torch.nn import BatchNorm1d, Dropout, LeakyReLU, Linear, Module, ReLU, Sequential, Sigmoid from torch.autograd import Variable import warnings from .data_sampler import DataSampler from ctgan.data_tran...
snsynth/pytorch/nn/patectgan.py
MIT
19,882
03cbbc26a826d8fe71bcfcc68b4974bfdcdd3450
Python
py
import os import shutil import numpy as np import torch from torch.utils.data import Dataset, DataLoader, ConcatDataset, Sampler from deepSM import SMData from deepSM import utils import deepSM.beat_time_converter as BTC from deepSM import wavutils from deepSM import StepPlacement from deepSM import SMDataset from d...
deepSM/SMDUtils.py
MIT
8,848
d7f84bef3d6e6c969b3f189f264a14c84051297b
Python
py