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. All Rights Reserved. # Copyright (c) 2021 Microsoft Corporation. Licensed under the MIT license. import numpy as np import torch from torch.nn import functional as F from maskrcnn_benchmark.modeling.box_coder import BoxCoder from maskrcnn_benchmark.modeling.matcher i...
scene_graph_benchmark/relation_head/loss.py
MIT
40,355
fdffb1381c63b32d6efeaf8ee4a3eebdc8acf9a2
Python
py
# original implementation: https://github.com/odegeasslbc/FastGAN-pytorch/blob/main/models.py # # modified by Axel Sauer for "Projected GANs Converge Faster" # import torch.nn as nn from pg_modules.blocks import (InitLayer, UpBlockBig, UpBlockBigCond, UpBlockSmall, UpBlockSmallCond, SEBlock, conv2d) def normalize_sec...
training/networks_fastgan.py
MIT
6,139
dfe0d0e14b9a9266dadc36ecf1ea111a203aa413
Python
py
from models.mtcnn import MTCNN from models.inception_resnet_v1 import InceptionResnetV1 import torch from torch.utils.data import DataLoader from torchvision import datasets import numpy as np import pandas as pd import os workers = 7 device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('devi...
casia_test.py
MIT
1,188
e969ad4680b9af31ae1c86c0014f7abaeecf1cd3
Python
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2018 Nagoya University (Tomoki Hayashi) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Tacotron 2 related modules.""" import logging import numpy as np import torch import torch.nn.functional as F from espnet.nets.pytorch_backend.nets_utils...
espnet/nets/pytorch_backend/e2e_tts_tacotron2.py
Apache-2.0
33,030
10635ab9a7cde0dfa200f7a8dfb49f26103d1a42
Python
py
import importlib import math import os import warnings from fractions import Fraction from typing import List, Tuple import numpy as np import torch _HAS_VIDEO_OPT = False try: lib_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) loader_details = ( importlib.machinery.Extension...
torchvision/io/_video_opt.py
BSD-3-Clause
21,393
e92ac1bd396b98e33e7483e70d257a8b28875c94
Python
py
import time import trimesh import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from torch.nn.utils.rnn import pad_sequence from options.train_options import TrainOptions from options.test_options import TestOption...
unused_experiments/ST_global_content.py
MIT
5,878
f9b7d97fa575ea324bd20bbaebfa7f9d98f2bbc2
Python
py
from typing import Any, List from torch import nn, optim from torch.optim.lr_scheduler import ExponentialLR from torch.optim.optimizer import Optimizer from pystiche import enc from pystiche.image import transforms __all__ = [ "multi_layer_encoder", "preprocessor", "postprocessor", "optimizer", "...
pystiche_papers/ulyanov_et_al_2016/_utils.py
BSD-3-Clause
2,084
7097f2b295e5a4f45f0cfe3b3b94e4fd5e5e31b3
Python
py
import gin import torch import torch.nn as nn import torch.nn.functional as F @gin.configurable class GraphNetWeightedBCE(nn.Module): """Weighted binary cross entropy for RDGraphNet""" def __init__(self, real_weight, fake_weight): super().__init__() self.real_weight = real_weight self....
ariadne/graph_net/loss.py
MIT
746
fcaf1aa5abb4242729b39ae26f4b06f744828207
Python
py
from __future__ import print_function import torch import torch.nn.functional as F from torchvision import datasets, transforms from torch.autograd import Variable import os import keras from keras import backend as K import numpy as np import dill as pickle import numpy as np def test_tf2torch(tf_model,torch_model,in...
util.py
BSD-3-Clause
2,366
d7b627b064b86444e83c47658f7c690d54954954
Python
py
import json import unittest from shutil import rmtree import numpy as np import torch from metal.end_model import EndModel from metal.logging import LogWriter from metal.tuners.random_tuner import RandomSearchTuner class RandomSearchModelTunerTest(unittest.TestCase): @classmethod def setUpClass(cls): ...
tests/metal/tuners/test_random_search_tuner.py
Apache-2.0
3,954
fcc382bcd0f6a9b4eb0f8f41d64f092c43369bf8
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 logging import numpy as np import torch from fairseq.data import FairseqDataset, data_utils logger = logging.getLogger(__name__) d...
fairseq/data/language_pair_dataset.py
MIT
19,032
ff3e14bf14770638524ef6067b558e455dbe5f2b
Python
py
import pytest import torch from caldera.blocks import Flex def test_flex_block(): flex_linear = Flex(torch.nn.Linear) model = flex_linear(Flex.d(), 11) print(model.__str__()) print(model.__repr__()) x = torch.randn((30, 55)) model(x) print(model.__str__()) print(model.__repr__()) @p...
tests/test_blocks/test_flex_block.py
MIT
1,956
3a83a665cb40296884a26984a29093312b760bd0
Python
py
import os import numpy as np import itertools import collections import torch from .example import Example from .utils import nostdout class Dataset(object): def __init__(self, examples, fields): self.examples = examples self.fields = dict(fields) def collate_fn(self): def collate(bat...
meshed-memory-transformer/data/dataset.py
MIT
6,254
b297f53d47e9ef9c05fce8376ce6890de9d413a1
Python
py
import torch import json import os import torch.nn.functional as F import numpy as np from utils.data_reader import SimpleQABatcher from utils.args import get_args from utils.util import save_model, clip_gradient_threshold, load_model, get_f1, threshold, get_f1_mit_span from models.e2e_entity_linking import E2E_entity_...
train_e2e.py
MIT
15,998
fda3ccfc5b143814a20583a4fb8aaac7ce3b7a77
Python
py
''' REDS dataset support reading images from lmdb, image folder and memcached ''' import os.path as osp import random import pickle import logging import numpy as np import cv2 import lmdb import torch import torch.utils.data as data import data.util as util try: import mc # import memcached except ImportError: ...
EDVR_data/REDS_dataset.py
Apache-2.0,MIT
9,509
4b3e3ac7d8995d0dce8a284f460fad7c42bfc151
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from backbone import res50, bbn_res50, res32_cifar_mb, bbn_res32_cifar from modules import GAP, Identity, FCNorm class Network2(nn.Module): def __init__(self, cfg, mode, num_classes): super(Network2, self).__init__() pret...
lib/net/network2.py
MIT
3,769
7cdf4deedab208de2fa8ee9573c035bc4529153e
Python
py
#!/usr/bin/env python3 import threading import typing import warnings from collections import defaultdict from typing import Any, Callable, Dict, List, Tuple, Union, cast import torch from torch import Tensor, device from torch.nn import Module from captum._utils.common import ( _reduce_list, _run_forward, ...
captum/_utils/gradient.py
BSD-3-Clause
26,984
3a83ee38b79f90642474f841ef2c277c2594c9cb
Python
py
#!/usr/bin/env python """ Barebone Simulation without camera or extraneous sensors. With navigation and relative coordinates """ from __future__ import print_function # ============================================================================== # -- find carla module --------------------------------------------...
relative_coordinates_simulation.py
Apache-2.0
14,220
f99714ae02cf7d40f6c241a18254721389d2beae
Python
py
import torch import gnn_fw as gfw import pandas as pd from datetime import datetime import matplotlib.pyplot as plt import os from torch_geometric.utils import to_networkx import importlib.util from os import listdir from os.path import isfile, join """ How the script works: 1) load the gfw.config.Config object 2) rea...
run.py
MIT
12,226
1e3f04802a035e2f4e1995b10396fa71b3591d4b
Python
py
import argparse import io import pickle import tarfile import time from timeit import default_timer as timer import boto3 import numpy as np import skimage.transform import torch import torchvision.models as models from torch.autograd import Variable from torch import nn import candidate_data import featurize import ...
code/featurize_test.py
MIT
2,873
5e6dbd2819e8834e6e7b11914c1f1a4578f1abec
Python
py
# Built on top of the original implementation at https://github.com/hila-chefer/Transformer-Explainability # # Modifications by Copyright 2022 Zilliz. 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 obt...
towhee/models/visualization/transformer_visualization.py
Apache-2.0
6,849
3a84498ed83fc1bbcb1ffbee19b00eaa9c840eb6
Python
py
import os import time import argparse import numpy as np from tqdm import tqdm from sklearn.metrics import roc_auc_score import torch from torch.utils.data import DataLoader import torch.nn as nn import torch.optim as optim from torch.utils.data.sampler import RandomSampler from utils.util import * # import apex # from...
AE_method_real_attack.py
MIT
19,327
42257b7daba8a146bb3cc9e585f179aa03e597de
Python
py
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # 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 applicab...
aloe/aloe/common/pytorch_util.py
Apache-2.0
12,840
f9d31effb10247df24e7ca29ffb75eb32e91d4cb
Python
py
from copy import deepcopy import numpy as np import torch from mvn.models.v2v import Basic3DBlock, Res3DBlock, Pool3DBlock import torch.nn as nn import torch.nn.functional as F from mvn.utils import op, volumetric from mvn.models import pose_resnet class Encoder(nn.Module): def __init__(self): super()._...
mvn/models/fk.py
MIT
11,826
1e3baa48332b1a40a38ca36c849ecce6a1cd6368
Python
py
import unittest import torch from torch import nn import torch.nn.functional as F from asdfghjkl import FISHER_EXACT, FISHER_MC, COV from asdfghjkl import SHAPE_FULL, SHAPE_BLOCK_DIAG from asdfghjkl import fisher_free_for_cross_entropy from asdfghjkl import NaturalGradient, LayerWiseNaturalGradient def _relative_er...
tests/test_conjugate.py
MIT
4,901
3a8490d703fe5b7ecebf1eb0f7181f778d0f47a9
Python
py
""" In this module **precision**, **recall** and **F1 score** calculations are defined in separate functions. :py:class:`PrecisionRecallF1ScoreMeter` can keep track for all three of these. """ from collections import defaultdict import torch from catalyst.tools.meters import meter def f1score(precision_value, reca...
catalyst/tools/meters/ppv_tpr_f1_meter.py
Apache-2.0
4,036
7ca3ec1fbfe7338320e2d78db5947c78f719a363
Python
py
import torch import numpy as np import random import os def iou_xyxy_torch(boxes1, boxes2): """ [N, 4] with [M, 4] return [N, M] """ boxes1_area = torch.prod(boxes1[:, 2:] - boxes1[:, :2], -1) boxes2_area = torch.prod(boxes2[:, 2:] - boxes2[:, :2], -1) # 计算出boxes1与boxes2相交部分的...
utils/tools.py
MIT
10,551
3a84d9a5562a40c973c8a7f120c6f98373cf90b4
Python
py
""" Copyright (c) 2022 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writin...
nncf/torch/pruning/base_algo.py
Apache-2.0
13,277
e6534f5eea53887dc2de9df4dab4161a6e78e450
Python
py
################################################################################################### #FPENet:Feature Pyramid Encoding Network for Real-time Semantic Segmentation #Paper-Link: https://arxiv.org/pdf/1909.08599v1.pdf ###########################################################################################...
model/FPENet.py
MIT
9,253
ffa3809694b1b0373a6010eb43d6ee390e88bdc8
Python
py
import unittest from unittest.util import safe_repr from warnings import warn import torch from scipy.stats import truncnorm from TruncatedNormal import TruncatedNormal as TruncatedNormalPT class TruncatedNormalSC: def __init__(self, loc, scale, a, b): self.loc = loc self.scale = scale se...
tests/test.py
BSD-3-Clause
4,783
e634e4206ce3e30c5f70a007727bd5b1e41c5cf3
Python
py
#!/usr/bin/python3 -m unittest # # basic shelf assignment tests # import unittest import pymm import numpy as np import math import torch def colored(r, g, b, text): return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text) def log(*args): print(colored(0,255,255,*args)) force_new=True ...
src/python/pymm/testing/assignment.py
Apache-2.0
2,304
3418a8fdfa34858e36dd1e2759b417070b1d9766
Python
py
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
pytorch_lightning/metrics/metric.py
Apache-2.0
10,431
3a853be0ebdd50c1792fb4c53e215e6ef4e445d0
Python
py
""" Copyright (c) Microsoft Corporation. Licensed under the MIT license. distributed API using Horovod Modified from OpenNMT's native pytorch distributed utils (https://github.com/OpenNMT/OpenNMT-py) """ import math import pickle import torch from horovod import torch as hvd def all_reduce_and_rescale_tensors(tenso...
utils/distributed.py
MIT
6,296
fce69ea97322ec78a07fb2c8b3bc2f0398836e83
Python
py
import torch import torch.nn as nn from CVAE_testbed.models.weight_init import weight_init class CVAE(nn.Module): def __init__(self, x_dim, c_dim, enc_layers, dec_layers): super(CVAE, self).__init__() self.xdim = x_dim self.cdim = c_dim self.enc_layer1 = enc_layers[0] # en...
CVAE_testbed/models/CVAE_baseline.py
Xnet,X11
2,508
429ea1019eb574ca626aaf0d89f26daad6ed4718
Python
py
# MIT License # # Copyright (c) 2020 The Google AI Language Team Authors, The HuggingFace Inc. team and github/lonePatient # # 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 restricti...
venv/Lib/site-packages/transformers/models/mobilebert/modeling_mobilebert.py
MIT
66,074
3a855ba4fb75ef20ee0df558ad83406e74fa5c09
Python
py
""" Common training and validation utilities Hacked together by / Copyright 2020 Ross Wightman """ from copy import deepcopy import torch import math import os import re import shutil import glob import csv import operator import logging import logging.handlers import numpy as np from collections import OrderedDict ...
timm/utils.py
Apache-2.0
13,326
65255b532eba78c1a938bfeee791f641c89312b7
Python
py
import numpy as np import torch from torch.nn import functional as F from nflows.transforms.base import InputOutsideDomain from nflows.utils import torchutils DEFAULT_MIN_BIN_WIDTH = 1e-3 DEFAULT_MIN_BIN_HEIGHT = 1e-3 DEFAULT_MIN_DERIVATIVE = 1e-3 def unconstrained_rational_quadratic_spline( inputs, unnorma...
nflows/transforms/splines/rational_quadratic.py
MIT
6,254
3a85986a100c65cb84aa270df33829d84fe0a87f
Python
py
import pytest import torch from pytorch_lightning import Trainer from tests.base import EvalModelTemplate def test_optimizer_with_scheduling(tmpdir): """ Verify that learning rate scheduling is working """ hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) model.c...
tests/trainer/test_optimizers.py
Apache-2.0
8,509
3a85a756fc7855c17d06da9864c4363592e3e0fc
Python
py
# Pytorch Tabular # Author: Manu Joseph <manujoseph@gmail.com> # For license information, see LICENSE.TXT """Tabular Data Module""" import logging import re from typing import Callable, Iterable, List, Optional, Tuple, Union import category_encoders as ce import numpy as np import pandas as pd import pytorch_lightning...
pytorch_tabular/tabular_datamodule.py
MIT
23,749
3a85b0eb5e5beef536285fb61473dc1e765386ed
Python
py
import hparams import torchvision.transforms.functional as tvf import torchvision.transforms as transforms import pathlib import torch from torch.utils.data import Dataset from PIL import Image class PetData(Dataset): def __init__(self, transforms=None): self.path = hparams.DATASET_PATH self.tran...
nn/data.py
MIT
1,401
4288de3b6f8f2fade59fca4338bb24c639ab9653
Python
py
import abc import os import sys import numpy as np from torch._C import device from torch.serialization import validate_cuda_device import tqdm import torch from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from typing import Callable, Any from pathlib import Path from src.utils...
src/train.py
MIT
81,136
8051c1bbb00b5cda40dda0ff302ab050e82d13ce
Python
py
import torch import cv2 import numpy as np import torch.optim as optim import torchvision.models as models import torch.nn as nn from PIL import Image import scipy.misc def loadim(path): im = cv2.imread(path, cv2.IMREAD_COLOR) im = np.array([im[:, :, 2], im[:, :, 1], im[:, :, 0]]) im = torch.from_numpy(im)...
benet_style.py
MIT
4,415
3a86015406f249cab4fbdd2940f7b1278d260ba4
Python
py
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # 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://w...
nnUNet/nnunet/inference/predict.py
Apache-2.0
39,256
e96b4fcb2a23ef19917c92917fef21fd1abe5041
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...
examples/segmentation_3d/unet_training_dict.py
Apache-2.0
7,706
a92c006c9f18f0eb377ef93ab33c34cba637897f
Python
py
import torch.nn as nn import torch import torch.nn.functional as F from sklearn.metrics import roc_auc_score import numpy as np import sys import imp import molgrid import argparse import os import time import wandb from sklearn.metrics import precision_recall_fscore_support torch.backends.cudnn.benchmark = True def p...
train.py
MIT
15,295
10ba41b97090dfb1332072fe19de0473c1431f75
Python
py
import torch import torch.nn as nn from .layers import DynamicLSTM from .env import multienv class TextRNN(nn.Module): def __init__(self, rnn_type, num_layers, hidden_dim, configs): super(TextRNN, self).__init__() WN, WD = configs['embedding_matrix'].shape HD = hidden_dim C = con...
code/models/textrnn.py
MIT
2,443
3410ea1eff1caa43cefdd9e3adf86e81b2e3f80d
Python
py
# ***************************************************************************** # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions...
loss_functions.py
BSD-3-Clause
2,324
ff5834696bb68b22075673ba48572074a03e46cb
Python
py
"""Model-Agnostic Meta-Learning (MAML) algorithm implementation for RL.""" import collections import copy from dowel import tabular import numpy as np import torch from garage import log_multitask_performance from garage import TrajectoryBatch from garage.misc import tensor_utils from garage.sampler import OnPolicyVe...
src/garage/torch/algos/maml.py
MIT
21,079
a901258c1848378768612959ef15f4d58aeb67ab
Python
py
# -*- coding: utf-8 -*- # -------------------------------------------------- # # validation.py # # Validation phase. Model tuning of attribute label embedding (ALE) method on APY dataset # 15 seen classes : bird - cat - mug - bus - diningtable - bottle - car - boat # dog - zebra - monkey - cen...
validation.py
MIT
10,083
3a86508292d5159f58efc3570b388bf60819dae4
Python
py
import argparse import os import time import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torchvision.transforms as transforms import torchvision.datasets as datasets from models.alexnet import alexnet from models.vgg import ...
main.py
MIT
16,825
cc09fff7aa503acc5a99a3fdfe4649b721f4026a
Python
py
import math import warnings from typing import List from torch.optim import Optimizer from torch.optim.lr_scheduler import _LRScheduler class WarmupCosineLR(_LRScheduler): """ Sets the learning rate of each parameter group to follow a linear warmup schedule between warmup_start_lr and base_lr followed by...
src/hiding_adversarial_attacks/classifiers/pytorch_cifar10/scheduler.py
MIT
5,422
3a866577356e1657f8578cefc47d09a25b963418
Python
py
from os.path import join import os import sys import time import argparse import numpy as np from sklearn.metrics import precision_recall_fscore_support from sklearn.metrics import roc_auc_score from sklearn.metrics import precision_recall_curve from torch.utils.tensorboard import SummaryWriter from torch.utils.data i...
train_rnn_match.py
MIT
12,861
fd6767d3e4cb11b49c33380284204423e5155fc5
Python
py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from __future__ import print_function from torch.utils.data import Dataset import pandas as pd import os import numpy as np import pickle import re import random import io class Youcook_Caption...
end-2-end/UniVL/dataloaders/dataloader_youcook_caption.py
MIT
9,932
f952d16213069b17ca70e417ef3d1c5765cdffe7
Python
py
import torch import torch.nn as nn from torchvision import models import kornia.filters # borrowed from https://github.com/usuyama/pytorch-unet/blob/master/pytorch_resnet18_unet.ipynb and edited def convrelu(in_channels, out_channels, kernel, padding): return nn.Sequential( nn.Conv2d(in_channels, in_chan...
DRACO/models/resnet.py
MIT
15,180
347c7e8fe476b813db5c0852686b4e27ce7fd607
Python
py
#! /usr/bin/python3 # -*- coding: utf8 -*- import os, time, random, re, glob from pathlib import Path import math import random import numpy as np from PIL import Image, ImageMath, ImageFilter, ImageOps from io import BytesIO import torch from torch.utils.data import DataLoader, Dataset from torchvision import transfo...
main.py
Apache-2.0
16,915
24f0b053ad646495b68eae6d69a80518ecad2f3e
Python
py
# Copyright (c) 2019-present, Francesco Croce # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ i...
pytorch_ares/third_party/autoattack/autoattack/fab_base.py
MIT
15,372
3a86bba87120557c0a68581468eea784a4fa7408
Python
py
import math import torch from torch.distributions.kl import register_kl _EPS = 1e-7 class _TTransform(torch.distributions.Transform): domain = torch.distributions.constraints.real codomain = torch.distributions.constraints.real def _call(self, x): t = x[..., 0].unsqueeze(-1) v ...
power_spherical/distributions.py
MIT
6,734
3a86d3cb187f3bb763f12ba0811aa48da38c3e1c
Python
py
import torch import argparse from albert_modeling import AlBertJointForNQ, AlbertConfig from torch.utils.data import TensorDataset, SequentialSampler, DataLoader import utils from tqdm import tqdm import os import json import collections import pickle import pandas as pd from albert_preprocess import InputLSFeatures fr...
tf2qa/predict.py
MIT
8,526
3a86de7b740f0d496b5fa1b83578e18778b38e20
Python
py
import torch import torch.nn as nn from transformers import BertModel, BertPreTrainedModel, BertLayer from transformers.models.bert.modeling_bert import BertPooler class PSUM(nn.Module): def __init__(self, count, config, num_labels): super(PSUM, self).__init__() self.count = count self.num_...
models/berts/bpsum_asc.py
Apache-2.0
2,375
5f81c875804482865d603bd3fe37adae8bfa4b50
Python
py
import torch from tensorboardX import SummaryWriter class AverageMeterSet: # Nawid - Calculates averages def __init__(self): self.sums = {} self.counts = {} self.avgs = {} def _compute_avgs(self): # Nawid - Calculate average for name in self.sums: self.avgs[name] =...
stats.py
MIT
3,294
038043a9246d80bd7680079945858c5419b753d0
Python
py
import torch import torch.nn.functional as F from torch.optim import Adam from sac.utils import soft_update, hard_update from sac.model import TransferQNetwork, TransferGaussianPolicy, Encoder, DynamicsActionEncoder, RewardActionEncoder from sac.dynamics_model import DynamicsModel, RewardModel import numpy as np impor...
sac/sac_easy.py
MIT
11,159
3a86f386bc965294648ecb0aa6797cb121adc324
Python
py
"""CURRENTLY OUTDATED. WILL UPDATE IN FUTURE""" """ import torch from torch import Tensor from torch.autograd import Variable as Var from torch.utils.data import DataLoader from rl.utils import ProgBar, RealtimePlot from rl.envs import controller class DAgger(): def __init__(self, env, learner, expert): ...
rl/algos/dagger.py
MIT
2,489
3a86f84ad86c83c7dc1d8695947adfbadd2e54ed
Python
py
import torch from espnet.nets.pytorch_backend.transformer.attention import MultiHeadedAttention from espnet.nets.pytorch_backend.transformer.embedding import PositionalEncoding from espnet.nets.pytorch_backend.transformer.encoder_layer import EncoderLayer from espnet.nets.pytorch_backend.transformer.layer_norm import ...
training/finetuneav/ctcencoder.py
Apache-2.0
4,313
28deff1b62c75ebf66293721ca91946b300979d9
Python
py
from __future__ import absolute_import from __future__ import division import torch import torch.nn as nn class CrossEntropyLoss(nn.Module): r"""Cross entropy loss with label smoothing regularizer. Reference: Szegedy et al. Rethinking the Inception Architecture for Computer Vision. CVPR 2016. ...
torchreid/losses/cross_entropy_loss.py
MIT
2,212
12d5eb9a948e5c640c89784b8a250b55806fe8a0
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class YoloLoss(nn.Module): def __init__(self, S, B, l_coord, l_noobj): super(YoloLoss,self).__init__() self.S = S self.B = B self.l_coord = l_coord self.l_noobj = l_noobj ...
yolo_loss.py
MIT
11,588
3a870b3b4f8b064b87a70a4b5cb1cba39dbec4a9
Python
py
import torch import torch.nn as nn from vgg import vgg from decoder import decoder def calc_mean_std(feat, eps=1e-5): # eps is a small value added to the variance to avoid divide-by-zero. size = feat.size() assert (len(size) == 4) N, C = size[:2] feat_var = feat.view(N, C, -1).var(dim=2...
model/SANet.py
MIT
6,763
3a870d50e1cb0696b28eefbfa54ed5df5f3417d6
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Parameter import math import pdb # -------- Vanilla ---------# # nn.Conv3d(3, 64, kernel_size=3, padding=1) # -------- 3DCDC ---------# # CDC_ST(3, 64, kernel_size=3, padding=1, theta=0.6) # CDC_T(3, 64, kernel_size=3, paddi...
3DCDC.py
MIT
4,955
24943597e58a0e7040af19461d98a5dd335b6111
Python
py
import torch import torch.nn as nn from torchviz import make_dot class MyNetwork2(nn.Module): def __init__(self): super().__init__() # define the layers self.layers = nn.Sequential( nn.Linear(16, 12), nn.ReLU(), nn.Linear(12, 10), ...
7_ref_how_to_build_network/test5.py
MIT
802
7020aaba75230b99b9e0c38859b2693fe3c3c8a0
Python
py
import torch import torch.nn.functional as F from tqdm import tqdm from dice_loss import dice_coeff from easydict import EasyDict as edict import yaml with open("cfgs/train.yml", 'r', encoding="utf-8") as f: args = edict(yaml.load(f, Loader=yaml.FullLoader)) def eval_net(net, loader, device): """Evaluation w...
UNet_pytorch/eval.py
BSD-3-Clause
1,238
d71064e4aeac2f402a4fcaf3e519d0101ea5a30e
Python
py
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
flash/pointcloud/detection/data.py
Apache-2.0
5,465
3a87369f97a06a9fe5178e1b5fc470ea8840cc4a
Python
py
import torch import torch.nn as nn import torch.nn.functional as F class KIMCNN1D(nn.Module): def __init__(self, opt): super(KIMCNN1D, self).__init__() self.embedding_type = opt.embedding_type self.batch_size = opt.batch_size self.max_seq_len = opt.max_seq_len self.embeddi...
models/CNNKim.py
MIT
5,574
345a2004705a3c58adf9750eebba3c4e1d24e3ba
Python
py
# coding: utf-8 ############################################# # Cross Entropy with ResNet-34 ############################################# # Imports import os import time import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import argparse import sys from torch.utils.data import Da...
experiment-logs/cacd/cacd-ce.py
MIT
12,795
3467e704a7dd250e818b182d1d4d9b088f309f25
Python
py
##################################################### # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2019.01 # ##################################################### import torch.nn as nn import torch.nn.functional as F from ..initialization import initialize_resnet class ConvBNReLU(nn.Module): def __init__(self, nI...
lib/models/shape_infers/InferCifarResNet_depth.py
MIT
5,898
d773fc5035054af8d22390b10250b7b295d52f79
Python
py
import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F # from Discriminator import Discriminator class Adversarial_Loss(nn.Module): def __init__(self, lambda_adv): super(Adversarial_Loss, self).__init__() self.lambda_adv = lambda_adv pass def forward(self, input...
Adversarial_Loss.py
MIT
788
3a875daa5f3115086f0543e16ba3da04468740a1
Python
py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and 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. from dataclasses import dataclass, field from enum import Enum, unique from math import ...
torchrec/modules/embedding_configs.py
BSD-3-Clause
3,588
7cc3270041944eec2adc0f5441e9b8e5c1b7e7cd
Python
py
import torch import torch.nn as nn from sandstone.models.pools.abstract_pool import AbstractPool from sandstone.models.pools.factory import RegisterPool @RegisterPool('GlobalMaxPool') class GlobalMaxPool(AbstractPool): def replaces_fc(self): return False def forward(self, x, batch=None): # X ...
sandstone/models/pools/max_pool.py
MIT
385
6b47974fc79c38d35af5116efc4fde6b2c7e43e5
Python
py
from torch import nn from ..functions.sigmoid_focal_loss import sigmoid_focal_loss # TODO: remove this module class SigmoidFocalLoss(nn.Module): def __init__(self, gamma, alpha): super(SigmoidFocalLoss, self).__init__() self.gamma = gamma self.alpha = alpha def forward(self, logits,...
mmdet/ops/sigmoid_focal_loss/modules/sigmoid_focal_loss.py
Apache-2.0
670
34202b566437a4d4c6fee5b0cf70f630cac29b3f
Python
py
import argparse import collections import os import re import time from collections import OrderedDict from distutils.util import strtobool import numpy as np import scipy.stats import torch import torch.nn as nn import torchvision from torch._six import int_classes, string_classes from torch.autograd import Variable ...
test_model.py
BlueOak-1.0.0,Apache-2.0
13,064
5fb78e916a09f0b0669ba5512210aced6a259294
Python
py
import collections import inspect import io import types import typing import warnings import torch from . import (_dev_utils, activations, convolution, normalization, pooling, preprocessing, regularization, upsample) from ._version import __version__ from .module import InferDimension __all__ = ["sum...
torchlayers/__init__.py
MIT
24,781
e9ac09094bd5e14224a8cfb9e17c0ba476057827
Python
py
# Copyright (c) OpenMMLab. All rights reserved. import pytest import torch from mmflow.models.decoders.pwcnet_decoder import PWCModule, PWCNetDecoder from mmflow.models.decoders.utils import CorrBlock def _get_test_data(): input_feat1 = dict( level6=torch.randn(1, 196, 8, 8).cuda(), level5=torch...
tests/test_models/test_decoder/test_pwcnet_decoder.py
Apache-2.0
3,228
10cae689e85d367d227f5e243e5c19ecba00acb5
Python
py
import torch import torch.nn as nn class GRUNet(nn.Module): def __init__(self, in_channels, hid_channels, out_channels, num_layers, drop_prob=0.2): super(GRUNet, self).__init__() self.relu = nn.ReLU() self.gru = nn.GRU(in_channels, hid_channels, num_layers, batch_first=True, dropo...
Models/gru.py
MIT
749
d79e1dd284dcd0a5e56f274fad62e58b38b17423
Python
py
from logging import NOTSET from absl import app, flags, logging from pytorch_lightning import trainer import torch as th import pytorch_lightning as pl import nlp from torch.optim import optimizer import transformers import sh import math import torch.nn as nn import torch.nn.functional as F from model.bert import BE...
demo.py
MIT
4,002
d78e378dc0266a072309d2d12865a515e7af9034
Python
py
import torch from torch.nn import Linear as Lin from torch.nn import ReLU from torch.nn import Sequential as Seq from torch_sparse import SparseTensor from torch_geometric.nn import DynamicEdgeConv, EdgeConv def test_edge_conv_conv(): x1 = torch.randn(4, 16) x2 = torch.randn(2, 16) edge_index = torch.ten...
test/nn/conv/test_edge_conv.py
MIT
3,234
ff1e94d21f809c7f939f51770936d935eece978f
Python
py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. """PyTorch Dataset implementation for Iterative CLEVR dataset""" import json import cv2 import h5py import numpy as np import torch from torch.utils.data import Dataset from ..utils.config import keys class ICLEVERDataset(...
irgan/data/clevr_dataset.py
MIT
4,615
5f7fd201cc4432d225e141549089d95ec0cb8142
Python
py
import torch import torch.nn as nn from entmax import entmax15, sparsemax from .sparsesoftmax import sparse_softmax def entropy(p: torch.Tensor): """Numerically stable computation of Shannon's entropy for probability distributions with zero-valued elements. Arguments: p {torch.Tensor} -- tensor o...
lvmhelpers/marg.py
MIT
4,809
42a8acc323e86e386793935087c71e05496f789a
Python
py
import pycuda.driver as cuda import pycuda.autoinit import numpy as np import tensorrt as trt import torch import time from cv2 import imwrite from packnet_sfm.utils.image import load_image from packnet_sfm.datasets.augmentations import resize_image, to_tensor from packnet_sfm.utils.depth import write_depth, inv2dept...
src/trt_packnet/src/trt_engine.py
MIT
4,243
f9c70d6464cb4674ba7705b49ed5dc1712fff1ca
Python
py
from __future__ import print_function import os import math import random import numpy as np import sys import time import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import CosineAnnealingLR import t...
pruning/main.py
Apache-2.0
5,548
3a883431edaa642a8b96cac6844270b437843b04
Python
py
import numpy as np import torch import time import os os.environ['NPY_MKL_FORCE_INTEL'] = 'GNU' num_params = 4010 k = torch.tensor(np.load('./tests/utils/numpy_params/function_0_param_k.npy'), requires_grad=True, dtype=torch.float) torch.set_num_threads(1) y = (((k*k+3*k)-k/4)/k+k*k*k*k+k*k*(22/7*k)+k*k*k*k*k*k*k*k*k)...
tests/utils/pytorch.py
MIT
559
3a883ace2c8a57d959b75113f054cd9ab1688032
Python
py
#-*- coding:utf-8 -*- import torch import numpy as np def point_form(boxes): """ Convert prior_boxes to (xmin, ymin, xmax, ymax) representation for comparison to point form ground truth data. Args: boxes: (tensor) center-size default boxes from priorbox layers. Return: boxes: (tensor)...
src/utils.py
MIT
11,479
3a884478cdcaf49ff35d9f11dc688104cb4a59c2
Python
py
from PIL import Image import random import math from typing import ClassVar, Sequence, List, Tuple from torch import Tensor import torch import torchvision.transforms.functional as F import torchvision.transforms.transforms as T import torch.nn as nn from . import MultipleApply as MultipleApplyBase, NormalizeAndTranspo...
common/vision/transforms/segmentation.py
MIT
9,176
e648c1ab2afab85c34fc3961fa19aade61612b34
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. """ The metrics module contains implementations of various metrics used commonly to understand how well our models are performing. For e.g. accuracy, vqa_accuracy, r@1 etc. For implementing your own metric, you need to follow these steps: 1. Create your own metric cl...
pythia/modules/metrics.py
BSD-3-Clause
18,463
3a8872a629677f847a25547cf2f7feb38a037c74
Python
py
from collections import OrderedDict import numpy as np import torch.optim as optim import rlkit.torch.utils.pytorch_util as ptu import torch from rlkit.core.trainer import Trainer from rlkit.core.eval_util import create_stats_ordered_dict from rlkit.policies.simple import RandomPolicy from rlkit.samplers import rollo...
ILSwiss/rlkit/torch/algorithms/ddpg/ddpg.py
MIT
10,115
247c44ce2d12a7a21944115fac3ff29d137f7ff3
Python
py
"""Test the multi-output GP implementations.""" import pytest import numpy as np try: import torch from safe_exploration.ssm_pytorch import BatchMean, BatchKernel, MultiOutputGP, LinearMean, GPyTorchSSM import gpytorch from torch.nn.functional import softplus except: pass @pytest.fixture(autous...
safe_exploration/test/test_gaussian_process.py
MIT
7,472
f9fa01e3675628d8fecb29506ec0d9a60d1a1c66
Python
py
#-------------# import torch import torch.nn as nn from torch.nn.utils.rnn import pad_sequence #-------------# from .decoar import Decoar from .audio import create_transform from collections import OrderedDict ############ # CONSTANT # ############ EXAMPLE_FEAT_SEQLEN = 1000 ################### # UPSTREAM EXPERT # #...
upstream/decoar/expert.py
MIT
1,976
45f9f8a40b79babe8b4cf7b7586ce92fc295f97a
Python
py
import math import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.utils import _triple from network.model.graph_front.graphFront import _graphFront from network.model.tgcn.gcn import ConvTemporalGraphical from network.model.roi_align.modules.roi_align import RoIAlignAvg class Spat...
network/R3D_model.py
MIT
16,195
3a88d7d1a6cf6a68d76ed92404bdba4d417b181e
Python
py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Copyright (c) Megvii, Inc. and its affiliates. from loguru import logger import apex import torch from apex import amp from torch.utils.tensorboard import SummaryWriter from yolox.data import DataPrefetcher from yolox.utils import ( MeterBuffer, ModelEMA, a...
yolox/core/trainer.py
Apache-2.0
11,417
3a88e2011794df552f7c1515ea5b5666904d048d
Python
py
# coding=utf-8 # Copyright 2018 Salesforce and HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # h...
transformers/modeling_ctrl.py
Apache-2.0
24,667
1ed9e6ebb111997b503a0938748a97539ae856a4
Python
py
import torch from tqdm import tqdm def evaluate(model, data_loader, metrics, device): if model.training: model.eval() summary = {metric: 0 for metric in metrics} for step, mb in tqdm(enumerate(data_loader), desc='steps', total=len(data_loader)): x_mb, y_mb = map(lambda elm: elm.to(device...
senCNN/model/metric.py
MIT
741
f96f3a8bf59867d30182ee8c83986bf197687406
Python
py
import torchvision import torch.utils.data as torch_data from torch.nn import CrossEntropyLoss from models.simple import SimpleNet from tasks.task import Task from torchvision.transforms import transforms class MNISTTask(Task): normalize = transforms.Normalize((0.1307,), (0.3081,)) def load_data(self): ...
tasks/mnist_task.py
MIT
1,633
3a8914437c4e6ca740dfbe37406a5e5acde2212a
Python
py
from __future__ import absolute_import, division, print_function, unicode_literals import torch from tests import utils class SimpleFlattenModule(torch.nn.Module): def __init__(self, start_dim=0, end_dim=-1): super(SimpleFlattenModule, self).__init__() self.start_dim = start_dim self.end_...
torch_glow/tests/nodes/flatten_test.py
Apache-2.0
1,412
3a8914f8967c736d379482a362b9c6d22d241130
Python
py