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
# 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. # # Description: generate inputs and targets for the dlrm benchmark # The inpts and outputs are generated according to the following three opti...
dlrm_data_pytorch_class.py
MIT
43,421
5ec3348822d02e4f6d957f7191cf8250b351d309
Python
py
from __future__ import division import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import cv2 import matplotlib.pyplot as plt try: from util import count_parameters as count from util import convert2cpu as cpu from util import predic...
yolo/darknet.py
Apache-2.0
18,592
12d17ecd1665eb9e1f6dca5533a30b51f452aaae
Python
py
import torch.distributed as dist def get_world_size(): if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() def reduce_mean(tensor): ''' Reduce the tensor across all machines, the operation is in-place. :param tensor: tenso...
src/CGDs/distributed.py
MIT
597
dfb0cc090a5ed5cfbcd0acda2a331cb4c96fb11a
Python
py
import torch as ch import numpy as np import torch.nn as nn from torch.optim import SGD, lr_scheduler from torchvision.utils import make_grid from cox.utils import Parameters from .tools import helpers from .tools.helpers import AverageMeter, calc_fadein_eps, \ save_checkpoint, ckpt_at_epoch, has_attr from .to...
robustness/train.py
MIT
19,658
5fb0cdd5df81f01fb370970dacde6847f99cde27
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 io import logging import os import pickle import random import socket import struct import subprocess import warnings from argparse imp...
fairseq/distributed/utils.py
MIT
29,693
29ddd75984bf45b5047b0f50e9d28471547bbacf
Python
py
import math import torch import stable_nalu import argparse # Parse arguments parser = argparse.ArgumentParser(description='Runs the simple function static task') parser.add_argument('--layer-type', action='store', default='NALU', choices=list(stable_nalu.ne...
experiments/simple_function_recurrent.py
MIT
5,447
df9a05dd7004c639a372bd89b24f13f738f53f5f
Python
py
#!/usr/bin/env python # coding=utf-8 # Copyright The HuggingFace Team and The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.ap...
examples/pytorch/multiple-choice/run_swag.py
Apache-2.0
18,991
29ddd9475459640e7e650b4badbcd5e26e436cf3
Python
py
# Code mainly from: https://github.com/lucidrains/stylegan2-pytorch/blob/master/stylegan2_pytorch/stylegan2_pytorch.py from einops import rearrange from functools import partial from kornia.filters import filter2d from math import log2, sqrt from random import random from stylegan2_deepspeed.diff_augment import DiffAu...
stylegan2_deepspeed/stylegan2.py
MIT
16,053
1e57421be1d41e86b3749940447b5470c911ea0c
Python
py
# Compatability Imports from __future__ import print_function from os.path import join try: import tensorflow as tf except: print('Tensorflow could not be imported, therefore tensorboard cannot be used.') from io import BytesIO import matplotlib.pyplot as plt import numpy as np import torch import datetime c...
tb_logger.py
MIT
4,617
10cf3ee9bd57bbb6729dc95240885521ee0dc747
Python
py
import torch import torch.nn as nn import torch.utils.model_zoo as model_zoo import os import sys model_urls = { 'imagenet': 'http://data.lip6.fr/cadene/pretrainedmodels/inceptionresnetv2-520b38e4.pth' } class BasicConv2d(nn.Module): def __init__(self, in_planes, out_planes, kernel_size, stride, padding=0):...
fastai/models/inceptionresnetv2.py
Apache-2.0
11,330
29de01ef44e89f03a970ff96b0b04ba932bec3a4
Python
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # PROGRAMMER: Johannes SB # DATE CREATED: 05/20/21 # REVISED DATE: # PURPOSE: # Provides a image processing function to bring input image in the right format # for the model ## # Imports python modules import torch import numpy as np from PIL import Image def proces...
process_image.py
MIT
2,003
29de04b1d3e20e7fc1d407b028f17e40c58c96b8
Python
py
# Tensorflow solely for the Progress Bar (totally worth it) from .utilities import ProgressBar from .move_selection import get_next_move_training import torch import numpy as np import re from .utilities import ( config, BOARD_SHAPE, product ) def training_loop(model, optimizer, num_games, device, off_policy = l...
pytorch-implementation/lib/training.py
MIT
3,247
3437fc041194834886a5cb15379816ff5a03b037
Python
py
from dataloaders.datasets import cityscapes, coco, combine_dbs, pascal, sbd, apollo, farsight from torch.utils.data import DataLoader, random_split def make_data_loader(args, **kwargs): if args.dataset == 'pascal': train_set = pascal.VOCSegmentation(args, split='train') val_set = pascal.VOCSegment...
dataloaders/__init__.py
MIT
4,571
f9a05556d27c560e6d12e5844d5c076950fb8e1b
Python
py
import torch import torch.nn as nn from transformers.modeling_bart import BartForConditionalGeneration from relogic.logickit.dataflow.semtransparse.grammar.keywords import SKETCH_KEYWORDS, KEYWORDS import logging import os logger = logging.getLogger(__name__) WEIGHTS_NAME = "pytorch_model.bin" class SQL2TextModel(nn....
relogic/pretrainkit/models/sql_to_text.py
Apache-2.0
2,972
29de2dcd5061c692574fd20150bf41d9d5826422
Python
py
import os import json from pathlib import Path from contextlib import nullcontext # Set up logging import sys import logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], level=logging.WA...
seq2seq/eval_all.py
Apache-2.0
13,613
29de346b2fde7deb76f0f5f0bfc3a36d24ccbb37
Python
py
from torch.utils.data.sampler import Sampler from torch.utils.data import Dataset, DataLoader from utils.dsp import * from utils import hparams as hp from utils.files import unpickle_binary from utils.text import text_to_sequence from pathlib import Path import random #################################################...
utils/dataset.py
MIT
8,730
29de494c355dcf5615a02a17b434720aef667a1b
Python
py
import os import torch import numpy as np from torch.utils.data import Dataset, DataLoader import torch.nn as nn import pickle from tqdm import tqdm import argparse import operator from torch.nn import functional as F from dataloader import DatasetWebQSP, DataLoaderWebQSP from model import RelationExtractor from torch....
KGQA/RoBERTa/main.py
Apache-2.0
20,945
28f1092a8395ad189c15820aa58ae2b3af5f65b3
Python
py
import datetime import os import time import warnings import presets import torch import torch.utils.data import torchvision import transforms import utils from torch import nn from torch.utils.data.dataloader import default_collate from torchvision.transforms.functional import InterpolationMode try: from torchv...
references/classification/train.py
BSD-3-Clause
21,499
29de4fce91ce201e5d4ce58c811c767f52b04e40
Python
py
from typing import Callable, Sequence from functools import partial from operator import itemgetter import torch from keyedtensor import KeyedTensor def _many_to_one(keyedtensors: Sequence[KeyedTensor], op: Callable, dim: int) -> KeyedTensor: keys = list(keyedtensors[0]) getter = itemgetter(*keys) op =...
src/keyedtensor/ops.py
MIT
2,915
28f74e67d6feea0898eb88d25f1d7aa931e608d1
Python
py
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """SSD 300 utils adapted from MLCommons. Based on MLCommons Reference Implementation `here`_ .. _here: https://github.com/mlcommons/training/tree/master/single_stage_detector/ssd """ import itertools import random from math import sqrt...
composer/models/ssd/utils.py
Apache-2.0
15,692
5ea8421475da1563850d9b23e9af8c73acde4ec3
Python
py
# pip3 install transquest # python3 evaluate_transquest.py --testset data/ro-en/dev --checkpoint TransQuest/monotransquest-da-ro_en-wiki # python3 evaluate_transquest.py --testset data/et-en/dev --checkpoint TransQuest/monotransquest-da-et_en-wiki import torch from transquest.algo.sentence_level.monotransquest.run_mod...
scripts/evaluate_sentence_level_transquest.py
MIT
1,512
45c3b88016c6bfd69a83e4d2d6f6a6f16cec0b4e
Python
py
# Owner(s): ["module: unknown"] import torch from torch.testing._internal.common_utils import TestCase, run_tests class TestSetDefaultMobileCPUAllocator(TestCase): def test_no_exception(self): torch._C._set_default_mobile_cpu_allocator() torch._C._unset_default_mobile_cpu_allocator() def test...
test/test_set_default_mobile_cpu_allocator.py
Intel
977
29dea32f5a88c0d032fd16a95b5c9766f1a6a907
Python
py
import gym import numpy as np import time import os import cv2 import matplotlib.pyplot as plt from IPython.display import clear_output from collections import deque import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from qnetwork import QNetwork from replay_buffer impor...
Value_Based/Double_Duel_Noisy_C51_MultiTD_1dim/agent.py
MIT
13,330
b2b941daee33d623f9154812a3dd24c455526dfc
Python
py
import collections import sys import os this_path = os.path.dirname(os.path.realpath(__file__)) root_path = os.path.abspath(os.path.join(this_path, os.pardir)) sys.path.append(root_path) from datasets import captioning, gpt2, bert, vggpt2, resgpt2, light from utilities.evaluation import sanity from utilities.evaluat...
src/models/eval.py
MIT
29,349
29deb58b95bff98c4afa111e3a8550810717ef12
Python
py
# python: 3.6 # encoding: utf-8 import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.init import xavier_uniform_ from fastNLP.modules.utils import initial_parameter class ConvMaxpool(nn.Module): """ Convolution and max-pooling module with multiple kernel sizes. """ def __i...
fastNLP/modules/encoder/conv_maxpool.py
Apache-2.0
1,890
42994bcd0168c4d572475c637d73cbd9e2c97517
Python
py
from __future__ import absolute_import, division, print_function, unicode_literals from abc import ABCMeta, abstractmethod from six import add_metaclass from itertools import combinations from boltons.cacheutils import LRU import numpy as np from scipy.ndimage import zoom from scipy.special import logsumexp from tqd...
pysaliency/models.py
MIT
27,276
5eb729b1d783753341ad90bed3ee7d69ced18d38
Python
py
"""This module contains simple helper functions """ from __future__ import print_function import os import numpy as np import torch from PIL import Image def tensor2im(input_image, imtype=np.uint8): """"Converts a Tensor array into a numpy image array. Parameters: input_image (tensor) -- the input...
util/util.py
MIT
3,348
29df08fb2c0b85c4b1ffdb3c2e0c5d8e26209550
Python
py
# Copyright 2020 MONAI Consortium # 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, s...
tests/test_bilateral_approx_cuda.py
Apache-2.0
13,113
5ea0d997d1e1b68fd8c69912242ed57c4f5f2beb
Python
py
''' Example shows how to compute combined softmax for multilabel multivalue setting. ''' import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np # in one output (6 dim vector) we want to encode 2 features and level of its expression # each feature is represen...
softmax_accuracy.py
MIT
1,632
45cecde7f3b1a08457731a4211a571f5babae117
Python
py
#!/usr/bin/env python """Train models.""" import os import signal import torch import onmt.opts as opts import onmt.utils.distributed from onmt.utils.misc import set_random_seed from onmt.utils.logging import init_logger, logger from onmt.train_single import main as single_main from onmt.utils.parse import ArgumentPa...
train.py
MIT
6,939
12cee32f3b41d4d04c81f85bb676ab654db510a7
Python
py
import numpy as np import torch from torch import nn import scipy import tensorly as tl from tensorly.decomposition import parafac from tensorly.kruskal_tensor import kruskal_to_tensor from musco.pytorch.compressor.rank_selection.estimator import estimate_rank_for_compression_rate tl.set_backend('pytorch') class ...
musco/pytorch/compressor/decompositions/cp4.py
BSD-3-Clause
7,302
29df24f8efdf0c3f2c9b7dc6bffb965180869615
Python
py
from __future__ import absolute_import import math import torch.nn as nn __all__ = ['oresnet'] def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(n...
CIFAR10/models/cifar/oresnet.py
MIT
4,493
4b76579eaa05a82be921f77501b8012a45df60fe
Python
py
import argparse import os import warnings import mmcv import torch from mmcv import Config, DictAction from mmcv.cnn import fuse_conv_bn from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import (get_dist_info, init_dist, load_checkpoint, wrap_fp16_model) fro...
detection/test.py
Apache-2.0
8,326
52c88faa31a7b997b0dc8fe36b01c49932c754be
Python
py
# AI for Self Driving Car # Import libraries import numpy as np import random import os import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.autograd as autograd from torch.autograd import Variable # Create architecture of NN class Network(nn.Mo...
AI - Virtual Self Driving Car/aicustom.py
MIT
4,145
29df5576a93b6fc7dd7b509aefceb6a969070ce7
Python
py
from gaussed.solver.base import Solver from gaussed.utils.matrix_sqrt import sqrtm, svd_sqrtm from gaussed.utils.safe_svd import svd_safe, svd_clip from gaussed.utils.nearest_spd_matrix import nearestSPD import torch from torch import cholesky, cholesky_solve class LinearSolver(Solver): def __init__(self): ...
src/gaussed/utils/lin_alg_solvers.py
MIT
6,358
cc02954775328b649210ffc4595d258cf883a4b3
Python
py
import torch import torch.nn as nn from collections import defaultdict from models.yolo_layer import YOLOLayer from torch.autograd import Variable import numpy as np def add_conv(in_ch, out_ch, ksize, stride): """ Add a conv2d / batchnorm / leaky ReLU block. Args: in_ch (int): number of input chan...
models/yolov3.py
MIT
24,957
29df5f02f68f9ef90db915feb698a5786c0aac85
Python
py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import Dict, Union import torch from pytext.common.constants import Stage from pytext.config.component import create_trainer from pytext.data.bert_tensorizer import BERTTensorizer from pytext.data.data import Data...
pytext/task/tasks.py
BSD-3-Clause
13,093
3448c270a8e2f2aead943a46b815dfd40d1d65f5
Python
py
from DataLoad.Instance import * from wt_DataUtils.UniversalData import char_pad import torch import re import os torch.manual_seed(seed_num) random.seed(seed_num) class DataLoadHelp(object): @staticmethod def _clean_str(string): """ Tokenization/string cleaning for all datasets except for SST...
DataLoad/DataLoad_NER.py
Apache-2.0
5,028
52bee45668ac72479b2cfc7502ef5850562eaa30
Python
py
# -------------------------------------------------------- # Pytorch multi-GPU Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Thomas Balestri; based off Ross Girshick # -------------------------------------------------------- from __future__ import absolute_import from __future__ i...
trainval_net.py
MIT
16,771
29dfb85d4b19d5486c8024cddb289c47bb092949
Python
py
import math import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from a2c_ppo_acktr.utils import AddBias # TODO: In order to make this code faster: # 1) Implement _extract_patches as a single cuda kernel # 2) Compute QR decomposition in a separate process # 3) Actually make ...
a2c_ppo_acktr/algo/kfac.py
MIT
7,731
12efb6f57c29330794946854508bf0fdb6455e11
Python
py
# SPDX-FileCopyrightText: Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of sourc...
rsl_rl/algorithms/ppo.py
BSD-3-Clause
9,046
29dfbf74c9e6b1579857aca551d05f4f4a63c494
Python
py
""" This file contains specific functions for computing losses of FCOS file """ import torch from torch.nn import functional as F from torch import nn import os from ..utils import concat_box_prediction_layers from paa_core.layers import IOULoss from paa_core.layers import SigmoidFocalLoss from paa_core.modeling.match...
paa_core/modeling/rpn/fcos/loss.py
BSD-2-Clause
11,302
29dfc9b5647fdba90bb3e35f7fcc30b0dd53e099
Python
py
from src.utils import loaders from src import algorithms, model from . import cmd, document_parser from runners.experiment_utils import load_experiment import inspect import numpy as np import os import matplotlib.pyplot as plt from argparse import ArgumentParser import logging import torch def visualize(path_to_yml_f...
scripts/visualize.py
MIT
4,547
12c66ffc7c7278a0ffa42f0c5ad71ec6876113b4
Python
py
import torch import os import PIL from ncsnv2.datasets.vision import VisionDataset from ncsnv2.datasets.utils import download_file_from_google_drive, check_integrity class CelebA(VisionDataset): """`Large-scale CelebFaces Attributes (CelebA) Dataset <http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html>`_ Dataset. ...
ncsnv2/datasets/celeba.py
MIT
7,886
5fb753a436d7fa9d75f8196eb9fe29d4b703023a
Python
py
import torch import argparse import sys import logging import time from botorch.models.contextual_multioutput import LCEMGP from gpytorch.mlls import ExactMarginalLogLikelihood from botorch import fit_gpytorch_model from botorch.optim.fit import fit_gpytorch_torch from botorch.acquisition.objective import LinearMCObje...
contextualbo_experiments/cbo_experiment.py
Apache-2.0
10,020
29e00a1fe77362c1ac768a16ce5a9a64bf9be4ef
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/data/audio_to_label.py
Apache-2.0
9,743
7c740f4bb57bc94bb35c22c6574aff272c51b46a
Python
py
from typing import Any from typing import Dict from typing import List from typing import Optional from typing import Union import pandas as pd from etna import SETTINGS from etna.datasets.tsdataset import TSDataset from etna.loggers import tslogger from etna.models.base import Model from etna.models.base import log_...
etna/models/nn/deepar.py
Apache-2.0
5,688
340a84059154bf2dac776ee552ca086eaa7a9b46
Python
py
import os import torch import pytorch_lightning as pl from torchvision.datasets import MNIST from torchvision import transforms from typing import Optional from torch.utils.data import DataLoader, random_split class MNISTDataModule(pl.LightningDataModule): """LightningDataModule implementation of MNIST dataset. ...
src/datasets/mnist_data.py
Apache-2.0
3,516
7054767d6d1bccf641881a9ca7b7e7a55049845d
Python
py
import os import torch import torchvision import argparse from tensorboardX import SummaryWriter apex = False try: from apex import amp apex = True except ImportError: print( "Install the apex package from https://www.github.com/nvidia/apex to use fp16 for training" ) from model import load_m...
main.py
MIT
3,498
29e09865c4e75e8e34b1cef72cb7b4435d682388
Python
py
import numpy as np from torch import nn from torch import autograd import torch import os class Concat_embed(nn.Module): def __init__(self, embed_dim, projected_embed_dim): super(Concat_embed, self).__init__() self.projection = nn.Sequential( nn.Linear(in_features=embed_dim, out_featu...
utils.py
MIT
3,386
5e78d33e6c81d08359f77d7f8c78267659cadae4
Python
py
import torch import torch.nn as nn from dtln_utils.custom_layers import CausalConv1d class DTLN(nn.Module): """ Dual-Signal Transformation Long Short-Term Memory Network. Similar architecture as presented by N. Westhausen et. al for the DNS INTERSPEECH 2020: https://www.isca-speech.org/archive/Inter...
recipes/experiments_dtln/leakage_rm/dtln_fix_aec.py
MIT
17,714
29e0bb8ef6c60b05714b2a461f54a8d1cde1d7a4
Python
py
import argparse import time import datetime import torch import torch_ac import tensorboardX import sys import inspect import utils from model import ACModel import gym_minigrid.envs as minigrid_envs import random # Parse arguments parser = argparse.ArgumentParser() ## General parameters parser.add_argument("--algo"...
scripts/train.py
MIT
8,984
4b65746fe430f109c282c23a4023b8030459ca2a
Python
py
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ## Created by: Albert Berenguel ## Computer Vision Center (CVC). Universitat Autonoma de Barcelona ## Email: aberenguel@cvc.uab.es ## Copyright (c) 2017 ## ## This source code is licensed under the MIT-style license found in the ## LICENSE file...
model/matching-net-classifier.py
MIT
3,167
d7e46b7c26e4e3dbb94ac643edb8ae50ba32bbe1
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from maskrcnn_benchmark.structures.bounding_box import BoxList ## transpose #FLIP_LEFT_RIGHT = 0 #FLIP_TOP_BOTTOM = 1 #class BoxList(object): #""" #This class represents a set of bounding boxes. #The bounding boxes are r...
fcos_core/structures/bounding_box.py
BSD-2-Clause
9,938
29e0dee21b46b2db7043e2efc0ad87c62733b379
Python
py
import torch import typing from ..core.transforms_interface import BaseWaveformTransform class PeakNormalization(BaseWaveformTransform): """ Apply a constant amount of gain, so that highest signal level present in each audio snippet in the batch becomes 0 dBFS, i.e. the loudest level allowed if all sampl...
torch_audiomentations/augmentations/peak_normalization.py
MIT
2,557
804b7f5254c254ff0320d281688898934e7ebe76
Python
py
import glob import os from pathlib import Path from typing import Callable, List, Optional import torch from torch_geometric.data import (Data, InMemoryDataset, download_url, extract_tar) from torch_geometric.utils import remove_isolated_nodes class MalNetTiny(InMemoryDataset): ...
torch_geometric/datasets/malnet_tiny.py
MIT
3,603
29e0f1942cd6c9e822ab4a8ce7ea577d17ae461d
Python
py
import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical from common.utils import init class CategoricalAC(nn.Module): def __init__(self, base, recurrent, num_actions): """ embedder: (torch.Tensor) model to extract the embedding for observation - probably a...
common/actor_critic.py
MIT
1,766
703b2e178dfc582d43a9a15235386cc883ec6042
Python
py
import argparse import math import os import random as rn import shutil import subprocess import h5py import librosa import matplotlib as mpl mpl.use('Agg') import matplotlib.animation as manimation import matplotlib.pyplot as plt import numpy as np from tqdm import tqdm import torch import torch.nn ...
generate.py
MIT
6,984
29e0fa067ec91a74bc0ec230b60356869b730043
Python
py
import inspect import torch.nn as nn from .misc import is_tuple_of from ..common.registry import NORM_LAYERS NORM_LAYERS.register_module('BN', module=nn.BatchNorm2d) NORM_LAYERS.register_module('BN1d', module=nn.BatchNorm1d) NORM_LAYERS.register_module('BN2d', module=nn.BatchNorm2d) NORM_LAYERS.register_module('BN3d...
examples/ASSA/module/common/norm.py
MIT
6,238
29e1004dce3b1057f074e7cd4837cff024091a04
Python
py
r""" This package adds support for CUDA tensor types, that implement the same function as CPU tensors, but they utilize GPUs for computation. It is lazily initialized, so you can always import it, and use :func:`is_available()` to determine if your system supports CUDA. :ref:`cuda-semantics` has more details about wo...
torch/cuda/__init__.py
Intel
23,938
29e112fc67abd9a43cb4ac78a8d434c48b14be16
Python
py
# -*- coding: utf-8 -*- """ @date: 2020/9/20 下午4:23 @file: tsm_recognizer.py @author: zj @description: """ import torch import torch.nn as nn from tsn.model import registry from tsn.model.backbones.build import build_backbone from tsn.model.heads.build import build_head from .temporal_shift import make_temporal_shi...
tsn/model/recognizers/tsm_recognizer.py
Apache-2.0
848
7c80f957dd45f526676b5003c5e70753c86844ae
Python
py
import torch.nn as nn import math import torch.utils.model_zoo as model_zoo from modeling.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d webroot = 'https://tigress-web.princeton.edu/~fy/drn/models/' model_urls = { 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', 'drn-c-26': we...
modeling/backbone/drn.py
MIT
14,649
29e11e065b258e43d4a9ca1e671b8f5af4ae62c6
Python
py
import itertools import logging import math import os from collections import OrderedDict import torch from torch import nn, optim from torch.nn.functional import kl_div, softmax, log_softmax from tqdm import tqdm from theconf import Config as C, ConfigArgumentParser from common import get_logger from data import ge...
train.py
Apache-2.0
10,179
fdfeb6a5d1bd254e511d5c696cb2a2205947e9e1
Python
py
# Copyright (c) Chris Choy (chrischoy@ai.stanford.edu). # # 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 Software without restriction, including without limitation the rights to # use, copy, modify, ...
models/examples/indoor.py
MIT
5,909
29e129c2a9e0d59ef823f86cfc389e23798f0bd3
Python
py
from gehm.utils.np_distances import * from tests.test_data import create_test_data import pytest import numpy as np import torch from numpy import cos, sin @pytest.mark.distances def test_nx_second_order_proximity(create_test_data): G,G_undir=create_test_data nodes=np.array(G.nodes) # Te...
tests/test_np_distances.py
MIT
7,605
29e12c7a6308a409cb7f250cbecb68ff20a73b65
Python
py
import torch.nn as nn class ResNetLoss(nn.Module): def __init__(self, loss_type="ce"): super().__init__() self.loss_type = loss_type if loss_type == "ce": self.loss = nn.CrossEntropyLoss() elif loss_type == "bce": self.loss = nn.BCELoss() def forward(s...
src/criterion.py
MIT
631
10f2045edf620da4229737bba9da96377cc29ae7
Python
py
import torch from torch.utils.data import DataLoader, Dataset class CategoryDataset(Dataset): def __init__(self, id_list, digit1_list, digit2_list, digit3_list, text_obj_list, text_mthd_list, text_deal_list): self.id_list = id_list self.digit1_list = digit1_list self.digit2_list = digit2_li...
main.py
MIT
2,793
037fe9a1dbb19aed58b3e245b34f97e1fac20be1
Python
py
import numpy as np import torch from common.logging.console_loger import ConsoleLogger from services.text_extraction.application.ai.model import BERTBaseUncased from services.text_extraction.application.ai.training.src.dataset import TextExtractionDataset from services.text_extraction.application.ai.training.src.prepr...
backend/services/text_extraction/application/ai/inference/prediction_manager.py
MIT
6,588
29e15e20b950dc5293e8ffe5672248baaf64aa21
Python
py
import torch from torch import nn, Tensor from torch.nn import functional as F from allennlp.data.vocabulary import Vocabulary from allennlp.models import Model from allennlp.modules import Seq2SeqEncoder, InputVariationalDropout, TimeDistributed from allennlp.nn import InitializerApplicator from allennlp.training.metr...
models/my_model/base_model.py
MIT
17,864
4b3c6f3d75d686789d46d56d7e7d6d750fa4bb33
Python
py
from abc import ABC, abstractmethod import torch import torch.nn as nn import numpy as np from typing import Optional, Union, List, Dict, Iterator, Tuple from lifelong_methods.models.resnetcifar import ResNetCIFAR from lifelong_methods.models.resnet import ResNet from lifelong_methods.utils import get_optimizer from i...
lifelong_methods/methods/base_method.py
MIT
13,163
29e165b83c21a6fce8f29036bfd1782a8a25cc55
Python
py
import os import random import numpy as np from PIL import Image, ImageFile from torch.utils.data import Dataset from torchvision import transforms from s_data.MaskTheFace.augment_mask import AugmentMask default_trans_list = [ transforms.Resize((112, 112)), transforms.RandomHorizontalFlip(p=0.5), transform...
s_data/dataset.py
MIT
2,446
29e19e1e7829b720af4b55062727437ec3cf4f31
Python
py
import torch.nn.functional as f import torch.nn as nn import torch import numpy as np def init_weights(m): if type(m) == nn.Linear: nn.init.xavier_uniform_(m.weight) m.bias.data.fill_(0.01) class Actor(nn.Module): def __init__(self, state_dim, action_dim, fc1_units, fc2_units, seed): ...
p3_collab-compet/model.py
MIT
1,897
3480594052bb89c998512222674969e5ed340d40
Python
py
# -*- coding: utf-8 -*- # Copyright 2019 Pierre-Luc Delisle. All Rights Reserved. # # Licensed under the MIT License; # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://opensource.org/licenses/MIT # # Unless required by applicable law or agreed t...
deepNormalize/training/unet.py
MIT
32,012
03ee6110005c84f3e475ec799fe153ce8a6364ff
Python
py
# Copyright 2021 solo-learn development team. # 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 Software without restriction, including without limitation the rights to use, # copy, modify, merge, publ...
solo/utils/pretrain_dataloader.py
MIT
20,320
10b9c0c514207d82ed7fd2b8b38f3be72c5b99c2
Python
py
# Owner(s): ["module: codegen"] import torch from torch.testing._internal.common_utils import TestCase, run_tests from torch.testing._internal.logging_tensor import LoggingTensor, LoggingTensorReentrant, capture_logs, log_input from torch.utils._pytree import tree_map import logging def are_aliased(x, y): if x._...
test/test_functionalization.py
Intel
26,557
f9c425fb01a71300429c756eadca802a2f561b08
Python
py
""" Copyright 2021 The LightSeq Team Copyright Facebook Fairseq We use layers from Facebook Fairseq as our baseline for unit test """ from typing import Dict, List, Optional import math from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F from fairseq import utils from fairseq....
tests/fairseq_layers.py
Apache-2.0
20,684
ff6573e0879a64fc6cb6b08ae556749cc12f7be9
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import inspect import logging import numpy as np import os from pathlib import Path from typing import Dict, List, Optional, Tuple, Union import cv2 import torch from torch import nn from detectron2.config import configurable from detectron2.layers...
projects/WSL/wsl/modeling/roi_heads/roi_heads_oicr.py
Apache-2.0
26,859
29e1d795cc451bc439b5fe6f2eff504c2629a172
Python
py
# Owner(s): ["oncall: fx"] import torch import torch.fx.experimental.fx_acc.acc_ops as acc_ops from torch.testing._internal.common_fx2trt import AccTestCase from parameterized import parameterized, param from torch.testing._internal.common_utils import run_tests class TestClampConverter(AccTestCase): @parameteri...
test/fx2trt/converters/acc_op/test_clamp.py
Intel
903
e9be71edd7fb7e75312eef979bd13bf120df4a1d
Python
py
# Inspired by https://huggingface.co/transformers/perplexity.html from transformers import GPT2LMHeadModel, GPT2TokenizerFast import torch device = 'cuda' model_id = 'gpt2-large' model = GPT2LMHeadModel.from_pretrained(model_id).to(device) tokenizer = GPT2TokenizerFast.from_pretrained(model_id) def get_perplexity(...
perplexity/compute_ppl.py
MIT
1,215
a96b34d6bc9e2acfd4f30f5ed5e3e2966b0fe17e
Python
py
from overrides import overrides import torch from claf.config.namespace import NestedNamespace from claf.learn.optimization.learning_rate_scheduler import get_lr_schedulers from claf.learn.optimization.learning_rate_scheduler import ( LearningRateWithoutMetricsWrapper, LearningRateWithMetricsWrapper, ) from c...
claf/factory/optimizer.py
MIT
5,116
ff8856b29d58de989892874326792dec4f0c28f6
Python
py
import numpy as np import platalea.dataset as D import platalea.rank_eval as E import platalea.xer as xer import torch def score(net, dataset): data = dataset.evaluation() correct = data['correct'].cpu().numpy() image_e = net.embed_image(data['image']) audio_e = net.embed_audio(data['audio']) resu...
platalea/score.py
Apache-2.0
2,394
fd6594f3ff978bc752ea48204045e74a112cda05
Python
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 25 09:55:24 2019 @author: edward """ import numpy as np import matplotlib.pyplot as plt import torch from torch import nn from torch.distributions import Categorical import torch.nn.functional as F from arguments import parse_a2c_args from torchv...
3dcdrl/models.py
MIT
5,141
29e24f443ae3072c4f85487bfcb4ec3535eee3f6
Python
py
#!/usr/bin/python # -*- encoding: utf-8 -*- from core.utils.logger import setup_logger from core.models.cabinet import CABiNet from core.datasets.cityscapes import CityScapes import torch from torch.utils.data import DataLoader import torch.nn.functional as F import torch.distributed as dist import logging import nu...
scripts/evaluate.py
MIT
5,053
29e2567d2aaaadd41a2196258d16b39d9d1e06bc
Python
py
from __future__ import print_function, absolute_import import time from collections import OrderedDict import pdb import torch import numpy as np from .evaluation_metrics import cmc, mean_ap, map_cmc from .utils.meters import AverageMeter from torch.autograd import Variable from .utils import to_torch from .utils im...
reid/evaluators.py
Apache-2.0
4,588
29e2569a96f03a13f58b08bf2c4e8bcb9935c08f
Python
py
# execute mask_rcnn # save txt file # output : " frame_id, -1, x1, y1, w, h, scores, -1, -1, -1 "<- deep sort want this format import torch import numpy as np import os from PIL import Image from PIL import ImageDraw from maskrcnn_benchmark.config import cfg from demo.predictor import COCODemo def createFolder(direc...
excute_mask_rcnn_DAD.py
MIT
4,135
29e267b1bf63f34617be8e2714d8e177d74a7eaa
Python
py
"""Define a dymamical system for TurtleBot3""" from typing import Tuple, Optional, List import torch import numpy as np from .control_affine_system import ControlAffineSystem from neural_clbf.systems.utils import Scenario, ScenarioList class TurtleBot(ControlAffineSystem): """ Represents a two wheeled diffe...
neural_clbf/systems/turtlebot.py
BSD-3-Clause
9,445
7cccccae3c0f0cce8fad9d253a67eae3ccff070a
Python
py
# utils.py import torch from torchtext import data import spacy import pandas as pd import numpy as np from sklearn.metrics import accuracy_score class Dataset(object): def __init__(self, config): self.config = config self.train_iterator = None self.test_iterator = None self.val_it...
Model_Transformer/utils.py
MIT
4,255
b2abe0f98a6f15293cebbdd2f576fe743244469f
Python
py
from typing import Any, Dict, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.configuration_fsmt import FSMTConfig from transformers.file_utils import is_torch_tpu_avail...
examples/seq2seq/seq2seq_trainer.py
Apache-2.0
9,810
805a73871fb22e9e6da6655f3e95655ccdda0260
Python
py
import numpy as np import pandas as pd import os import os.path as osp import pickle from pathlib import Path import motmetrics as mm from copy import deepcopy from collections import OrderedDict import torch from torch_scatter import scatter_add from pytorch_lightning import Callback import re from mot_neural_so...
src/mot_neural_solver/utils/evaluation.py
MIT
18,236
29e2b868a582744dfa9b8ba57571e1c06edfff43
Python
py
import warnings from typing import Tuple, Optional import torch from torch import Tensor from .linear import _LinearWithBias from torch.nn.init import xavier_uniform_ from torch.nn.init import constant_ from torch.nn.init import xavier_normal_ from torch.nn.parameter import Parameter from .module import Module from .....
pytorch-frontend/torch/nn/modules/activation.py
MIT
39,726
fcaa84caa25d0ac275bc3076a6ac0323f47df4b5
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 itertools import torch import functorch from functorch import vmap import torch.utils._pytree as pytree fr...
test/common_utils.py
BSD-3-Clause
10,572
b2db5b51664dec85f19f584a11ea51f4b8cd61d5
Python
py
# code in this file is adpated from # https://github.com/kekmodel/MPL-pytorch import argparse import logging import math import os import random import time import numpy as np import torch from torch.cuda import amp from torch import nn from torch.nn import functional as F from torch import optim from torch.optim.lr_...
main.py
MIT
28,751
102061ef6c1504201de60bfa4ec9a39c617cc6aa
Python
py
from ruamel.yaml import YAML, dump, RoundTripDumper from raisimGymTorch.env.bin.rsg_ouzel_delta import RaisimGymEnv from raisimGymTorch.env.bin.rsg_ouzel_delta import NormalSampler from raisimGymTorch.env.RaisimGymVecEnv import RaisimGymVecEnv as VecEnv from raisimGymTorch.helper.raisim_gym_helper import ConfigurationS...
raisimGymTorch/raisimGymTorch/env/envs/rsg_ouzel_delta/scripts/runner.py
Apache-2.0
6,810
24f490a9b39a1a8f78f84f2c469fc556663ae62c
Python
py
"""Evaluate the model""" import argparse import random import logging import os import numpy as np import torch from SequenceTagger import BertForSequenceTagging, BertConfig from metrics import f1_score from metrics import classification_report from data_loader import DataLoader import utils parser = argparse.Arg...
evaluate.py
MIT
4,802
29e308ce54e736904eacc8e5f334fca093465c35
Python
py
# -*- coding: utf-8 -*- # @Time : 2018-8-2 9:20 # @Author : xylon import time import torch def gct(f="l"): """ get current time :param f: "l" for log, "f" for file name :return: formatted time """ if f == "l": return time.strftime("%m-%d %H:%M:%S", time.localtime(time.time())) ...
utils/common_utils.py
MIT
2,119
b2e17c2d52bafe44894ac725a42571945fa51dd9
Python
py
import argparse import os import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from tqdm import tqdm from dataloaders import make_data_loader from modeling.panoptic_deeplab import PanopticDeepLab from modeling.sync_batchnorm.replicate import patch_replication_callback from mypath imp...
train_panoptic.py
MIT
18,712
29e33a547e89474304b7d5e60011c96e723ab92b
Python
py
import torch.nn as nn import numpy as np from abc import abstractmethod class BaseModel(nn.Module): """ Base class for all models """ @abstractmethod def forward(self, *inputs): """ Forward pass logic :return: Model output """ raise NotImplementedError ...
base/base_model.py
MIT
838
29e3425afc22519f8ce853dc38e536951e60635c
Python
py
import argparse from typing_extensions import IntVar import torch import time from models.hardnext import HarDNeXt from models.resnet import resnet50 def speed_test(full_model_name, model, height, width, batch, gpu): # start = torch.cuda.Event(enable_timing=True) # end = torch.cuda.Event(enable_timing=True...
src/speed_measure.py
MIT
2,367
d7f35802cad878e554a44a459d294416c47a0671
Python
py
import torch from pytorch_lightning.utilities.data import extract_batch_size def test_extract_batch_size(): """Tests the behavior of extracting the batch size.""" batch = "test string" assert extract_batch_size(batch) == 11 batch = torch.zeros(11, 10, 9, 8) assert extract_batch_size(batch) == 11...
tests/utilities/test_data.py
Apache-2.0
585
29e35a7b891166afb86fb0316c727ddb3f59f652
Python
py
"""Custom decoder definition for transducer models.""" import torch from espnet.nets.pytorch_backend.transducer.blocks_for_tt import build_blocks from espnet.nets.pytorch_backend.transducer.utils import check_batch_state from espnet.nets.pytorch_backend.transducer.utils import check_state from espnet.nets.pytorch_bac...
espnet/nets/pytorch_backend/transducer/custom_decoder_for_tt.py
Apache-2.0
9,081
b2a0693e6d2f034d34d04746b56e27ee05675cb3
Python
py