content
stringlengths
200
198k
repo
stringlengths
4
186
path
stringclasses
1 value
license
stringclasses
101 values
size
int64
200
198k
sha
stringlengths
40
40
lang
stringclasses
1 value
ext
stringclasses
1 value
import math from pathlib import Path import torch import torch.nn as nn import torch.utils.model_zoo as model_zoo MODEL_URLS = {"mobilenetv2": "https://github.com/rdroste/unisal/raw/master/unisal/models/weights/mobilenet_v2.pth.tar"} # Source: https://github.com/tonylins/pytorch-mobilenet-v2 def conv_bn(inp, oup, ...
gazenet/models/shared_components/mobilenetv2/model.py
MIT
6,922
28ee80b33cbd53d97fac86f4158410ff64a85371
Python
py
import numpy as np import torch from torch import nn from torch.nn import init class SimplifiedScaledDotProductAttention(nn.Module): ''' Scaled dot-product attention ''' def __init__(self, d_model, h,dropout=.1): ''' :param d_model: Output dimensionality of the model ...
model/attention/SimplifiedSelfAttention.py
MIT
2,937
29a671925fcc602beef43d74cb59ec06feef3153
Python
py
# Copyright 2020 - 2021 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 wri...
monai/transforms/io/array.py
Apache-2.0
13,031
5f236452ce867c9381528132e85892fff3149823
Python
py
import typing as _typing import torch import torch_geometric from autogl.data import Dataset, InMemoryDataset from autogl.data.graph import GeneralStaticGraph from autogl.data.graph.utils import conversion def to_pyg_dataset( dataset: _typing.Union[Dataset, _typing.Iterable[GeneralStaticGraph]] ) -> Dataset[t...
autogl/datasets/utils/conversion/_to_pyg_dataset.py
MIT
1,435
29a6cd1e4b82c2134e0e5a92ef8cf7560332c3f1
Python
py
""" CUDA / AMP utils Hacked together by / Copyright 2020 Ross Wightman """ import torch try: from apex import amp has_apex = True except ImportError: amp = None has_apex = False from .clip_grad import dispatch_clip_grad class ApexScaler: state_dict_key = "amp" def __call...
timm/utils/cuda.py
Apache-2.0
1,758
5e8e7efc9c11e823428039dab3e73b8bc7b1a16a
Python
py
from data import config from train import bilstm from models.NER import NER from build_dataloader import corpus, test_iter import numpy as np import torch from torch import nn from torch.optim import Adam checkpoint_path = config.CHECKPOINT3 def accuracy(preds, y): max_preds = preds.argmax(dim=1, ...
src/evaluate.py
MIT
1,753
b2bdfa533c1c58f2407c611a30145ec74f1dd1c5
Python
py
import torch from nanodet.util import util_mixins class SamplingResult(util_mixins.NiceRepr): """ Example: >>> # xdoctest: +IGNORE_WANT >>> self = SamplingResult.random(rng=10) >>> print('self = {}'.format(self)) self = <SamplingResult({ 'neg_bboxes': torch.Size([1...
nanodet/model/head/sampler/sampling_result.py
Apache-2.0
3,025
f9bf11f60276664f7ee7a7e95947506a977b9f40
Python
py
import os import sys import unittest sys.path.append(os.getcwd()) import numpy as np import torch from iqa import psnr from libs.basicsr_psnr_ssim import calculate_psnr IMAGE_SHAPES = ( ('CHW', (3, 128, 128)), ('CHW', (1, 128, 128)), ('HWC', (128, 128, 3)), ('HWC', (128, 128, 1)), ) class PSNRTestC...
tests/test_psnr.py
Apache-2.0
2,890
106ae37c43676469895062025e120357cfafbb13
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. import functools import os from typing import Callable, Dict, List, Optional, Tuple import torch import torch.distributed as dist from torch ...
oslo/torch/nn/parallel/data_parallel/_reduce_scatter_bucketer.py
Apache-2.0
8,448
ff604db5eae2fd0db21777589cae3fd3a30573db
Python
py
import argparse import time import torch from rl_credit.utils.penv import ParallelEnv import script_utils as utils # Parse arguments parser = argparse.ArgumentParser() parser.add_argument("--env", required=True, help="name of the environment (REQUIRED)") parser.add_argument("--model", required=T...
rl_credit/scripts/evaluate.py
MIT
3,846
d7577f96beb52d105b0661f4e33db1be19c3d17c
Python
py
import os import json import torch import numpy as np import hifigan from model import FastSpeech2, ScheduledOptim def get_model(args, configs, device, train=False): (preprocess_config, model_config, train_config) = configs model = FastSpeech2(preprocess_config, model_config).to(device) if args.restore...
utils/model.py
MIT
3,325
b2576aed77c0e4ea5393f8c207b408a13596d672
Python
py
import os # import torchsummary from functools import partial import pickle import fire import torchaudio from pl_bolts.models.self_supervised.resnets import resnet18 from pl_bolts.optimizers.lars_scheduling import LARSWrapper from pl_bolts.optimizers.lr_scheduler import LinearWarmupCosineAnnealingLR from pytorch_ligh...
semi_supervised.py
MIT
27,602
29a713d05cdc7a6e6b072f256a90c0e7aaf6b43b
Python
py
# Copyright 2021 TUNiB Inc. import os import random import numpy import torch import torch.distributed as dist from datasets import load_dataset from torch.optim import Adam from torch.utils.data import DataLoader from transformers import GPT2Tokenizer from oslo.models.gpt2.modeling_gpt2 import ( GPT2ForSequence...
tests/gpt2/gpt2_test_3d_training_with_fusion.py
Apache-2.0
7,758
1e70498a8759e260e7509bd75387c903b129ee1d
Python
py
# -*- coding: utf-8 -*- # """*********************************************************************************************""" # FileName [ evaluate.py ] # Synopsis [ main objective evaluation script for any-to-any voice conversion ] # Author [ Wen-Chin Huang (https://github.com/unilight) ] # Copyr...
s3prl/downstream/a2a-vc-vctk/evaluate.py
Apache-2.0
10,261
d7377c9127df9b3a3c1b8cd49511b4ca115f4f17
Python
py
# # export a trained model to huggingface format # ------------------------------- import argparse import os import sys sys.path.append(os.getcwd()) import torch from matchmaker.utils import * from matchmaker.models.all import get_model, get_word_embedder, build_model from typing import Dict, Tuple, List from ma...
matchmaker/utils/export_to_huggingface.py
Apache-2.0
2,950
29a72be7f9efb343dcb197cae7f66086b9521cb1
Python
py
import pytest import torch from pytorch_lightning.metrics.utils import class_reduce, reduce def test_reduce(): start_tensor = torch.rand(50, 40, 30) assert torch.allclose(reduce(start_tensor, 'elementwise_mean'), torch.mean(start_tensor)) assert torch.allclose(reduce(start_tensor, 'sum'), torch.sum(star...
tests/metrics/functional/test_reduction.py
Apache-2.0
1,092
03a34f6c5a25b867b2d627bf3c514ceb37dd3f63
Python
py
import argparse import os import torch import torch.backends.cudnn as cudnn import torchvision from model import Net parser = argparse.ArgumentParser(description="Train on market1501") parser.add_argument("--data-dir",default='data',type=str) parser.add_argument("--no-cuda",action="store_true") parser.ad...
traffic_monitoring/deep_sort/deep/test.py
Apache-2.0
2,493
29a7370acce4061e8bc77f621b550f269c2751c9
Python
py
"""lstm_utils.py contains utility functions for running LSTM Baselines.""" import os from typing import Any, Dict, List, Tuple import numpy as np import torch from torch.autograd import Variable from torch.utils.data import Dataset import utils.baseline_config as config use_cuda = torch.cuda.is_available() if use_c...
utils/lstm_utils.py
BSD-3-Clause-Clear
7,373
b26760f618ba8ff28a869ce4decd3e87096ee7bd
Python
py
""" Robust loss functions for training accurate deep neural networks (DNNs) in the presence of noisy (incorrect) labels. Extracted [Normalized Loss Functions for Deep Learning with Noisy Labels](https://arxiv.org/abs/2006.13554) paper implemented on https://github.com/HanxunH/Active-Passive-Losses/blob/master/loss.py ...
train/losses/APL_losses.py
MIT
18,276
1e0ba3ef47c0b99513b5576906c273f7454ea0cc
Python
py
import argparse import os import os.path as osp import pickle import shutil import tempfile import mmcv import torch import torch.distributed as dist from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import get_dist_info, init_dist, load_checkpoint from mmdet.core import wrap_fp16_m...
test.py
Apache-2.0
15,527
29a779e315a36f00f2ebd348d3c54b022f0ccf87
Python
py
import time import torch # Project imports from utils import * from options import TrainOptions from data_loaders import create_dataloader from methods import create_method class Trainer: """ Trains any of the model methods in methods/ using any of the losses in losses/. Initialize the t...
train.py
MIT
3,637
24a6ceaa6ad3a63b821c739a4e853b4bfbbe8d5a
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. # 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_...
projects/continual-lm/old_util.py
BSD-3-Clause
3,269
29a797de701c771bfe426d3700b8cbb55166369c
Python
py
import torch class TokenEmbedding(torch.nn.Module): """ Token Embedding It can be embedding matrix, language model (ELMo), neural machine translation model (CoVe) and features. * Args: vocab: Vocab (rqa.tokens.vocab) """ def __init__(self, vocab): super(TokenEmbedding, self...
claf/tokens/embedding/base.py
MIT
628
5f97ebc44f51040c1e10fe702ea9cad06d5df67e
Python
py
# These operations are based on the implementation of https://github.com/JiahuiYu/slimmable_networks import torch.nn as nn from utils.config import FLAGS def make_divisible(v, divisor=1, min_value=1): if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * d...
models/randwidth_ops.py
MIT
5,110
7c119fb209e5ea3c12d849e24bd65c0b74cd188e
Python
py
import os import sys import re import six import math import lmdb import torch from augmentation.weather import Fog, Snow, Frost from augmentation.warp import Curve, Distort, Stretch from augmentation.geometry import Rotate, Perspective, Shrink, TranslateX, TranslateY from augmentation.pattern import VGrid, HGrid, Gri...
dataset2.py
Apache-2.0
20,656
101d89c7fd01255d36778bc3aa1a768821610a56
Python
py
import argparse from collections import defaultdict import logging import copy import numpy as np import torch import torch.optim as optim from torch.nn import functional as F from tqdm import trange from torchsummary import summary from experiments.nyuv2.data import nyu_dataloaders from experiments.nyuv2.metrics imp...
experiments/nyuv2/trainer_cnn.py
MIT
8,751
347e78355e79ddb2b0f9db6b2ec8236fe0733295
Python
py
import numpy as np import torch from torch.autograd import Variable from pytorch2keras.converter import pytorch_to_keras import torchvision class VGG(torchvision.models.vgg.VGG): def __init__(self, *args, **kwargs): super(VGG, self).__init__(*args, **kwargs) def forward(self, x): x = self.fea...
tests/models/vgg11.py
MIT
1,287
f9da7c744975883ded7dbbf14218730113444138
Python
py
import os import re import yaml import textwrap import torch from torch.testing._internal.common_utils import TestCase, run_tests from collections import namedtuple path = os.path.dirname(os.path.realpath(__file__)) aten_native_yaml = os.path.join(path, '../aten/src/ATen/native/native_functions.yaml') all_operators_...
test/test_namedtuple_return_api.py
Intel
7,765
345431d5b250827d287ab5dd71d6c8df3205bcf3
Python
py
#!/usr/bin/python # encoding: utf-8 from PyQt5 import QtWidgets from multiprocessing import Process, Manager, freeze_support from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QSlider, QPushButton, QDesktopWidget, QVBoxLayout, \ QHBoxLayout, QComboBox, QTextBrowser, QTextEdit, QLabel, QDialog, QFileDia...
entrance.py
MIT
4,863
29a840f6948dfd1d02a1847d9c1a74ce5ed3fc35
Python
py
import torch import os import glob from torch.utils.data import Dataset import numpy as np from PIL import Image from torchvision import transforms from xmuda.data.utils.preprocess import vox2pix, compute_local_frustums, compute_CP_mega_matrix from xmuda.data.semantic_kitti.params import kitti_class_cluster_4, kitti_cl...
xmuda/data/semantic_kitti/kitti_dataset.py
Apache-2.0
12,195
4282f765c26cc45ae82090a2cdb3fdd24d495f77
Python
py
""" Learning to Count Objects in Natural Images for Visual Question Answering Yan Zhang, Jonathon Hare, Adam Prügel-Bennett ICLR 2018 This code is from Yan Zhang's repository. https://github.com/Cyanogenoid/vqa-counting/blob/master/vqa-v2/counting.py MIT License """ import torch import torch.nn as nn from torch.autogr...
counting.py
MIT
7,594
ff86e2c8d850a71f0dc2aeea435aa53eb0c2891e
Python
py
# -*- coding: utf-8 -*- """ PROJECT 1 - DEEP LEARNING models.py Authors: Lucia Montero Sanchis, Ada Pozo and Milica Novakovic Deep Learning models """ import torch import torch.nn as nn from bci_dataset import * #torch.set_default_tensor_type('torch.FloatTensor') #################################################...
Projects/Project1/Submission_code_DL1/models.py
MIT
9,576
d7a7ee7a0113aceecfc6b01b2a6ddde2150f2a2f
Python
py
from __future__ import print_function import torch import torch.nn as nn import torch.nn.parallel import torch.utils.data from torch.autograd import Variable import numpy as np import torch.nn.functional as F import sys sys.path.append("./expansion_penalty/") import expansion_penalty_module as expansion sys.path.append...
model.py
Apache-2.0
6,414
d79c38f34ed5f7c07d68790f3fd4322f35adef4a
Python
py
# Dataset utils and dataloaders import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch import torch.nn.functional ...
detector/yolov5/utils/datasets.py
MIT
43,872
29a8812a20a2c32c4957977ffe74b8f8eeea0035
Python
py
#!/usr/bin/env python3 import logging import numpy as np import time import torch import cv2 logger = logging.getLogger(__name__) def retry_load_images(image_paths, retry=10, backend="pytorch"): """ This function is to load images with support of retrying for failed load. Args: image_paths (li...
slowfast/slowfast/datasets/utils.py
MIT
2,946
29a897468616f4f503639ee310ae49a3ddf2ec71
Python
py
import torch import torch.nn as nn OPS = { 'none' : lambda C, stride, affine: Zero(stride), 'avg_pool_3x3' : lambda C, stride, affine: nn.AvgPool2d(3, stride=stride, padding=1, count_include_pad=False), 'max_pool_3x3' : lambda C, stride, affine: nn.MaxPool2d(3, stride=stride, padding=1), 'skip_connect' : lambd...
cnn/operations.py
Apache-2.0
4,587
29a8a4590de7d38913a3f23cc11df162708cd02b
Python
py
import os import time from collections import OrderedDict import logging import argparse import numpy as np import random import torch import torch.nn as nn import torch.optim import torch.utils.data import torch.backends.cudnn import torchvision.utils from torch.autograd import Variable import torchvision.utils as vu...
generative_models/cGAN_PyTorch/main.py
MIT
6,285
d7829595b3d509e0e8f75fe4daa3832b40bfcbee
Python
py
import copy import math import glob import os import time from collections import deque import gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import algo from arguments import get_args from envs import make_vec_envs from model_nomodulation import ...
main_nomodulation.py
MIT
5,672
29a8b77da0f09a6dce858c5ceda9ddb79e9a6add
Python
py
'''Train CIFAR100 with PyTorch.''' import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as cudnn import torchvision import torchvision.transforms as transforms import os import argparse from models import * from utils import progress_bar from mode...
eval_ablation3.py
MIT
8,018
29a8c35dd56ca8bd519cdd3cadc2e85f72f3007d
Python
py
# coding=utf-8 # Copyright 2021 The HuggingFace Inc. 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...
src/transformers/modeling_flax_pytorch_utils.py
Apache-2.0
12,341
a91d41b9d6d91baa8a909ad24b9c2fb3c3c33ce5
Python
py
import torch import torch.nn as nn from dmb.modeling.stereo.layers.basic_layers import conv3d_bn, conv3d_bn_relu, conv_bn_relu, conv_bn from dmb.modeling.stereo.cost_processors.utils.hourglass import Hourglass class AcfAggregator(nn.Module): """ Args: max_disp (int): max disparity in_planes (...
dmb/modeling/stereo/cost_processors/aggregators/AcfNet.py
MIT
3,356
d777d6bf72369a49cec1819dc1dff78c3763fd52
Python
py
from torch.utils.data import Sampler import numpy as np from random import shuffle class GroupLengthBatchSampler(Sampler): def __init__(self, data_source, batch_size, batches_per_group=20): super().__init__(data_source) ind_n_len = [] for i, p in enumerate(data_source): ind_n_l...
hw_asr/batch_sampler/group_sort_batch_sampler.py
MIT
1,892
29a8e4f031b88c913dd95d7e9e8efe682bdc96ab
Python
py
#This file regroups the methods used to load the data and preprocess images from torchvision import datasets, transforms import torch import json from PIL import Image import numpy as np class Utils: @staticmethod def LoadData(data_dir, folders): # We define the transforms used on each image of t...
utility.py
MIT
5,693
29a9040bac5086d3813d9235cb3f2f09e80c745d
Python
py
import torch.nn as nn import math """ Imported by https://github.com/marvis/pytorch-mobilenet/blob/master/main.py """ class MobileNetV1(nn.Module): def __init__(self, dropout_keep_prob=0.999): super(MobileNetV1, self).__init__() self.dropout_keep_prob = dropout_keep_prob self.dropout = nn...
solutions/pedestrian_search/webserver/src/service/models/mobilenet.py
Apache-2.0
1,834
29a9117224979bd85b9882ef589d710d8dba2215
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 applica...
stego/dino/vision_transformer.py
Apache-2.0
12,222
10cf5b585e0b6cb3ada97e977ca9f30db005ec6d
Python
py
""" Classes to be used for postprocessing data after a simulation. """ import warnings import numpy as np import torch from scipy.stats import beta from perm_hmm.util import ZERO from perm_hmm.loss_functions import zero_one, log_zero_one def clopper_pearson(alpha, num_successes, total_trials): """ Computes ...
perm_hmm/postprocessing.py
Apache-2.0
15,799
fd79bfbf3ab2cb218182abbd353738ab15acadf9
Python
py
# -*- coding=utf-8 -* from __future__ import print_function, division import os import time import torch import mlflow import argparse import setproctitle import numpy as np from match import run_experiments, run_single_dataset_experiments class CustomSettings(object): def __init__(self, seed=None, data='weibo'...
traj_er/DPLink/codes/run_my_data.py
MIT
6,652
29a93c1117a666e11be35b4d1557ca050d6fa8f2
Python
py
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ## Created by: Guanglei Yang ## Department of Information Engineering and Computer Science, University of Trento ## Email: guanglei.yang@studenti.unitn.it or yangguanglei.phd@gmail.com ## Copyright (c) 2020 ## ## This source code is licensed un...
depth_prediction/pytorch/multihead.py
MIT
8,110
4bbc3896c88822ac784f71891404cf37ae7b4665
Python
py
# Copyright 2020 The HuggingFace 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 required by applicabl...
src/transformers/training_args.py
Apache-2.0
44,357
a91921d466a5db982c7e1e067ee8223c3cd90493
Python
py
import random from itertools import product import torch class CartesianSampler: """Random subset sampling from {0, 1, ..., M-1} X {0, 1, ..., L-2} where X is Cartesian product. Attributes: M: number of trajectories. L: trajectory length. batch_size: input batch size for training the...
misc/sampler.py
MIT
5,474
10fc7c3c5c782b5be1e8cb43f8c4fb8feca75e4a
Python
py
import torch from torch import nn import numpy as np import os from .utils.detect_face import detect_face, extract_face class PNet(nn.Module): """MTCNN PNet. Keyword Arguments: pretrained {bool} -- Whether or not to load saved pretrained weights (default: {True}) """ def __init__(self, ...
models/mtcnn.py
MIT
21,412
29a9534c518293c68f178cbb8abb1dd3da0841cc
Python
py
# System libs import os import time import argparse from distutils.version import LooseVersion # Numerical libs import numpy as np import torch import torch.nn as nn from scipy.io import loadmat import torch.utils.data as data # Our libs from data.augmentations import Compose, PaddingCenterCrop from data.ac17_dataloade...
eval.py
BSD-3-Clause
6,762
ff04a77455d628cd6e79d080bafc01172e6cbeed
Python
py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. """ Detection Training Script. This scripts reads a given config file and runs the training or evaluation. It is an entry point that is made to train standard models in detectron2. In order to let one script support training of many models, this...
vehicle_detection/utils/trainer.py
MIT
5,539
7c71302f503c85f9e31ef1a1d0b9e02628158036
Python
py
# General import torch import torch.nn as nn import torch.nn.functional as F # Setup from setups import CategoricalImageFlowSetup # Data from pixelflow.data import CategoricalCIFAR10 # Model from pixelflow.flows import UniformlyDequantizedFlow from pixelflow.transforms import LinearSplineAutoregressiveTransform2d fr...
experiments/train/elbo_pixelcnn.py
MIT
2,457
29a95e0be461696b804e990c2643bba59a6fe97b
Python
py
###################### # So you want to train a Neural CDE model? # Let's get started! ###################### import math import torch import torchcde ###################### # A CDE model looks like # # z_t = z_0 + \int_0^t f_\theta(z_s) dX_s # # Where X is your data and f_\theta is a neural network. So the first th...
example/example.py
Apache-2.0
6,633
29a95eea6a2614a7daa5db7745229e20c96fc0fa
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...
tests/trainer/test_dataloaders.py
Apache-2.0
39,173
03810309d91362cd65ea0fa1a140e0fe926deff4
Python
py
# This file contains experimental modules import numpy as np import torch import torch.nn as nn from .common import Conv, DWConv from .utils.google_utils import attempt_download class CrossConv(nn.Module): # Cross Convolution Downsample def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): ...
models/experimental.py
MIT
5,636
4b60543efd8b1a1fbd554a5cfcf8995621f6ee47
Python
py
# -*-coding:utf-8-*- import torch.nn as nn import torch.nn.functional as F __all__ = ["mynet"] class MyNet(nn.Module): def __init__(self, num_classes=10): super(MyNet, self).__init__() self.conv_1 = nn.Conv2d(3, 6, 5) self.conv1_bn = nn.BatchNorm2d(6) self.conv_2 = nn.Conv2d(6, 16...
models/mynet.py
MIT
972
342a9e81140cc254a441a8b3d8068a82505f695f
Python
py
import pickle, logging import numpy as np import revtok # tokenizer import torch import torch.nn as nn from gen.constants import * class WordEmbedding(torch.nn.Module): ''' inputs: x: batch x ... outputs:embedding: batch x ... x emb mask: batch x ... ''' def __init_...
models/nn/embedding.py
MIT
4,734
7c51aa7dad6502387fd7affb8dba06e35a05a26c
Python
py
# Expansion penalty module (based on minimum spanning tree) # author: Minghua Liu # Input: # xyz: [#batch, #point] # primitive_size: int, the number of points of sampled points for each surface elements, which should be no greater than 512 # in each point cloud, the points from the same surface element should be succ...
expansion_penalty/expansion_penalty_module.py
Apache-2.0
2,785
42130774caa412fd5a880aaaac1d8fda009be6fd
Python
py
""" PrivacyRaven has support for user-defined Pytorch Lightning Bolt callbacks which may be passed as arguments into the currently available attack functions. A callback is just a function (or class in this case) that gets passed in as an argument to another function, which should execute the callback function or cla...
examples/example_pytorch_callback.py
Apache-2.0
3,121
29a9c166fb3c2a53195e36849dc6cab2e95bef6c
Python
py
from __future__ import absolute_import import itertools import numpy as np import torch import unittest from prob_phoc import cphoc, pphoc class ProbPHOCTest(unittest.TestCase): @staticmethod def _run_cphoc_sum_prod(device, dtype, use_log): x = np.asarray([[.7, .4], [.9, .6]], dtype=dtype) y...
prob_phoc/test.py
MIT
2,868
5e1683310cd736c80178367d4237b82dc467ef4c
Python
py
import torch import torch.nn.functional as F from torch import nn from .layers import DownBlock, get_activation # The number of filters used in the first conv layer. # Each following layer will use twice filters (until reaching a predefined maximum filters). cfg_conv1_nf = {'A': 32, } # This is the maximum number of ...
models/stn/affine_stn.py
BSD-3-Clause
6,230
29a9e1572efe2f50a2126564aca5d6f313ea87a2
Python
py
import os from pathlib import Path from itertools import product from functools import lru_cache from ipdb import set_trace as breakpoint import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import roc_auc_score, log_loss, hinge_loss import requests import plotly import plotly.ex...
notebooks/cotrain_helper.py
MIT
31,075
10e08f8f8a18efdc5d3e16d12cafb3f6305794fb
Python
py
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ## Created by: RainbowSecret ## Microsoft Research ## yuyua@microsoft.com ## Copyright (c) 2018 ## ## This source code is licensed under the MIT-style license found in the ## LICENSE file in the root directory of this source tree ##++++...
Train/openseg/lib/models/nets/hrnet.py
MIT
9,609
29a9f9e6a9c5dbd089d0ad03180185c0c7e08452
Python
py
import torch from torch import nn from torch.nn import functional as F from nets.layers import ( round_filters, round_repeats, drop_connect, get_same_padding_conv2d, get_model_params, efficientnet_params, load_pretrained_weights, Swish, MemoryEfficientSwish, ) class MBConvBlock(nn...
nets/efficientnet.py
Apache-2.0
12,153
70937285665c51e172e9d8795fff24af949c4724
Python
py
""" @author: Junguang Jiang @contact: JiangJunguang1123@outlook.com """ import random import time import warnings import sys import argparse import os.path as osp import shutil import torch import torch.nn as nn import torch.backends.cudnn as cudnn from torch.optim import SGD from torch.optim.lr_scheduler import Lambd...
examples/domain_adaptation/image_classification/mdd.py
MIT
12,448
29aa1c84ae88036a721c706351bb1ad2357b0fc1
Python
py
import os.path as osp import mmcv import numpy as np import torch.nn as nn from mmcv.parallel import MMDistributedDataParallel from mmedit.core import tensor2img from ..base import BaseModel from ..builder import build_backbone, build_component, build_loss from ..common import GANImageBuffer, set_requires_grad from ....
mmedit/models/synthesizers/cycle_gan.py
Apache-2.0
17,710
29aa5d5ec0a5dacb9c325830c68f5613af330f19
Python
py
""" torchinfo.py """ import sys from typing import ( Any, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Tuple, Union, cast, ) import torch from torch import nn from torch.jit import ScriptModule from torch.utils.hooks import RemovableHandle from...
torchinfo/torchinfo.py
MIT
17,877
29aa60eba042659339f220bc016a1972ef003380
Python
py
"""treelstm.py - TreeLSTM RNN models Written by Riddhiman Dasgupta (https://github.com/dasguptar/treelstm.pytorch) Rewritten in 2018 by Long-Huei Chen <longhuei@g.ecc.u-tokyo.ac.jp> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the ...
onmt/modules/tree_lstm.py
CC0-1.0
6,052
7cfdf38d91fdd86f7c602016d31bb3c35ccc30e1
Python
py
# encoding: utf-8 """ @author: liaoxingyu @contact: sherlockliao01@gmail.com """ import torch from torch import nn from torch.autograd import Variable def normalize(x, axis=-1): """Normalizing to unit length along the specified dimension. Args: x: pytorch Variable Returns: x: pytorch Variable,...
solutions/1st-place/models/triplet_loss.py
BSD-3-Clause
12,530
29aa781105a050f216b38eaaabb8cebf2187fb02
Python
py
#!/usr/bin/env python3 # Copyright (c) 2020 NVIDIA Corporation. All rights reserved. # This work is licensed under the NVIDIA Source Code License - Non-commercial. Full # text can be found in LICENSE.md """Test a DeepIM network on an image database.""" import torch import torch.nn.parallel import torch.backends.cudn...
tools/test_net.py
BSD-Source-Code
6,454
801ce6e796492293c5eb8027632dd0aebeeb8918
Python
py
""" Copyright (C) 2019 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ import importlib import torch import logging from .gscnn import GSCNN def get_net(args, criterion): net = get_model(network=args.arch, nu...
pywick/models/segmentation/testnets/gscnn/__init__.py
MIT
956
29aab75936884b05b85aedbbff15932778b99fbb
Python
py
# coding: utf-8 import torchvision.transforms as tt from torchvision.datasets import ImageFolder from torch.utils.data import DataLoader import time import torch.nn as nn import torch import torchvision import torch.nn as nn from torch.autograd import Variable import torchvision.transforms as transforms from torchvisi...
manoah-farmer-individual-project/Code/7Layers_straight_4maxpool_10epochs_64batchsize_3kernelsize copy.py
MIT
11,196
2494157458e7cd8c8b3293e09f7eca228cc5b4e6
Python
py
import torch import torch.nn as nn def update_bn(model, s=1e-4): for m in model.modules(): if isinstance(m, nn.modules.batchnorm._BatchNorm) or \ isinstance(m, nn.modules.instancenorm._InstanceNorm) or \ isinstance(m, nn.GroupNorm): m.weight.grad.data.add_(s * torch.sig...
netslim/sparse.py
MIT
748
dff62958f5d14dc93ae98e223792e0b0a758f0bd
Python
py
import math import torch import numpy as np from .. import utils from .loss_surfaces import get_plane def dataloader_loss_surface(basis, model, dataloader, loss=torch.nn.MSELoss(), rng=0.1, n_pts=25, **kwargs): start_pars = model.state_dict() ## get ...
hess/loss_surfaces/dataloader_loss_surface.py
Apache-2.0
1,191
29aae32bd290c974f1fd9d5d7df18c233741175b
Python
py
# Author: David Harwath, Wei-Ning Hsu import datetime import numpy as np import pickle import shutil import time import torch import torch.nn as nn from models.quantizers import compute_perplexity from .util import * def map_skip_none(fn, it): """ emulate list(map(fn, it)) but leave None as it is. """ ...
steps/traintest.py
BSD-3-Clause
12,155
4b7a0b848d2d2635572d7479ecb2379f7fbedffb
Python
py
# ------------------------------------------------------------------------ # Deformable DETR # Copyright (c) 2020 SenseTime. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from DETR (ht...
models/backbone.py
Apache-2.0
7,404
70821d2f4a703518ddae8f9517b578a564c42d0a
Python
py
import torch from processor import RANGE_NOTE_ON, RANGE_NOTE_OFF, RANGE_VEL, RANGE_TIME_SHIFT SEPERATOR = "=========================" # Taken from the paper ADAM_BETA_1 = 0.9 ADAM_BETA_2 = 0.98 ADAM_EPSILON = 10e-9 LR_DEFAULT_START = 1.0 SCHEDULER_WARMUP_STEPS...
utilities/constants.py
MIT
710
e97940c2e5a2f738809078121d4314ff402222b0
Python
py
import torch DEVICE = torch.device("cuda") SAVED_CHECKPOINTS = [32*1000, 100*1000, 150*1000, 200*1000, 300*1000, 400*1000] SAVED_CHECKPOINTS += [10*1000, 20*1000, 30*1000, 40*1000, 45*1000, 50*1000, 60*1000, 70*1000, 80*1000, 90*1000] SAVED_CHECKPOINTS += [25*1000, 50*1000, 75*1000] SAVED_CHECKPOINTS = set(SAVED_CHE...
ColBERT_increase_cls_token_similarity/colbert/parameters.py
MIT
329
34011d5bf8330323c5347e6baf82b53526e1a2b3
Python
py
from tensorflow.keras.applications.imagenet_utils import preprocess_input as efficientnet_preprocess_input from tensorflow.keras.layers import Activation from tensorflow.keras.backend import sigmoid, constant from tensorflow.keras.initializers import Initializer from torch.nn import ConvTranspose2d, init from torch im...
utils/helpers.py
CC-BY-4.0
16,042
29ab4b80413ce38004e662289a02c061dbe89b28
Python
py
import shutil from argparse import ArgumentParser import optuna import torch import yaml from build_problem import BuildProblem from my_functions import out_size from timeit import default_timer as timer # Convert params from Optuna def convert_params(params, length): params["hidden_dims"] = 2 ** ...
xml-cnn/train.py
MIT
4,031
34669bd51d41526382a03c32521a3f207526f56f
Python
py
import math import torch import torch.nn as nn from mmcv.runner import load_checkpoint from mmedit.models.common import (PixelShufflePack, ResidualBlockNoBN, make_layer) from mmedit.models.registry import BACKBONES from mmedit.utils import get_root_logger class UpsampleModule(nn.Seq...
mmedit/models/backbones/sr_backbones/edsr.py
Apache-2.0
4,603
038b7948643a15b073d20009531a950aaacf8d1b
Python
py
from torch import nn, Tensor class Classifier(nn.Module): """ Simple model with linear layers for mnist """ def __init__(self): super(Classifier, self).__init__() self.fc1 = nn.Linear(784, 512) self.relu1 = nn.LeakyReLU(negative_slope=0.1) self.drop1 = nn.Dropout(p=0.5...
classifiers/MNIST.py
MIT
803
03a97795ce8fb68401717a8e56f1f6b9eeed5570
Python
py
#!/usr/bin/python # # Copyright 2020 Azade Farshad # # 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...
scripts/evaluate_robot_metrics.py
Apache-2.0
11,384
29ab7bb969e9e8dc3042d0193f791be8b28d39e5
Python
py
from ..._fgsm import FGSM, FGM from . import _plot_settings import torch.nn as nn import torch import matplotlib.pyplot as plt """ Adversarial Evaluation functions for Pytorch neural models """ from tqdm import tqdm from mpl_toolkits import mplot3d import numpy as np import matplotlib matplotlib.use('Agg') __all__...
deepillusion/torchattacks/analysis/plot/_loss_landscape.py
MIT
3,791
29ab7fad8ca6d355ce6296a3772bebd3f68ce000
Python
py
# TODO: # * Do not use test data during training # * Add option to run on GPU import argparse import logging import numpy as np import os import time from sklearn.datasets import load_svmlight_file import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as data # import torch.backends.c...
src/main/python/ncf/ncf.py
MIT
6,365
4b45b5b013133f7fc80cd5e43cd401de8d7d5280
Python
py
""" Recurrent Neural Networks ------------------------- """ import torch.nn as nn from numpy.random import RandomState from typing import List, Optional, Union from ..logging import raise_if_not, get_logger from ..utils.torch import random_method from .torch_forecasting_model import TorchForecastingModel logger = ge...
darts/models/rnn_model.py
Apache-2.0
6,461
29ab8a5f9fd2b544dd64fc4c39b0b441590c5203
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from .mwm import MWMLNet from .layers import WordsCapsLayer,SelfAttnMatch class MWMLNetLMFineGrind(nn.Module): def __init__(self,**kwargs): super(MWMLNetLMFineGrind,self).__init__() self.n_class = kwargs["n_class"] self.type...
src/model/lm.py
MIT
3,877
29abd7916a8e2841444135a0210ab97065871d48
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Train and eval functions used in main.py """ import math import os import sys from typing import Iterable import torch import util.misc as utils from datasets.coco_eval import CocoEvaluator from datasets.panoptic_eval import PanopticEvaluator ...
detr/engine_multi.py
MIT
7,967
1e74bd00a78aa9aa7f16f14c729128fb711d5773
Python
py
import torch import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt import numpy as np import utils import seaborn as sns # Load the training sets # The data is shuffled by the trainloader transformCutout = transforms.Compose([ transforms.RandomCrop(32, padding=4), tran...
data.py
MIT
3,921
29ac1eaa732f8ba4d224e8d925a9fcbd1f098bb2
Python
py
#!/usr/bin/env python # 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 applica...
pytorch_lightning/setup_tools.py
Apache-2.0
7,362
29ac3b814b3c2e852e36611a34b9be054724bd6e
Python
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import csv import sys from datetime import datetime import pandas import torch sys.path.append('../') from loglizer.models import AutoencoderConv from loglizer import dataloader, preprocessing import pickle import numpy as np import os import time # struct_log = '../data...
demo/Autoencoder_conv_demo.py
MIT
5,065
3479dd8cacf78f7059e2bf4a3a338716543269ce
Python
py
""" Statistics calculation utility """ from __future__ import division import time import math import sys from onmt.utils.logging import logger class Statistics(object): """ Accumulator for loss statistics. Currently calculates: * accuracy * perplexity * elapsed time """ def __init__...
onmt/utils/statistics.py
MIT
4,401
703f3c4dfb629d7b546de328d66979f254478f98
Python
py
"""this class build and run a trainer by a configuration""" import os import sys import shutil import datetime import cv2 import numpy as np import torch import torch.nn as nn import torch.optim as optim import torchvision from torchvision.transforms import transforms from torch.optim.lr_scheduler import ReduceLROnPla...
trainers/_fer2013_trainer.py
MIT
13,648
12eca1fd942c0fe3c94e99fd7ca8997356694483
Python
py
from .c_dataloader import CDataLoader from .c_dataloader_sklearn import * from .c_dataloader_svmlight import CDataLoaderSvmLight from .c_dataloader_imgclients import CDataLoaderImgClients from .c_dataloader_imgfolders import CDataLoaderImgFolders from .c_dataloader_mnist import CDataLoaderMNIST from .c_dataloader_lfw i...
src/secml/data/loader/__init__.py
Apache-2.0
709
29ac5827c029c098f991e6b578e11076a382593b
Python
py
#! /usr/bin/env python from django.conf import settings from django.core.management.base import BaseCommand from django.db.models import Count, Q from face_manager.models import Person, Face from filepopulator.models import ImageFile from scipy import stats from scipy.spatial import distance # from sklearn.cluster imp...
face_manager/management/commands/deprecated/classify_images_custom_snn.py
MIT
21,632
b24c43c2c4c0d04b17f898414f5fa4b48f6229d6
Python
py
from rlpyt.envs.gym_isaac.isaacgym_env import IsaacGymEnv from rlpyt.samplers.serial.isaac import IsaacSampler from rlpyt.algos.pg.ppo import PPO from rlpyt.agents.pg.mujoco import MujocoFfAgent from rlpyt.runners.minibatch_rl import MinibatchRl from rlpyt.utils.logging.context import logger_context if __name__ == "_...
examples/example_2a_isaac.py
MIT
1,797
29ac7d4997a521ffc22628e8aa8c206dd72a3967
Python
py
import torch class AliasMultinomial(torch.nn.Module): '''Alias sampling method to speedup multinomial sampling The alias method treats multinomial sampling as a combination of uniform sampling and bernoulli sampling. It achieves significant acceleration when repeatedly sampling from the save multinom...
models/loss/alias_multinomial.py
Apache-2.0
2,472
29ac7e76ebb1718964bdeb3f4eb32531195798f4
Python
py
r"""Importing this file includes common utility methods and base clases for checking quantization api and properties of resulting modules. """ import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.intrinsic.quantized.dynamic as nniqd import torch.nn.quantized as nnq import torch.nn.quantiz...
torch/testing/_internal/common_quantization.py
Intel
80,656
e93273faa2781a94600999a897094f5a57a14a1f
Python
py