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
import torch import numpy as np import utils as u from argparse import Namespace from torch.nn.parameter import Parameter import torch.nn as nn import math class Sp_GCN(torch.nn.Module): def __init__(self, args, activation): super().__init__() self.activation = activation self.num_layers =...
experiment/models/egcn_components.py
Apache-2.0
8,391
703acda094063a9753dfbf20f39fe63c446c3200
Python
py
# Copyright (c) OpenMMLab. All rights reserved. import os import mmcv import pytest import torch from mmgen.apis import (init_model, sample_ddpm_model, sample_img2img_model, sample_unconditional_model) class TestSampleUnconditionalModel: @classmethod def setup_class(cls): pr...
tests/test_apis/test_inference.py
Apache-2.0
4,700
80067a452fa870b692422ddf10450a6e2f946390
Python
py
import torch import torch.nn as nn import torch.nn.functional as F class VectorQuantizer(nn.Module): def __init__(self, num_embeddings, embedding_dim, commitment_cost): super(VectorQuantizer, self).__init__() self._embedding_dim = embedding_dim self._num_embeddings = num_...
models/vq.py
MIT
5,117
29c8de5193f979b7c2e3aed07b06c435ef7d8358
Python
py
"""Helper functions to modify models to have multiple gradient paths.""" import functools import torch def introspect_model(model, input_data_shape, modality="vision"): """Compute model feature shapes.""" feature_shapes = dict() if modality == "vision": setup = dict(device=next(iter(model.paramete...
breaching/cases/malicious_modifications/parameter_utils.py
MIT
4,260
29c8fd49ef4ca55c1720666065464b1dbaeb45d2
Python
py
from typing import Dict # isort:skip from collections import defaultdict import torch from torch.optim import Optimizer class Lookahead(Optimizer): def __init__(self, optimizer: Optimizer, k: int = 5, alpha: float = 0.5): """ Taken from: https://github.com/alphadl/lookahead.pytorch """ ...
catalyst_rl/contrib/nn/optimizers/lookahead.py
Apache-2.0
3,019
ff7c4e020707de111d1a7b59c1f7d1c54a817571
Python
py
import time import torch import wjc_core import argparse from tensorboardX import SummaryWriter from attention_unet import AttU_Net from segnet import SegNet from unet import Unet from Unet_plus_plus import NestedUNet from Res_net import ResNet50, ResNet101 from MDOAU_net import MDOAU_net from new_model impo...
main.py
MIT
5,813
29c961eef20045d82c1d158a48f894403bf3f467
Python
py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """Train a video classification model.""" import numpy as np import pprint import torch from fvcore.nn.precise_bn import get_bn_modules, update_bn_stats import slowfast.models.losses as losses import slowfast.models.optimiz...
tools/train_net.py
Apache-2.0
17,761
29c98c9e93439e81f21bef32b61dee2b64df09f5
Python
py
# 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 required by appli...
nemo/collections/asr/parts/rnnt_beam_decoding.py
Apache-2.0
29,286
29c9960ffe14fd99bff9e9cd061c5aa4b1c3511e
Python
py
import unittest import os import mock import torchtext from seq2seq.data import SourceField, TargetField from seq2seq.trainer import SupervisedTrainer class TestSupervisedTrainer(unittest.TestCase): def setUp(self): test_path = os.path.dirname(os.path.realpath(__file__)) src = SourceField() ...
seq2seq/tests/test_supervised_trainer.py
Apache-2.0
1,805
24d274b7e2dbd31aa10daec97b9c9a10ee04cffa
Python
py
import os import sys import json import subprocess import numpy as np import torch from torch import nn from opts import parse_opts from model import generate_model from mean import get_mean from classify import classify_video import glob from tqdm import tqdm import pdb import pickle as pkl def convert_to_np(resul...
video-classification-3d-cnn-pytorch/main.py
MIT
2,405
29c9d3535c0c856d9cc26dbd11db02ac7cdfba01
Python
py
import os import sys import json import random import numpy as np from PIL import Image import collections import torch import torchvision.transforms as T from skimage import io from torchvision.transforms import functional as F from pathlib import Path if sys.version_info < (3, 3): sequence = collections.Sequence...
naslib/utils/load_ops.py
Apache-2.0
15,458
29c9dcab51a4b3598e2475dee4b42d542b108019
Python
py
from typing import List, Union import numpy as np import torch from numpy import ndarray from transformers import * class BertParent(object): """ Base handler for BERT models. """ MODELS = { 'bert-base-uncased': (BertModel, BertTokenizer), 'bert-large-uncased': (BertModel, BertToken...
summarizer/bert_parent.py
MIT
5,766
1038f8f7d05a5821b3d113cbe4bae5bc481e5824
Python
py
import math import random import torch from torch import nn from torch.nn import functional as F if torch.cuda.is_available(): from op.fused_act import FusedLeakyReLU, fused_leaky_relu from op.upfirdn2d import upfirdn2d else: from op.fused_act_cpu import FusedLeakyReLU, fused_leaky_relu from op.upfirdn...
e4e/models/stylegan2/model.py
MIT
18,729
fcb12af85669ab6fd7f79cb14ddbdf80b2fbd83d
Python
py
import os import time import random import argparse import torch import torch.nn as nn import torch.optim as optim import torch.utils.data from dataset.md_seq import MoDaSeq, paired_collate_fn from dataset.md_seq_ac import MoDaSeqAC from utils.log import Logger from utils.functional import str2bool, load_data, load_...
actor_critic.py
MIT
32,393
29c9f5519c3a6894f95b71f8dd4328c6631e9aa8
Python
py
from typing import Any, Callable, Dict, Optional, Tuple, Type, Union import numpy as np import torch as th from hmlf import spaces from hmlf.algorithms.td3.policies import TD3Policy from hmlf.algorithms.td3.td3 import TD3 from hmlf.common.noise import ActionNoise from hmlf.common.off_policy_algorithm import OffPolicy...
hmlf/algorithms/paddpg/paddpg.py
MIT
8,866
650f078c17d28bcb7fafab11e968ceab55bcfd62
Python
py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from mmdet.core import (auto_fp16, bbox_target, delta2bbox, force_fp32, multiclass_nms) from ..builder import build_loss from ..losses import accuracy from ..registry import HEADS @HEADS.register_module class...
mmdet/models/track_heads/track_head.py
Apache-2.0
6,697
f996cfbdd33ced8d566b70911d4f362419268041
Python
py
""" trying to resolve: - https://intellij-support.jetbrains.com/hc/en-us/requests/3764538 You will need to run pip install transformers pip install fairseq On mac pip3 install torch torchvision torchaudio on linux pip3 install torch==1.10.1+cpu torchvision==0.11.2+cpu torchaudio==0.10.1+cpu -f https:...
tutorials_for_myself/try_catch_pycharm_issues/try_catch_with_pickle.py
MIT
3,168
e621119a87c44175c1d81820b550a2a48182dd0a
Python
py
import os import librosa.display as lbd import matplotlib.pyplot as plt import sounddevice import soundfile import torch import torchaudio import configparser import soundfile as sf from Preprocessing.AudioPreprocessor import AudioPreprocessor from Preprocessing.TextFrontend import TextFrontend from speechbrain.pretr...
InferenceInterfaces/aridialect_Tacotron2.py
Apache-2.0
9,929
42192edf6ecbfabbfe5a31cefbcb3b9f6890d8d9
Python
py
# Owner(s): ["oncall: quantization"] import torch import math from typing import Tuple from torch.ao.quantization import ( FakeQuantize, MovingAverageMinMaxObserver, default_observer, default_affine_fixed_qparams_fake_quant, ) from torch.ao.quantization._learnable_fake_quantize import _LearnableFakeQu...
test/quantization/core/test_workflow_ops.py
Intel
58,785
28de0540877f7bf0341b2377dbeab6de32246309
Python
py
from .camera_geometry import CameraGeometry import numpy as np import cv2 import torch from fastseg import MobileV3Small class LaneDetector(): def __init__(self, cam_geom=CameraGeometry(), model_path='./fastai_model.pth'): self.cg = cam_geom self.cut_v, self.grid = self.cg.precompute_gri...
code/solutions/lane_detection/lane_detector.py
CC-BY-4.0
2,634
ff011bbf911eba1f3dbeb536a002234c8535353f
Python
py
import torch from torch import nn class FuzzBuzzModel(nn.Module): def __init__(self, input_size, hidden_size, output_size): """ 2 layer network for prediction fiz or buz :param int input_size: size of the input layer :param int hidden_size: size of the hidden linear laye...
FuzzBuzzNet.py
MIT
918
29ca7a089ac9fa07f66636838e1a5d6bf3f31d15
Python
py
import warnings from typing import Dict, List, Optional, Tuple import torch from torch.utils.data import Dataset from lhotse import validate from lhotse.cut import Cut, CutSet, MonoCut from lhotse.utils import EPSILON class SourceSeparationDataset(Dataset): """ .. warning: Speech separation datasets are not...
lhotse/dataset/source_separation.py
Apache-2.0
6,601
247ce4e66125d4182c051248347393e4d3b8011b
Python
py
# we already use multiprocessing, multithreading will not improve anything here so disable it import os os.environ['OMP_NUM_THREADS'] = '1' os.environ['MKL_NUM_THREADS'] = '1' import torch.nn as nn import torch import trw class Net(nn.Module): def __init__(self): super(Net, self).__init__() self...
tutorials/recipes/segmentation_cityscapes.py
MIT
1,231
d75c87b0aa48899d3f7a59f5f0a918fcfd831cf4
Python
py
""" CHAED includes 1) 1000 images, 10 for each of 100 Chinese characters 2) including 20 characters with single element and 3) 80 with multi components in different structure types including horizontal composition, vertical composition, half surrounding compos...
dataset/chaed.py
Apache-2.0
10,301
7c84da9fb31ffda029ec297f3eb3e8dea43be73c
Python
py
""" Contains pieces taken from https://github.com/pytorch/examples/issues/70 and https://github.com/pytorch/examples/tree/master/vae """ import torch import torch.nn as nn class Decoder(nn.Module): def __init__(self): nc = 3 ndf = 128 ngf = 128 nz = 100 super().__init__() ...
demo/fishvae.py
MIT
3,721
5f0a581cab1a0bc31a3e55d97bf72ae5f8ee8aac
Python
py
import math from numbers import Number import torch from torch.distributions import constraints from torch.distributions.exp_family import ExponentialFamily from torch.distributions.utils import _standard_normal, broadcast_all from scipy.stats import gennorm import numpy as np class GeneralisedNormal(ExponentialFami...
nnest/distributions/generalised_normal.py
MIT
2,870
29cab4c961b2937ebd8ba5570e717d3ca75ea4ce
Python
py
#!/usr/bin/env python import logging import argparse import numpy import torch import pyro import pyro.infer import pyro.infer.mcmc import pyro.distributions as dist def get_arguments(): parser = argparse.ArgumentParser(description='Bayesian Calibration arguments') parser.add_argument('--logging-level', def...
run.py
BSD-3-Clause
3,112
29cabb18faffc8c6e81b74262da3a89ee7c76709
Python
py
import os, sys sys.path.append(os.getcwd()) import time import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import sklearn.datasets import tflib as lib import tflib.save_images import tflib.mnist import tflib.plot import torch import torch.autograd as autograd import torch.nn ...
gan_mnist.py
MIT
7,897
29cac132574a88fad302c9496c1fddc4225ec57d
Python
py
import torch import warpctc_pytorch as warp_ctc import pytest @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires GPU") def test_simple(): probs = torch.FloatTensor([[[0.1, 0.6, 0.1, 0.1, 0.1], [0.1, 0.1, 0.6, 0.1, 0.1]]]).transpose(0, 1).contiguous() grads = torch.zeros(probs.size()) labe...
pytorch_binding/tests/test_gpu.py
Apache-2.0
3,891
fcee5901015ececb2bdd86e930783631bc755564
Python
py
# -*- coding: utf-8 -*- # # sampler.py # # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.or...
entity_name_align/dataloader/sampler.py
Apache-2.0
41,901
fcf10be3073803a176ed88e1700363ce87a73d95
Python
py
import torch import torch.nn.functional as F import numpy as np from PIL import Image import morphology import network import os import math from tqdm import tqdm ### idx = 0 def save_img(img, output_path): result = Image.fromarray( (img.data.cpu().numpy().transpose((1, 2, 0)) * 255).astype(np.uint8)) ...
inference.py
MIT
30,176
29cadda836c61bd5fe5aec34cb80e6fba67391d7
Python
py
# flake8: noqa import numpy as np import torch from catalyst.metrics.functional._hitrate import hitrate def test_hitrate(): """ Tests for catalyst.metrics.hitrate metric. """ y_pred = [0.5, 0.2, 0.1] y_true = [1.0, 0.0, 1.0] k = [1, 2, 3] hitrate_at1, hitrate_at2, hitrate_at3 = hitrate(...
tests/catalyst/metrics/functional/test_hitrate.py
Apache-2.0
1,175
7c464798fdac0c3f7c13305ae4fb20f5e77ce681
Python
py
# -*- coding: utf-8 -*- ''' Author: Ioannis Kakogeorgiou Email: gkakogeorgiou@gmail.com Python Version: 3.7.10 Description: evaluation.py includes the code in order to produce the evaluation for each class as well as the prediction masks for the pixel-level semantic segmentation. ''' ...
semantic_segmentation/unet/evaluation.py
MIT
7,939
29caebd1538de52b3018c176bd7b4d33e4f2ce6d
Python
py
from __future__ import absolute_import, division, print_function import numbers import torch import math def _compute_chain_variance_stats(input): # compute within-chain variance and variance estimator # input has shape N x C x sample_shape N = input.size(0) chain_var = input.var(dim=0) var_with...
pyro/ops/stats.py
MIT
15,570
3414389735c4a837d6a9cc0ce02f5a13bc1ed9c4
Python
py
# -*- coding: utf-8 -*- # file: run_glove_test.py # time: 2021/12/4 # author: yangheng <yangheng@m.scnu.edu.cn> # github: https://github.com/yangheng95 # Copyright (C) 2021. All Rights Reserved. import shutil from torch import cuda from pyabsa import APCModelList, BERTBaselineAPCModelList, GloVeAPCModelList, \ AT...
basic_test/run_glove_test.py
MIT
4,009
45cf0eeb9178cbf1cf37b6ac7dbed185d7f842b7
Python
py
"""Neural net classes.""" import fnmatch from itertools import chain from collections import OrderedDict import tempfile import warnings import numpy as np from sklearn.base import BaseEstimator import torch from torch.utils.data import DataLoader from skorch.callbacks import EpochTimer from skorch.callbacks import ...
skorch/net.py
BSD-3-Clause
60,946
7c798ebdc6ada3734387a212d4e5e5b54dd64fe2
Python
py
import torchvision.models as vision_models import torch from torchvision import transforms def load_model(): model = vision_models.googlenet(pretrained=True) model.eval() model = { "model": model, "preprocessing": transforms.Compose([ transforms.Resize(256), transf...
api_ml/models/googlenet.py
Apache-2.0
632
29cb13deb0085d89241b0c1ed3e5803fce7e93be
Python
py
import torch import unittest from summarize.modules.coverage_matrix_attention import MLPCoverageAttention class TestMLPCoverageAttention(unittest.TestCase): def test_mlp_coverage_attention(self): batch_size = 3 num_encoder_tokens = 7 num_decoder_tokens = 9 encoder_dim = 11 ...
summarize/tests/modules/coverage_matrix_attention/mlp_test.py
Apache-2.0
1,850
29cb203792208463f38070f2061b12a29e99a09f
Python
py
from collections import deque import numpy as np import torch from torch import optim from torch._C import device import torch.nn as nn import torch.nn.functional as F from tqdm import tqdm from QL.DQN import DQN from QL.ReplayBuffer import ReplayBuffer from SetteEMezzoGame import SetteEMezzo import matplotlib.pyplot a...
SetteEMezzoDQL.py
MIT
8,094
7cadcded2f6081bd3908737105c9159f1bfcff98
Python
py
#import needed library import os import logging import random import warnings import numpy as np import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.multiprocessing as mp from utils import net_builder, get_logger, count_paramet...
train.py
MIT
15,340
7c29059dffdbd1e1c916e56d6d52b8329aa81243
Python
py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import copy import os import os.path as osp import mmcv import torch from mmcv import DictAction from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import (get_dist_info, init_dist, load_checkpoint, ...
tools/analysis_tools/test_robustness.py
Apache-2.0
15,222
29cb41da657005ee8fbf772fda03603a81442983
Python
py
import os import sys sys.path.append('../../') from dependencies import * from settings import * from reproducibility import * from models.TGS_salt.Unet34_scSE_hyper import Unet_scSE_hyper as Net import pickle TUNE = False SIZE = 101 PAD = 27 Y0, Y1, X0, X1 = PAD,PAD+SIZE,PAD,PAD+SIZE, FOLD=["0","1","2","3","9"] RAN...
projects/TGS_salt/obsolete/inference_kfolds.py
Apache-2.0
16,127
4bb89f8a136e8762efbdb70d563358bdf76e86ab
Python
py
import torch import os from PIL import Image from torch.utils.data import Dataset from natsort import natsorted # define custom dataset for TrojAI competition class CustomDataSet(Dataset): def __init__(self, main_dir, transform, triggered_classes, label_specific=False): self.main_dir = main_dir s...
dataset.py
MIT
1,311
1e702f9a77ff5fbbb2255cc5504bb0d975267ce8
Python
py
from __future__ import division import torch import onmt """ Class for managing the internals of the beam search process. hyp1-hyp1---hyp1 -hyp1 \ / hyp2 \-hyp2 /-hyp2hyp2 / \ hyp3-hyp3---hyp3 -hyp3 ================...
onmt/Beam.py
MIT
3,298
4b6603e165e8776102b05e829cf0060f6cd4e981
Python
py
#!/usr/bin/env python3 import inf_common as IC import torch from torch import Tensor import time from typing import Dict, List, Tuple, Optional from collections import defaultdict from collections import ChainMap import sys,random,itertools import numpy as np import math from multiprocessing import Pool import...
model_debugger_pieces.py
MIT
8,653
5ea164c824ec5a95922fb0d777e10b355a89dbeb
Python
py
"Callback support for half precision (fp16) training. Increases training speed." from ..torch_core import * from ..callback import * from ..basic_train import * from torch._utils import _unflatten_dense_tensors from torch.nn.utils import parameters_to_vector __all__ = ['MixedPrecision'] def get_master(layer_groups:Mo...
fastai_do_not_use/callbacks/fp16.py
Apache-2.0
5,471
29cbc52038794815c64f65c4427d098876fbbb75
Python
py
import random from collections import namedtuple import numpy as np import torch from src.config import BATCH_SIZE, BUFFER_SIZE, GAMMA, TAU, CHECKPOINT_SAVE_PATH, \ NOISE_STD, ACTOR_LEARNING_RATE, CRITIC_LEARNING_RATE from src.memory import ReplayBuffer from src.network import ActorNet from src.network import Cri...
src/agent.py
Apache-2.0
4,397
2484eec6304f9f2534c77e77de1a81b0027b0a4c
Python
py
# /* # # MIT License # # Copyright (c) 2021 AI4Finance # # Author: Berend Gort # # Year: 2021 # # GitHub_link_author: https://github.com/Burntt # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Softwa...
finrl_meta/env_crypto_trading/alpaca_paper_trade_multicrypto.py
MIT
10,870
29cbd9721025f8168c04ffdef8485991c21335eb
Python
py
import math import torch import numpy as np import matplotlib as mpl from matplotlib import pyplot as plt from matplotlib.collections import EllipseCollection import sys import os import pickle def save(simu, frames, attributes, attributes_alltimes, Nsaved=None, save_file=True, file_name="data"): """Basi...
sisyphe/display.py
MIT
23,641
7075e22401621713be70eddda935145605f53e97
Python
py
# # Copyright (c) 2019 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...
distiller/apputils/image_classifier.py
Apache-2.0
51,382
cc0a2ca1473f8e522acd22cecef7936e6f275129
Python
py
#!/usr/bin/env python3 # coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University 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 c...
examples/pplm_clickbait/run_gen_while.py
Apache-2.0
9,951
5f21fa4952efbcfbb3de7c65f8e55e0f64227046
Python
py
import numpy as np import torch import PIL.Image from collections import OrderedDict # global variable for holding a persistent single copy of a model netNetwork = None class Network(torch.nn.Module): def __init__(self, pretrained_hed=True): super(Network, self).__init__() self.netVggOne = torch....
lib/hed_pytorch/hed.py
Apache-2.0
6,551
650cbefbdf30ab5cf55c02d9236da486868acfd4
Python
py
import re from itertools import chain from torch.nn import Module, Conv2d, ConvTranspose2d def count_parameters(module: Module): """ Counts the number of learnable parameters in a Module """ return sum(p.numel() for p in module.parameters() if p.requires_grad) def count_conv2d(module: Module): ...
dense/utils.py
MIT
1,041
1e0ec2bd3b7d545b7b4f31ab917fe12f64f2bd62
Python
py
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ## Created by: Hang Zhang ## ECE Department, Rutgers University ## Email: zhang.hang@rutgers.edu ## Copyright (c) 2017 ## ## This source code is licensed under the MIT-style license found in the ## LICENSE file in the root directory of this sou...
hzproc/__init__.py
MIT
1,792
29cc86fa56deaedc00f364d338d6b1e47139eb63
Python
py
import getopt import random import sys from collections import deque # make sure the root path is in system path from pathlib import Path from flatland.envs.malfunction_generators import malfunction_from_params, MalfunctionParameters base_dir = Path(__file__).resolve().parent.parent sys.path.append(str(base_dir)) im...
baselines/torch_training/training_navigation.py
MIT
8,536
5ed2bd1e3bcbafbda72aff86932cc15e318b1789
Python
py
import torch import utils class Agent: """An abstraction of the behavior of an agent. The agent is able: - to choose an action given an observation, - to analyze the feedback (i.e. reward and done state) of its action.""" def __init__(self, env_id, obs_space, model_dir, argmax=False, num_envs=1): ...
utils/agent.py
MIT
2,077
29ccbefa3e6a41c5c43b1731c6577edfcd059ec3
Python
py
import pickle import shutil import pytest import pytorch_lightning as pl from pytorch_lightning.callbacks import EarlyStopping from pytorch_lightning.loggers import TensorBoardLogger from test_models.conftest import make_dataloaders from torch.optim import AdamW from pytorch_forecasting.metrics import MAE, CrossEntro...
tests/test_models/test_mlp.py
MIT
3,324
e92d2855d4e61d3a12531fdd35e7c4571ce4a0e6
Python
py
import math import numbers import warnings from enum import Enum from typing import List, Tuple, Any, Optional import numpy as np import torch from PIL import Image from torch import Tensor try: import accimage except ImportError: accimage = None from ..utils import _log_api_usage_once from . import function...
torchvision/transforms/functional.py
BSD-3-Clause
62,349
7c6aee1f3767c3abd6a9bd0c26e76062bb77cb6a
Python
py
''' Now that we have trained a VAE model wioth normalizing flows, we want to evalueate it in some way. We estimate the probability of data under the model using an importance sampling technique. We can write the marginal likelihood of a datapoint as: log p_theta(x) = log E_q [p_theta(x,z) / q_phi(z|...
evaluation_trained_model.py
MIT
4,144
80181ad3e0230fe42c78e770313817a103b80a2c
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ COCO dataset which returns image_id for evaluation. Mostly copy-paste from https://github.com/pytorch/vision/blob/13b35ff/references/detection/coco_utils.py """ from pathlib import Path import torch import torch.utils.data import torchvision f...
detr/datasets/coco.py
Apache-2.0
5,258
29cceedc67c9eed3ac960ee145a46a0acfeb0644
Python
py
#!/usr/bin/env python # coding=utf-8 # This file is copied from torchvision.models from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch.nn as nn from . import utils class Segnet(nn.Module): def __init__(self, in_channels, num_classes, stride, ...
libs/nets/segnet.py
Apache-2.0
1,230
29cd023d601ee36df2ae784026a952552d008a6a
Python
py
import torch import torch.nn as nn from torch.distributions import MultivariateNormal import gym import numpy as np device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class Memory: def __init__(self): self.actions = [] self.states = [] self.logprobs = [] self.r...
PPO_continuous.py
MIT
8,169
29cd21e22f4a6c7f67358f9577a9d32a49e9cc0d
Python
py
import os import sys sys.path.append('./../') import common.pytorch as pt import torch import torchvision def main(): #define the imagenet resnet50 ori_save_pth = '/gmodel/admin/PyTorch_IR/vv1/resnet50.pth' # model = torchvision.models.resnet50(pretrained=True) # torch.save(model, ori_save_pth) #co...
model-exchange/test/pytorch_test.py
OML
1,671
1e171f11534da6642e5d080ae1b5d0f0a1c4d937
Python
py
import logging import torch class DropBlock(torch.nn.Module): def __init__(self, block_size=7, keep_prob=0.9, current_step=0., train_steps=1.): super(DropBlock, self).__init__() self.block_size = block_size self.keep_prob...
layers/dropblock.py
MIT
2,573
29cd41e194e0d0d4e3c0354f52732b45085fbbb2
Python
py
import cv2 import torch import tqdm import os import numpy as np import pickle from data.coco_pose.ref import ref_dir, flipRef from utils.misc import get_transform, kpt_affine, resize from utils.group import HeatmapParser from util import draw_limbs import matplotlib.pyplot as plt valid_filepath = ref_dir + '/validati...
test.py
BSD-3-Clause
9,471
1e78cffcb8713da99b18ff0b2dc0e18b0bb2d764
Python
py
import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torch.utils.data as data from torch import optim from torchvision import datasets, transforms import numpy as np import random import sys import argparse import logging import os import time from dataset.cifar10 import get_dataset sys.pa...
cifar10/train.py
MIT
21,553
29cd447bf6c8a174a03c2ba1f356332427dec332
Python
py
import torch from torch.utils.data import Dataset, DataLoader from torch.nn.utils.rnn import pad_sequence import pickle import pandas as pd from tqdm import tqdm class IEMOCAPDataset(Dataset): def __init__(self, dataset_path, mode='train'): self.videoIDs, self.videoSpeakers, self.videoLabels, self.videoT...
bclstm/dataloader.py
MIT
5,034
29cd46befe926b6ee628c17e835895634c9be1b2
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from dataclasses import dataclass from typing import Union import torch @dataclass class DensePoseEmbeddingPredictorOutput: """ Predictor output that contains embedding and coarse segmentation data: * embedding: float tensor of size ...
projects/DensePose/densepose/structures/cse.py
Apache-2.0
1,398
fceeea5f8212b52df96a0433942e660f0b031d30
Python
py
from typing import Dict, Optional, Set, Union from pathlib import Path import torch from torch import quantization from catalyst.core import IRunner from catalyst.core.callback import Callback, CallbackOrder from catalyst.dl.utils import save_quantized_model class DynamicQuantizationCallback(Callback): """ ...
catalyst/dl/callbacks/quantization.py
Apache-2.0
4,916
29cd4ec53c12c23b92e2a396b85faa0a15f0babc
Python
py
import numpy as np import random import json import sys import torch import config from env import make_env import time import os import ann_th as ann import argparse from gym.wrappers import Monitor np.set_printoptions(precision=2) np.set_printoptions(linewidth=160) final_mode = True render_mode = False #final_m...
model_th.py
Apache-2.0
8,570
d7c136e076504afbb57dd56c1635b56441eae197
Python
py
import torch import torch.nn as nn import torch.nn.functional as F import json import math import numpy as np class Normalize(): def __init__(self, mean = (0.485, 0.456, 0.406), std = (0.229, 0.224, 0.225)): self.mean = mean self.std = std def __call__(self, img): imgarr = np.asarray(...
network/scalenet.py
MIT
7,318
6b1137f746ea487e381804e14b48c48390a23e94
Python
py
import datetime, time import os import numpy as np import torch import torchvision.utils as vutils from . import utils class Logger(object): def __init__(self, args): self.times = {'init': time.time()} self._checkPath(args) self.args = args self.printArgs() def printArgs(self):...
utils/logger.py
MIT
2,836
29cd5667d00d6f05e684db912ef461e977ff7deb
Python
py
import torch.nn as nn import torch.utils.checkpoint as cp from mmcv.cnn import (ConvModule, NonLocal3d, build_activation_layer, constant_init, kaiming_init) from mmcv.runner import _load_checkpoint, load_checkpoint from mmcv.utils import _BatchNorm from torch.nn.modules.utils import _ntuple, _trip...
mmaction/models/backbones/resnet3d.py
Apache-2.0
32,623
29cd93394be074f38a40405313549b8c395faebe
Python
py
import argparse import json import os import pickle import sys import sagemaker_containers import pandas as pd import torch import torch.optim as optim import torch.utils.data from model import LSTMClassifier def model_fn(model_dir): """Load the PyTorch model from the `model_dir` directory.""" print("Loading ...
Project/train/train.py
MIT
6,217
29cdb57faf5fd2738fc600f0e3569fd10fb8e2f3
Python
py
# -*- coding: iso-8859-15 -*- import collections import random import modeling, tokenization import numpy as np import torch from torch.utils.data import TensorDataset, DataLoader, SequentialSampler from torch.utils.data.distributed import DistributedSampler import matplotlib.pyplot as plt class TrainingInstance(ob...
pytorch_viz/transfer.py
Apache-2.0
16,621
29cdbb01e8919a12bcae73275cef655324e1ca81
Python
py
import copy import tempfile import unittest import torch from transformers import ( ADAPTER_CONFIG_MAP, ADAPTERFUSION_CONFIG_MAP, AdapterType, BertModel, DistilBertModel, PfeifferConfig, RobertaModel, XLMRobertaModel, ) from transformers.testing_utils import require_torch from .test_m...
tests/test_adapter_fusion_loading.py
Apache-2.0
6,343
4b5de5b9c9801aec880664291bae8420f47aec72
Python
py
from os.path import join as pjoin from os import mkdir import pytest import numpy as np from hangar import Repository try: import torch from torch.utils.data import DataLoader from hangar import make_torch_dataset skipTorch = False except ImportError: skipTorch = True @pytest.mark.skipif(skipTor...
tests/test_dataloaders.py
Apache-2.0
16,692
038e72282e8e35fd7095368e5b6c5a5e244aa90f
Python
py
#!/usr/bin/env python # -*- coding: utf-8 -*- #------------------------------------------------------ # @ File : demo_pipeline.py # @ Description: # @ Author : Alex Chung # @ Contact : yonganzhong@outlook.com # @ License : Copyright (c) 2017-2018 # @ Time : 2021/2/3 上午10:40 # @ Software : PyCh...
docs/demo_pipeline.py
Apache-2.0
8,742
a93b2026b39e41a92144f209c2f1e047acbcfa15
Python
py
import torch import torch.nn as nn from uer.layers import * from uer.layers.transformer import TransformerDecoderLayer from uer.layers.layer_norm import LayerNorm, T5LayerNorm from uer.layers.relative_position_embedding import RelativePositionEmbedding class TransformerDecoder(nn.Module): """ BERT encoder exp...
uer/decoders/transformer_decoder.py
MIT
3,300
10366372da9197784deb61d83e926ee4eb8b08c9
Python
py
# @Time : 2019-08-10 11:20 # @Author : Lee_zix # @Email : Lee_zix@163.com # @File : main.py # @Software: PyCharm """ The entry of the KGEvolve """ import argparse import itertools import os import sys import time import pickle import copy import dgl import numpy as np import torch from tqdm import tqdm impor...
src/ensemble.py
Apache-2.0
39,049
29cded363b6d74c4cd575b9410e89998cadc52cb
Python
py
# coding: utf-8 import argparse import time import math import os import torch import torch.nn as nn import torch.onnx import sys sys.path.append(os.path.abspath("..")) from utils import data_train from model import model parser = argparse.ArgumentParser(description='LSTM Reverse Language Model') parser.add_argument...
train/train_revLM.py
BSD-3-Clause
10,539
1ec30ec75b0ddf60e737370e7b80610ace81d60c
Python
py
import copy import numpy as np import torch import nemo.collections.asr as nemo_asr from omegaconf import OmegaConf from torch.utils.data import DataLoader from TheSoundOfAIOSR.stt.nemo.audio_data_layer import AudioDataLayer from TheSoundOfAIOSR.stt.nemo.audio_framer import FrameASR from TheSoundOfAIOSR.stt.nemo.st...
TheSoundOfAIOSR/stt/nemo/streaming_model.py
MIT
4,554
29ce1277b2b4f7260c68478c0d666e09086bd45f
Python
py
''' Incremental-Classifier Learning Authors : Khurram Javed, Muhammad Talha Paracha Maintainer : Khurram Javed Lab : TUKL-SEECS R&D Lab Email : 14besekjaved@seecs.edu.pk ''' from torchvision import datasets, transforms import torch import numpy as np # To incdude a new Dataset, inherit from Dataset an...
myData/iDataset.py
Apache-2.0
5,405
1e1a3f1f995695710eff1e60597c8d709aa09537
Python
py
# ------------------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # -------------------------------------------------------------------...
InnerEye/ML/configs/histo_configs/classification/BaseMIL.py
MIT
5,928
29ce29da8fef2b73e55640e3e287b1c168d5443e
Python
py
from __future__ import annotations import abc import torch import torch.nn as nn import transformers from jiant.ext.allennlp import SelfAttentiveSpanExtractor from jiant.shared.model_resolution import ModelArchitectures from jiant.tasks.core import TaskTypes from typing import Callable from typing import List """ ...
jiant/proj/main/modeling/heads.py
MIT
12,398
7c548d5e00a2b1f70a2db6c22ea436915d6a77a9
Python
py
# -------------------------------------------------------- # ScaleConvLSTM # Copyright (c) 2018 Fudan-VTS # Licensed under The MIT License [see LICENSE for details] # Written by liwenxi # -------------------------------------------------------- import torch from torch import nn, optim from torchvision import models fro...
Deep-Learning/ConvLSTM/ScaleConvLSTM/test.py
Apache-2.0
4,211
1e6b22ecdc453d1427d3d874999e760f6e5174c8
Python
py
import os import json import random from collections import defaultdict, Counter import torch import numpy as np from torch.utils.data import Dataset, DataLoader, Sampler from torchtext.vocab import Vocab, Vectors from torch.distributions.categorical import Categorical class MasterData(): def __init__(self, fil...
src/data/pubmed.py
MIT
7,028
7cb8637299413d5e345238ccd4c81595c9d6b741
Python
py
import torch import torch.distributions from torch.utils.data import DataLoader, Dataset import numpy as np import os from torchvision.datasets.folder import default_loader from scipy.io import loadmat import paths_config from .imagenet_augmentation import get_imageNet_augmentation FLOWERS_LABELS = [ ...
utils/dataloaders/flowers.py
MIT
4,538
5e6314a41477b4b1715aa8d5b4a5505c9894ea74
Python
py
import numpy as np import torchvision import torch import torch.nn as nn from torch.autograd import Variable import dataset import models import helpers from config import * assert(file_name == 'gan') writer, save_dir = helpers.init(gpu, file_name, experiment_name) discriminator = models.Discriminator().cuda() gener...
gan.py
MIT
4,534
b25844e81d4aff97c0abf11525cbd79a9d4a5656
Python
py
from six.moves import cPickle import numpy as np from torch.utils.data import DataLoader from torch.utils.data.dataset import Dataset import pandas as pd from tqdm import tqdm from joblib import Parallel, delayed def get_data(data_table,i): return np.load(data_table.loc[i]['input']) def load_dataset(data_path): ...
asr/util/librispeech_dataset.py
MIT
5,666
29cf2e4692420c5016746de5d4c5cf67ebe4093b
Python
py
from __future__ import absolute_import # -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Sean Bell # -------------------------------------------------------- # ---------------...
lib/model/rpn/proposal_layer.py
MIT
8,416
454c6c3dbc8085d741c51853b43585953b7058d9
Python
py
"""Regression trainer/evaluator implementation module.""" import logging from typing import AnyStr # noqa: F401 import numpy as np import torch import torch.optim import thelper.concepts import thelper.typedefs as typ # noqa: F401 import thelper.utils from thelper.train.base import Trainer logger = logging.getLogg...
thelper/train/regr.py
Apache-2.0
8,096
1ec5b1f96f8f73837be58a4cbbdc7e132e98e732
Python
py
# Copyright (c) 2019 Microsoft Corporation. # Copyright (c) 2018 Ricky Tian Qi Chen # Licensed under the MIT license. import torch import lib.dist as dist from lib.adapters import LpNestedAdapter import vae_quant import ast def parseISA(isalist): print(isalist) pnested = [] pnested.append(isalist[0]) ...
lpnested-vae-learn-exponents/metric_helpers/loader.py
MIT
2,909
29cf74bbf9fc9829a4863993e4beb94ca289e482
Python
py
""" as for test_rnn_memorization.py, but this time the sender, not the receiver same idea: train supervised, and compare compositional vs non-compoisitoinal grammars """ import time import random import torch from torch import optim import torch.nn.functional as F import numpy as np from ulfs import rl_common from u...
mll/run_mem_send.py
MIT
14,370
29cf8450127153834feb8ac76fc2a3760ac29e0c
Python
py
''' Goal1: a GRU where the weight matrices have a block structure so that information flow is constrained Data is assumed to come in [block1, block2, ..., block_n]. Goal2: Dynamic parameter sharing between blocks (RIMs) ''' import torch import torch.nn as nn from .GroupLinearLayer import GroupLinearLayer from ....
modular_dynamics/utilities/BlockGRU.py
MIT
5,005
80550b91556e6f467f9b7c717176825f6ed44e8b
Python
py
#!/usr/bin/env python # coding=utf-8 ################################################################################ import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical ################################################################################ class MLP...
model.py
MIT
3,002
108c428d69075e67b62939e9ad65f95edf37ef10
Python
py
from typing import Any, Dict, List, Optional, Tuple, Type, Union import numpy as np import gym import torch as th import torch.nn.functional as F from torch import nn from torch.distributions import MultivariateNormal from stable_baselines3.common.policies import BaseModel, BasePolicy, ContinuousCritic, regi...
custom_algos/d3pg/policies.py
MIT
16,597
7cdb372ded8f8abab69394b54f919f2c359427f9
Python
py
from torch.autograd import Variable import warnings warnings.filterwarnings("ignore") import torch import torch.optim as optim from datetime import datetime, timedelta from torch.utils.data import DataLoader import torch.nn as nn from data.dataset import NCPDataset, NCP2DDataset, NCPJPGDataset, NCPJPGDataset_new, NCP...
validation.py
MIT
7,370
29cfbedc007e763b33c5b66bc3cfe0ed28a40c2a
Python
py
from __future__ import print_function, division import sys import os import torch import numpy as np import random import csv import itertools from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils from torch.utils.data.sampler import Sampler from pycocotools.coco import COCO impo...
retinanet/dataloader.py
Apache-2.0
19,097
7018d322e38debbf63ca62c810bf8422e307e252
Python
py
import torch.nn as nn import torch.nn.functional as F class CNN(nn.Module): """ CNNモデルクラス """ def __init__(self, num_classes=10, **kwargs): super(CNN, self).__init__() self.conv1 = nn.Conv2d(in_channels=1, out_channels=8, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) self....
nn_lesson/model/cnn.py
MIT
864
ff826e93b7845a3a682fe6d7ab843d0aba35bec6
Python
py