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
''' Following distilaltion distills knowledge from a normal teacher to a self distill student model. This enables us with the option of where (meaning at what FC layer) to transfer the KD loss, instead of just one option of tranferring to the final FC layer of the original student model. ''' # train a student network...
train_kd_to_SD.py
MIT
16,935
10bf01e3769a5a62e2610397258b5414802090e6
Python
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import cv2 import numpy as np from progress.bar import Bar import time import torch from models.model import create_model, load_model from utils.image import get_affine_transform from utils.debugger import Deb...
src/lib/detectors/base_detector.py
MIT
5,050
a93f7c3adc5feef3b4ceec877207f32a898e36af
Python
py
import pytest import torch from torch.nn.modules import GroupNorm from torch.nn.modules.batchnorm import _BatchNorm from mmpose.models.backbones.utils import (InvertedResidual, SELayer, channel_shuffle, make_divisible) def is_norm(modules): """Check if is one ...
tests/test_backbones/test_backbones_utils.py
Apache-2.0
3,988
fee72321f984726585c28b7d25d44ad101e6e955
Python
py
import torch def sequence_mask(seq): batch_size, seq_len = seq.size() mask = torch.triu(torch.ones((seq_len, seq_len), dtype=torch.uint8), diagonal=1) mask = mask.unsqueeze(0).expand(batch_size, -1, -1) # [B, L, L] return mask
model/tool/sequence_mask.py
Apache-2.0
265
52b13984b40678228c38e6780a9e04f3f859e541
Python
py
import torch import random from .default import NormalNN class L2(NormalNN): """ @article{kirkpatrick2017overcoming, title={Overcoming catastrophic forgetting in neural networks}, author={Kirkpatrick, James and Pascanu, Razvan and Rabinowitz, Neil and Veness, Joel and Desjardins, Guillaume and...
agents/regularization.py
MIT
14,056
fee73925193ae13ebd9e28cc4bb7913c2f7f8377
Python
py
from dataclasses import dataclass from typing import Tuple import numpy as np import torch from torch import jit, nn from pycave.bayes.core import covariance_shape, CovarianceType from pycave.bayes.core._jit import jit_log_normal, jit_sample_normal from pycave.core import ConfigModule @dataclass class GaussianMixture...
pycave/bayes/gmm/model.py
MIT
5,405
4250e4921436593bd16aeb816c4b1b9182a126af
Python
py
import torch import torch.nn as nn """Define new activation for VQA""" class Swish(nn.Module): def __init__(self): super(Swish, self).__init__() def forward(self, x): return torch.mul(x, torch.sigmoid(x))
src/activation.py
MIT
231
dfc43b4e26f19f5bf711ed47305f6375a0cf5b8b
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # import argparse # import itertools import json import os import subprocess # import sys # import time import unittest import uuid import torch # import datasets # import hparams_registry # import algorithms # import networks # from parameterize...
domainbed/test/scripts/test_train.py
MIT
1,654
fee7530ec18d87fbf0803988096a26535416ce48
Python
py
import argparse import os import shutil import time import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.optim import torch.utils.data import torch.utils.data.distributed import torchvision.tra...
docker_classify.py
Apache-2.0
17,636
fee75bea34e7ea676b3afa3fe0470f7f2ac65d47
Python
py
import torch from torch import nn import torch.nn.functional as F from tamil_tech.torch.layers import * from tamil_tech.torch.utils import * class Decoder(nn.Module): ''' A decoder model with self attention mechanism. ''' def __init__( self, sos_id, eos_id, n_tgt_vocab, d_word_vec, ...
tamil_tech/torch/decoders.py
Apache-2.0
10,036
fee75dc8515fa5bdd20dab853081f18de09bc90a
Python
py
import os import sys import json import torch import torch.nn as nn from torchvision import transforms, datasets import torch.optim as optim from tqdm import tqdm from model import GoogLeNet def main(): device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print("using {} device.".format(d...
pytorch_classification/GoogLeNet/train_pre.py
MIT
4,907
fee79bb224341713cfcc2d053d9451f607a02b35
Python
py
import os import torch from torchtext.data.field import Field, RawField from torchtext.data.iterator import BucketIterator from torchtext.vocab import Vectors from datasets.castor_dataset import CastorPairDataset class WikiQA(CastorPairDataset): NAME = 'wikiqa' NUM_CLASSES = 2 ID_FIELD = Field(sequentia...
datasets/wikiqa.py
Apache-2.0
2,777
fee7a6a0ceb303692b6ec58108f9ace97d6edeba
Python
py
import argparse from multiprocessing import Pool import os from time import time import matplotlib.pyplot as plt import numpy as np import torch from torch.utils.data import Dataset from utils.data_utils import DatasetHandler, load_mr_scan from utils import evaluation, utils class DataPreloader(Dataset): def __...
baseline.py
MIT
4,617
7c2a073c2402c5957b8c4e8dbd886439c8a48eac
Python
py
"""dataset.py""" import os import numpy as np from tqdm import tqdm import torch from torch.utils.data import Dataset, DataLoader from torchvision.datasets import ImageFolder from torchvision import transforms class CustomImageFolder(ImageFolder): def __init__(self, root, transform=None): super(CustomIm...
gan_training/dvae/dataset.py
RSA-MD
2,742
45e7a24a8a15686b125c8d939438dcc97b119172
Python
py
from torch import nn import torch import torch.nn.functional as F from detro.networks.components import BiFPN, Center_layer, Offset_layer, Reg_layer, Heatmap_layer, BasicBlock from detro.networks.losslib import center_loss, distance_loss from detro.networks.backbones.resnet_backbone import resnet18 class FeatureFusion...
detro/packages/fcosdet/network.py
MIT
1,880
fee7eb72919db9a3e293dcb1856698b507092ff2
Python
py
from data import * from utils.augmentations import SSDAugmentation, BaseTransform from utils.functions import MovingAverage, SavePath from layers.modules import MultiBoxLoss from yolact import Yolact import os import sys import time import math from pathlib import Path import torch from torch.autograd import Variable i...
train.py
MIT
15,891
fee7f2ace7f34ac5b560ad895db224be66cec613
Python
py
import torch from fastscript import * from fastbench.utils import show_install from fastbench.vision import train_imagenette from fastbench.tabular import train_tabular from fastbench.imdb import train_imdb """Compute image benchmarks on imagenette""" welcome_str="""Welcome to fastbench! your friendly benchmark for ...
bench.py
Apache-2.0
1,269
12a14cd549ebdd9a9f133e27f5548cb9deb7aba3
Python
py
import torch_audiomentations from torch import Tensor from hw_asr.augmentations.base import AugmentationBase class Gain(AugmentationBase): def __init__(self, sample_rate, p=0.2, mode="per_example", p_mode="per_example", *args, **kwargs): self._aug = torch_audiomentations.Gain(sample_rate=sample_rate, p=p...
hw_asr/augmentations/wave_augmentations/Gain.py
MIT
473
fee7fce16e90530f99707bdd31b40080ae548e5a
Python
py
import torch.nn.functional as F from utils.utils import * def make_divisible(v, divisor): # Function ensures all layers have a channel number that is divisible by 8 # https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py return math.ceil(v / divisor) * divisor class...
ultralytics_newest_yolov3/utils/layers.py
Apache-2.0
4,538
fee81ca101141b611c8e335c17240c32aa21a8e7
Python
py
import os import itertools import torch import numpy as np import pandas as pd from scipy.stats import special_ortho_group, pearsonr from sklearn.decomposition import PCA class Constants(object): eta = 1e-6 class CustomBatch: def __init__(self, batch): self.batch = torch.stack(batch, dim=1) de...
task_dyva/utils.py
MIT
9,565
5e5336f8fe83adf405e5a1180407fe85f8b27baa
Python
py
from torch_geometric.nn import radius_graph class RadiusGraph(object): r"""Creates edges based on node positions :obj:`pos` to all points within a given distance. Args: r (float): The distance. loop (bool, optional): If :obj:`True`, the graph will contain self-loops. (default:...
torch_geometric/transforms/radius_graph.py
MIT
1,416
fee8414b8fe69b088757362328c1a24509732ad1
Python
py
import random import numpy as np import torch from torch.utils.data import Dataset from purano.util import tokenize from purano.training.fasttext_hnsw import FasttextHnsw class Text2TitleDataset(Dataset): def __init__(self, data, ft_model, min_words=2, max_words=150): self.ft_hnsw = FasttextHnsw(ft_mode...
purano/training/datasets/text2title.py
Apache-2.0
1,815
fee8705a014b75291358b4ce334665e97caf9274
Python
py
import unittest from unittest import TestCase import torch from src.signals.outliers import MomentOutlierSignal class MomentOutlierTest(TestCase): def setUp(self): self.eps = 1e-2 # threshold for differences in data evaluation def test_scalar_mean(self): Signal = MomentOu...
tests.py
BSD-3-Clause
1,697
fee871e4d588db3332a3f127507c3dc3746ea042
Python
py
#!/usr/bin/env python3 # encoding: utf-8 import os import cv2 import argparse import numpy as np import torch import torch.multiprocessing as mp from config import config from utils.pyt_utils import ensure_dir, link_file, load_model, parse_devices from utils.visualize import print_iou, show_img from engine.evaluator ...
model/dfn/cityscapes.dfn.R101_v1c/eval.py
MIT
3,703
f95867a1ff6a16e823d1ce55a0b733bd89064d07
Python
py
# ------------------------------------------------------------------------ # Modified from DETR (https://github.com/facebookresearch/detr) # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # ------------------------------------------------------------------------ from typing import Optional ...
models/transformer_decoder.py
MIT
14,590
fee89790a193ea737b0ebac3edfd1e728944d44d
Python
py
"""Common image segmentation losses. """ import torch from torch.nn import functional as F def bce_loss(true, logits, mask=None, pos_weight=None): """Computes the weighted binary cross-entropy loss. Args: true: a tensor of shape [B, 1, H, W]. logits: a tensor of shape [B, 1, H, W]. Correspo...
lib/junno/nnet/torch/loss.py
BSD-3-Clause
6,650
fee8aae2bddb39feae17ada11b92b18382c83da5
Python
py
# coding=utf-8 # Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
examples/pytorch/eager/huggingface_models/examples/text-classification/run_glue_no_trainer_prune.py
Apache-2.0
20,958
3452720866fd40c0469d40387dd273d28c0e5b74
Python
py
import os import argparse import numpy as np import torch import model import data import train parser = argparse.ArgumentParser( description=r"""Denoising MLP autoencoder""") parser.add_argument('--mode', type=str, default='train', help='mode to run main (train, generate)') parser.ad...
main.py
Apache-2.0
6,394
fee8c8bbfcfe75d676e2c9fb58125dbd53c110db
Python
py
""" Use the output of gaze_estimation to calibrate (train) screen_gaze """ import logging import math import time from random import random from typing import List, Tuple import screeninfo import cv2 import numpy as np import torch.nn import yacs.config from gaze2screen_model import Gaze2Screen from gaz...
screen_gaze.py
MIT
8,042
45a1f4478ba4209f962c1407763a559f32b5cb0e
Python
py
"""The data layer used during training to train a Fast R-CNN network. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch.utils.data as data from PIL import Image import torch from model.utils.config import cfg from roi_da_data_layer.minibatc...
lib/roi_da_data_layer/roibatchLoader.py
MIT
9,067
fee8d74d718c95ec6382a1fe92ce520ebd20e21e
Python
py
""" This script was made by Nick at 19/07/20. To implement code for inference with your model. """ from argparse import ArgumentParser, Namespace import os import matplotlib.pyplot as plt import numpy as np import pytorch_lightning as pl import torch from src.utils import Config, get_dataloader pl.seed_every...
infer.py
MIT
2,098
127ff7df37ff42b84b26a441171af0497fd7e3f8
Python
py
from typing import Optional import torch from catalyst.metrics.functional import process_multilabel_components def average_precision( outputs: torch.Tensor, targets: torch.Tensor, weights: Optional[torch.Tensor] = None, ) -> torch.Tensor: """Computes the average precision. Args: outputs...
catalyst/metrics/precision.py
Apache-2.0
2,152
45e47c6a2072a302e75d095e2813fd8d45efff58
Python
py
# -*- coding: utf-8 -*- import torch import numpy as np from ..aggregators_base import AggregatorBase from ...registry import AGGREGATORS from ....index.utils import feature_loader from typing import Dict @AGGREGATORS.register class PWA(AggregatorBase): """ Part-based Weighting Aggregation. c.f. https:/...
pyretri/extract/aggregator/aggregators_impl/pwa.py
Apache-2.0
3,165
fee907b49fb72949b0454cd024c4c1eaf2824b6e
Python
py
import torch import torch.nn.functional as F import numpy as np from scipy import interpolate class InputPadder: """ Pads images such that dimensions are divisible by 8 """ def __init__(self, dims, mode='sintel'): self.ht, self.wd = dims[-2:] pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) % 8 ...
core/utils/utils.py
BSD-3-Clause
2,477
fee90888145858cfd00bab9f01cb631acb48fddd
Python
py
from typing import Any, Dict, Mapping, Union import copy import os import torch import torch.distributed as dist import torch.nn as nn from torch.nn.parallel import DistributedDataParallel from catalyst.core.engine import IEngine from catalyst.typing import RunnerCriterion, RunnerModel, RunnerOptimizer, RunnerSchedul...
catalyst/engines/torch.py
Apache-2.0
15,063
5ece2b919922690c19e7ca78357c60316390cd93
Python
py
#!/usr/bin/env python # encoding: utf-8 # The MIT License (MIT) # Copyright (c) 2017-2018 CNRS # 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 limita...
pyannote/audio/embedding/models/clopinet.py
MIT
11,434
5ed4f65c1272d213490c71a79633fab900597924
Python
py
import os import torch from torch.utils.ffi import create_extension sources = ['src/lib_cffi.cpp'] headers = ['src/lib_cffi.h'] extra_objects = ['src/bn.cu.obj'] #['src/bn.o'] with_cuda = True this_file = os.path.dirname(os.path.realpath(__file__)) extra_objects = [os.path.join(this_file, fname) for fname in extra_o...
modules/build_windows.py
BSD-3-Clause
658
12f17021b3cb74b5a9d7b8dc51ce59ababca79ad
Python
py
# The based unit of graph convolutional networks. import torch import torch.nn as nn import torch.nn.functional as F class ConvTemporalGraphical(nn.Module): r"""The basic module for applying a graph convolution. Args: in_channels (int): Number of channels in the input sequence data out_channel...
net/utils/tgcn_origin_mask_softmax.py
BSD-2-Clause
2,912
fee938d119bbe55d1ff17562027b70e1f0abf156
Python
py
# coding: utf-8 import argparse import time import math import os import torch import torch.nn as nn import torch.onnx import data import model parser = argparse.ArgumentParser(description='PyTorch Wikitext-2 RNN/LSTM Language Model') parser.add_argument('--data', type=str, default='./data/wikitext-2', ...
word_language_model/main.py
BSD-3-Clause
9,985
03bfaeb87eef2585aca6084ccae24b77d128d3c8
Python
py
# Copyright (c) OpenMMLab. All rights reserved. import pytest import torch from mmcv.ops.multi_scale_deform_attn import ( MultiScaleDeformableAttention, MultiScaleDeformableAttnFunction, multi_scale_deformable_attn_pytorch) _USING_PARROTS = True try: from parrots.autograd import gradcheck except ImportErr...
tests/test_ops/test_ms_deformable_attn.py
Apache-2.0
6,657
fee94c575cf107565ebbf355d220910897efd2db
Python
py
import pytest import torch from torch.autograd import gradcheck import kornia import kornia.testing as utils # test utils from kornia.testing import assert_close @pytest.mark.parametrize("batch_size", [1, 2, 5]) def test_get_perspective_transform(batch_size, device, dtype): # generate input data h_max, w_ma...
test/geometry/transform/test_imgwarp.py
ECL-2.0,Apache-2.0
24,846
df9fe54749873420acb91ab5748aef7ac4cb73fa
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
ai_ct_scans/dino/eval_video_segmentation.py
MIT
12,672
fee96aeef3b82a4afb6dda035e13fa807a9c2250
Python
py
import warnings from typing import Optional, Tuple import torch from kornia.utils import _extract_device_dtype, safe_inverse_with_mask from .conversions import convert_points_from_homogeneous from .epipolar import normalize_points from .linalg import transform_points TupleTensor = Tuple[torch.Tensor, torch.Tensor] ...
kornia/geometry/homography.py
ECL-2.0,Apache-2.0
7,555
fee972b59b3c99c8819c4c446bbe8239b3f89b44
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/utilities/nd_fotmax_for_inference.py
Apache-2.0
815
d726ece1bc96a65e8b9f8234807eddf387aeccbf
Python
py
from optparse import OptionParser import os, time, random, pickle import torch import numpy as np from src.util.data_operator import read_conll, write_conll, vocab from src.util.config_reader import Configurable import importlib import pdb if __name__ == '__main__': random.seed(666) np.random.seed(666) t...
gap/test_driver.py
BSD-3-Clause
3,143
6b4018be8bd7489b34ec234483f6b7e8c4c65c04
Python
py
# Copyright (c) 2020 NVIDIA CORPORATION. # Copyright (c) 2018-2020 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 wit...
models_dev/mink_transformer_voxel.py
MIT
14,799
fee98467ad47141b32e94ea8525cbe8a3e107988
Python
py
import os import time import numpy as np import torch import torchvision from torchvision.transforms import ToTensor from appfl.config import * from appfl.misc.data import * from appfl.misc.utils import * from models.cnn import * import appfl.run_serial as rs import appfl.run_mpi as rm from mpi4py import MPI impor...
examples/mnist.py
MIT
6,291
45d5db5076c5f95ffa268a542aab9a4dc649cd52
Python
py
from torch.optim.optimizer import Optimizer, required import torch import math import numpy as np class LRangerMod(Optimizer): # AMSGrad/Adam + AdaMod + QH Momentum + Iterate Averaging + Lookahead + Rule of Thumb Linear Warmup (instead of RAdam Rectification) + P from PAdam def __init__(self, params, lr=1e-...
models/optim/optimizers.py
MIT
56,673
106a295d4157c965d3a731ed518fb3fbf65915b7
Python
py
from setuptools import setup from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension setup( name='deep_hough', ext_modules=[ CUDAExtension('deep_hough', [ 'deep_hough_cuda.cpp', 'deep_hough_cuda_kernel.cu', ], extra_compile_args={'cxx': ...
utils/_cdht/setup.py
MIT
419
fee9a54c890ae04dd39ea5c888e95f0df7edea27
Python
py
import typing as t from typing import TYPE_CHECKING import torch from simple_di import inject from simple_di import Provide from bentoml import Tag from bentoml import Model from bentoml.exceptions import BentoMLException from bentoml.exceptions import MissingDependencyException from ..models import PT_EXT from ..mo...
bentoml/_internal/frameworks/pytorch_lightning.py
Apache-2.0
7,526
b26b861b83d8a9c204852ecf3e0dcfc3717012fa
Python
py
import unittest from torchtext.data.metrics import bleu_score class TestTorchtext(unittest.TestCase): def test_bleu_score(self): candidate = [['I', 'love', 'Kaggle', 'Notebooks']] refs = [[['Completely', 'Different']]] self.assertEqual(0, bleu_score(candidate, refs))
tests/test_torchtext.py
Apache-2.0
301
f9fbf76f48f629dfed65985f8afa1c2c2edfe082
Python
py
import torch import torch.nn as nn from marl.utils import init """ Modify standard PyTorch distributions so they are compatible with this code. """ FixedCategorical = torch.distributions.Categorical old_sample = FixedCategorical.sample FixedCategorical.sample = lambda self: old_sample(self).unsqueeze(-1) log_prob_c...
marl/rlcore/distributions.py
MIT
961
feea030eb20117e3867ffdfc7b66ce84a5c65425
Python
py
# -*- coding: utf-8 -*- """“TextLSTM-Torch.ipynb”的副本 Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1K75NsbkuejOzp2tfsXGDJxP-nQl9V0DC """ ''' code by Tae Hwan Jung(Jeff Jung) @graykode, modify by wmathor ''' import torch import numpy as np import to...
3-2.TextLSTM/TextLSTM-Torch.py
MIT
2,735
ff74ce2fbeb33e03c27cb45adea7ec9bd33ec358
Python
py
#!/usr/bin/env python3 # 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. """Loss functions.""" import torch.nn as nn from pycls.core.config import cfg # Supported loss functions _loss_funs...
pycls/core/losses.py
MIT
714
feea0b6f684ca7e60b9c20aae77b56fc307b205e
Python
py
import torch import torch.nn as nn import numpy as np from torch.optim import AdamW import torch.optim as optim import itertools from model.warplayer import warp from torch.nn.parallel import DistributedDataParallel as DDP from model.IFNet2F import * import torch.nn.functional as F from model.loss import * device = to...
model/RIFE2F.py
MIT
9,667
feea1df72f089809e4124bbf6b051afa4b9c5cd5
Python
py
"""From the project root directory (containing data files), this can be run with: Boolean logic evaluation: python -m spinn.models.fat_classifier --training_data_path ../bl-data/pbl_train.tsv \ --eval_data_path ../bl-data/pbl_dev.tsv SST sentiment (Demo only, model needs a full GloVe embeddings file to do well...
python/spinn/models/fat_classifier.py
Apache-2.0
30,757
804d6983d0ab86b72ae3f189cb33c0e8fff19bb3
Python
py
# -*- encoding: utf-8 -*- """ @File : DQN_brain.py @Time : 2020/12/4 @Author : Yuan Yifu """ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F MEMORY_CAPACITY = 2000 N_STATE = 4 N_ACTIONS = 2 EPSILON = 0.9 LR = 0.01 REPLACE_COUNTER = 100 BATCH_SIZE = 32 GAMMA = 0.9 class Ne...
DQN/CartPole/DQN_brain.py
MIT
2,753
feea298fda9086d758aa991fce9281751e0298f3
Python
py
## Portions of Code from, copyright 2018 Jochen Gast from __future__ import absolute_import, division, print_function import os import socket import re #from pytz import timezone from datetime import datetime import fnmatch import itertools import argparse import sys import six import unicodedata import json import i...
tools.py
Apache-2.0
15,246
feea3dd241d956d227c4f00aa1ad125875d5106a
Python
py
#!/usr/bin/env python3 # # # Copyright (c) 2021 Facebook, inc. and its affiliates. All Rights Reserved # # from ast import dump import copy import multiprocessing as mp import argparse import pickle import numpy as np import random import torch import torch.distributed as dist import sys import os import time import re...
uimnet/workers/mog.py
MIT
5,191
03f3df4f8f67adfdc0faa5cc70ab431db46cfcc1
Python
py
import torch.nn as nn import torch.optim as optim from torch.optim.lr_scheduler import MultiStepLR, StepLR from resnet_with_block import cifar_resnet32, cifar_se_resnet32,\ cifar_srm_resnet32, cifar_srm_with_corr_matrix_resnet32, srm_resnet50, se_resnet50, resnet50, oursrm_resnet50, cifar_srm_with_median_resnet32 im...
experiments.py
MIT
7,165
feeaad1d6e1f36f48b379131a42de400cf41efa3
Python
py
import torch.nn as nn from mmcv.utils.parrots_wrapper import _BatchNorm from mmedit.models.common import MaskConvModule from mmedit.models.registry import COMPONENTS @COMPONENTS.register_module() class PConvEncoder(nn.Module): """Encoder with partial conv. About the details for this archetecture, pls see: ...
mmedit/models/backbones/encoder_decoders/encoders/pconv_encoder.py
Apache-2.0
4,187
52f3c2c16e83672b8ffd5f4f4d633e17bd5bc035
Python
py
# -*- coding: utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the...
built-in/TensorFlow/Research/cv/image_classification/Cars_for_TensorFlow/automl/vega/search_space/networks/pytorch/utils/anchor_utils/anchor_target.py
Apache-2.0
8,923
6b10dd34e33d4af7d5e8f6f9d90c285879c524fe
Python
py
import time from datetime import timedelta import pytest import numpy as np from torch.optim import Adam from flights_time_series_dataset import FlightSeriesDataset, FlightsDataset from skorch.callbacks import EarlyStopping from skorch.dataset import CVSplit from sklearn.metrics import r2_score # mean_squared_error f...
tests/test_quantum_lstm.py
Unlicense
3,305
45f63e96bbc2b4435ef68a0d26b2ef139b417198
Python
py
import sys sys.path.append('..') import fewshot_re_kit import torch from torch import autograd, optim, nn from torch.autograd import Variable from torch.nn import functional as F import numpy as np class CausalConv1d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=2, dilation=2): sup...
models/snail.py
MIT
5,430
fdf88f4426ed836307e84fbcc77f7db74c2d80c7
Python
py
from torch.utils.data import Subset from PIL import Image from torchvision.datasets import MNIST from base.torchvision_dataset import TorchvisionDataset from .preprocessing import create_semisupervised_setting import torch import torchvision.transforms as transforms import random class MNIST_Dataset(TorchvisionDatas...
src/datasets/mnist.py
MIT
3,695
feead5eead461ab2c38f6a05f004ec17e76c4b81
Python
py
""" Utilities for working with the local dataset cache. This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp Copyright by the AllenNLP authors. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import json import logging import os impor...
transformers/file_utils.py
Apache-2.0
11,684
feead9ed742260a9807f0fd91824c50499e996b1
Python
py
import mmcv import numpy as np import torch from torch.nn.modules.utils import _pair from .builder import ANCHOR_GENERATORS @ANCHOR_GENERATORS.register_module() class AnchorGenerator(object): """Standard anchor generator for 2D anchor-based detectors. Args: strides (list[int] | list[tuple[int, int]]...
mmdet/core/anchor/anchor_generator.py
Apache-2.0
31,208
12d6f50b2de43788dad888d6c7aef1c9e8e1c8a9
Python
py
# Copyright (c) 2020 Graphcore Ltd. All rights reserved. import pytest import os import subprocess import torch import numpy as np import poptorch from torchvision import transforms from pathlib import Path import shutil import sys import re import random sys.path.append('..') from datasets.preprocess import NormalizeT...
applications/pytorch/cnns/datasets/test_data.py
MIT
15,639
feeb24d89063a2a99f82e15b3f0979acb8b428f1
Python
py
# Copyright (c) 2021 Xiaomi Corporation (authors: Fangjun Kuang) from typing import Dict from typing import List from typing import Optional import math import k2 import torch def _intersect_device(a_fsas: k2.Fsa, b_fsas: k2.Fsa, b_to_a_map: torch.Tensor, sorted_match_a: bool): '''This ...
snowfall/decoding/lm_rescore.py
Apache-2.0
12,581
1edef233c9760a7dcf5221f171d565e7721df116
Python
py
from __future__ import division import numpy as np import torch from torch import nn import torch.nn.functional as F from inverse_warp import inverse_warp def photometric_reconstruction_loss(tgt_img, ref_imgs, intrinsics, depth, explainability_mask, pose, ...
loss_functions.py
MIT
5,674
24cbefa4d038de57e007efbfac67d68c10b50e5e
Python
py
import warnings from collections import OrderedDict from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as cp from mmcv.cnn import build_norm_layer, constant_init, trunc_normal_init from mmcv.cnn.bricks.transformer import FFN, build_dropout from mm...
mmdet/models/backbones/swin.py
Apache-2.0
30,173
fce01664ad04db71de8607e3651ec247dadff94c
Python
py
# -*- coding: utf-8 -*- __author__ = 'ooo' __date__ = '2018/12/15 12:17' import time import argparse import shutil import os import random from datetime import datetime from collections import namedtuple from PIL import Image import warnings import torch from torch import nn from torch.utils import data import torchv...
factory/data_factory.py
MIT
20,254
e982d73b7a49f7cc47bf80b5e838fd45c7172c2d
Python
py
import torch.nn as nn import torch.optim as optim import torch.nn.functional as F class Brain: def __init__(self, net, config): self.net = net self.value_loss_coef = config.brain.value_loss_coef self.entropy_coef = config.brain.entropy_coef self.max_grad_norm = config.brain.max_gra...
2_PG/2-2_A2C/brain.py
MIT
1,821
5e364bf006880d9390316f5acc3bf866fc39aac4
Python
py
import argparse import torch import torch.nn.functional as F from torch.utils.data import DataLoader from torch_geometric.utils import negative_sampling import torch_geometric.transforms as T from torch_geometric.nn import GCNConv, SAGEConv from ogb.linkproppred import PygLinkPropPredDataset, Evaluator from logger ...
baseline_gcn.py
MIT
10,400
0398b1a9246ab9dd96030b7828dbaf8a20a6ffa6
Python
py
""" Copyright 2020 The Microsoft DeepSpeed Team """ import torch from .builder import CUDAOpBuilder class TransformerBuilder(CUDAOpBuilder): BUILD_VAR = "DS_BUILD_TRANSFORMER" NAME = "transformer" def __init__(self, name=None): name = self.NAME if name is None else name super().__init__(n...
op_builder/transformer.py
MIT
1,263
a94c6da62e399937b917e0f41b8323317d4b1b46
Python
py
import os.path as osp import warnings from collections import OrderedDict import mmcv import numpy as np from mmcv.utils import print_log from terminaltables import AsciiTable from torch.utils.data import Dataset from mmdet.core import eval_map, eval_recalls from .builder import DATASETS from .pipelines import Compos...
mmdet/datasets/custom.py
Apache-2.0
13,691
feeba09b0f97a28dab293bbd33a768dcfc81c68b
Python
py
import asyncio import websockets import json import sys import plotly.graph_objs as go import plotly.offline as offline import numpy as np from pytorch_pretrained_bert.tokenization import load_vocab, BertTokenizer from pytorch_pretrained_bert.modeling import BertForPreTraining, BertConfig, BertForMaskedLM fr...
BERTRAM/mi_mask_prediction.py
MIT
4,271
4bc3d3fd38e94eeed13ea364fe1d4943c9e44138
Python
py
# Copyright 2021 AlQuraishi Laboratory # Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
openfold/model/template.py
Apache-2.0
9,755
dfcc67571d43c428606fa18ad09566c1fbac5975
Python
py
import torch.nn as nn import torch import torch.nn.functional as F # *********************A(特征)量化(二值)*********************** class BinActive(torch.autograd.Function): def forward(self, input): self.save_for_backward(input) size = input.size() mean = torch.mean(input.abs(), 1, keepdim=True)...
quantization/WbWtAb/models/nin_bn_conv.py
MIT
3,870
24ece1e6a073a05187a4dd530e90e3595f7e494c
Python
py
import random from collections import namedtuple, deque import numpy as np import torch Transition = namedtuple('Transition', ('state', 'action', 'next_state', 'reward', 'is_done')) class ReplayMemory(object): def __init__(self, maxlen): self.memory = deque([], maxlen=maxlen) ...
Agents/LearningAgents/Memory.py
MIT
8,884
529f146a377d7e6fc514731164f589f3dcee63f8
Python
py
from __future__ import print_function import argparse import torch from torchvision import datasets, transforms from torch.utils.data import DataLoader from models import vgg, resnet, densenet import numpy as np import os import sys from tqdm import tqdm from utils import * if __name__ == '__main__': parser = argpa...
imagenet/eval.py
MIT
4,014
5e8ede2b1076cf31f56630b9fdde06a8ef7d890f
Python
py
""" Author: yvon Date: 2021-08-05 17:41:49 LastEditTime: 2021-12-06 15:31:10 LastEditors: Please set LastEditors Description: 批量测试文件夹中的图片 12.6号验证无误,后续应该不会再更新。 FilePath: /lanenet-lane-detection-pytorch/test_lanenet.py """ # import argparse import os import os.path as ops # import time import cv2 # from sklearn import ...
test_lanenet.py
MIT
5,992
feebcde9c3433de47ff5b4a8582d3e48f5c15078
Python
py
import argparse import atexit import copy import datetime import numpy as np import os import torch import tensorboardX from functools import partial from prob_mbrl import utils, models, algorithms, envs if __name__ == '__main__': parser = argparse.ArgumentParser("Deep-PILCO with moment matching") parser.add_...
examples/deep_pilco_mm.py
MIT
11,148
45e78a6ef22baf9fbbb3878b1ccd10c7947afa8f
Python
py
import os import logging from PIL import Image import numpy as np import sklearn.datasets import joblib from torch.utils.data import Dataset, DataLoader from torchvision import transforms, datasets import skorch.dataset from skorch.utils import to_numpy from utils.helpers import set_attributes from .helpers import t...
utils/data/datasets.py
MIT
13,146
24fc3ebcbfec638eaf5880a13f0a25c6a95cd2f1
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import math import numpy as np import torch from torch import nn from maskrcnn_benchmark.structures.bounding_box import BoxList class BufferList(nn.Module): """ Similar to nn.ParameterList, but for buffers """ def __init__(self...
maskrcnn_benchmark/modeling/rpn/anchor_generator.py
Xnet,X11
8,907
feebedbf54bfb53006467c0c761aec2692ad455d
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import copy import logging import numpy as np from typing import List, Union import torch import detectron2.data.detection_utils as utils import detectron2.data.transforms as T from detectron2.config import configurable from .detection_utils impor...
projects/PointSup/point_sup/dataset_mapper.py
Apache-2.0
4,813
52b9bd4ce19d51e07f98aa9adf36c41f6ddc22af
Python
py
import torch from torch.nn import functional as F from openpose.model.matcher import Matcher from openpose.model.balanced_positive_negative_sampler import ( BalancedPositiveNegativeSampler, ) from openpose.structures.boxlist_ops import boxlist_iou from openpose.modeling.utils import cat from openpose.layers impor...
openpose/model/roi_heads/vpose_head/vpose_loss.py
MIT
7,025
feec08bdec128863b4bcbcb84f6676204b70935d
Python
py
import os import torch import models def set_seed(seed, cuda): torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark = True torch.manual_seed(seed) if cuda: torch.cuda.manual_seed(seed) def SSE(logits, label): target = torch.zeros_like(logits) target[torch.arange(target.size(0)).l...
examples/WAGE/utils.py
MIT
2,973
feec1558c82b3373e1448e3c0a14b761f164409e
Python
py
"""Segmentation task interface module. This module contains a class that defines the objectives of models/trainers for segmentation tasks. """ import logging from typing import Optional # noqa: F401 import numpy as np import PIL.Image import torch import tqdm import thelper.concepts import thelper.utils from thelpe...
thelper/tasks/segm.py
Apache-2.0
8,891
feec22ecb3665d0f23dd4a31e2d945f4898b74a9
Python
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import torch from torch import nn, autograd from torch.utils.data import DataLoader, Dataset import numpy as np import random from sklearn import metrics import sys import os from timeit import default_timer as timer class DatasetSplit(Dataset): ...
models/Update.py
MIT
2,869
2486c0567e063aef73a99c2e05dcabfa5aa90e84
Python
py
#!/usr/bin/env python # coding: utf-8 # # Author: Kazuto Nakashima # URL: https://kazuto1011.github.io # Date: 08 February 2019 from __future__ import absolute_import, print_function import os.path as osp import cv2 import numpy as np import torch from PIL import Image from torch.utils import data from .base i...
libs/datasets/voc.py
MIT
4,766
7c36c3ce6d3700cede361a9dbee146e7880078cc
Python
py
from __future__ import print_function from six.moves import range import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import torch.backends.cudnn as cudnn from PIL import Image from tqdm import tqdm import pickle import os import numpy as np import glob import scipy.misc...
OP-GAN/code/trainer.py
MIT
25,808
feec41681fea71e37708f27ef55ac87e2e175ce6
Python
py
# Copyright xmuspeech (Author: Snowdar 2020-02-05) import sys import os import torch import torch.nn.functional as F subtools = '/data/lijianchen/workspace/sre/subtools' # subtools = os.getenv('SUBTOOLS') sys.path.insert(0, '{}/pytorch'.format(subtools)) from libs.nnet import * import libs.support.utils as utils c...
pytorch/model/xvector.py
Apache-2.0
5,469
feec4d8d98894a2e15fbf2e1112632b39d5cba31
Python
py
from escnn.nn.modules.basismanager import BasisManager from collections import defaultdict import torch from scipy import stats import math __all__ = ["generalized_he_init", "deltaorthonormal_init"] def _generalized_he_init_variances(basismanager: BasisManager): r""" Compute the variances of the weigh...
escnn/nn/init.py
BSD-3-Clause
5,451
6b0cdca8b38aa0de50d93a2580d6a8924358c4b1
Python
py
import torch import torch.nn as nn import torch.nn.functional as func class DepthWiseSeparableConv1d(nn.Module): r"""Depthwise separable 1D convolution. Analogous functionality to :class:`torch.nn.Conv1d`. Args: in_channels (int): number of input channels. out_channels (int): number of output channels....
torchsupport/modules/separable.py
MIT
1,862
804911a4e4c25e12c6674f4894351301903c0444
Python
py
from typing import Any, Dict, Optional, Tuple, Type import pytest import torch from torch.autograd import gradcheck import kornia import kornia.testing as utils # test utils from kornia.augmentation import ( AugmentationSequential, CenterCrop, ColorJiggle, ColorJitter, Denormalize, LongestMax...
test/augmentation/test_augmentation.py
ECL-2.0,Apache-2.0
124,458
28bd7771a56dce256a273403446b27a9fefa05c9
Python
py
import numpy as np import torch import torch.optim as optim import torch.nn as nn from torch.autograd import Variable from torch.nn import functional as F import time import re import os import sys import cv2 import bdcn from datasets.dataset import Data import argparse import cfg from matplotlib import pyplot as plt ...
test.py
MIT
3,370
24c171fb6f4bd452e860e193527863990c7a1419
Python
py
from argparse import Namespace import csv from logging import Logger import pickle import random from typing import List, Set, Tuple import os from rdkit import Chem import numpy as np from tqdm import tqdm from joblib import Parallel, delayed from chemprop.data.data import MoleculeDatapoint, MoleculeDataset from che...
dglt/contrib/moses/moses/model/pred_mpnn/utils.py
MIT
13,952
feeca11b719300a1a7d183dfdc22b2c343a86e50
Python
py
from typing import List import torch import torch.nn as nn from tqdm import tqdm from chemprop.data import MoleculeDataLoader, MoleculeDataset, StandardScaler def predict(model: nn.Module, data_loader: MoleculeDataLoader, disable_progress_bar: bool = False, scaler: StandardScaler...
chemprop/train/predict.py
MIT
1,413
5f0e71011f23a211a87515f980255b2d9a373b03
Python
py
# Copyright 2021 Faranak Shamsafar # # 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 a...
models/submodule.py
Apache-2.0
10,865
feecaea15da95321d89bb0d8062393aa631b517a
Python
py