content
stringlengths
200
198k
repo
stringlengths
4
186
path
stringclasses
1 value
license
stringclasses
101 values
size
int64
200
198k
sha
stringlengths
40
40
lang
stringclasses
1 value
ext
stringclasses
1 value
import torch.nn as nn import torch.nn.functional as F import torch from torchvision.models import vgg19 import math class FeatureExtractor(nn.Module): def __init__(self): super(FeatureExtractor, self).__init__() vgg19_model = vgg19(pretrained=True) # Extracts features at the 11th layer ...
implementations/srgan/models.py
MIT
3,774
5f003cda99e3e25531f1bede58d60a0566ec668b
Python
py
import dataclasses import json import os from dataclasses import dataclass, field from enum import Enum from typing import Any, Dict, List, Optional, Tuple from .file_utils import cached_property, is_torch_available, is_torch_tpu_available, torch_required from .trainer_utils import EvaluationStrategy from .utils impor...
src/transformers/training_args.py
Apache-2.0
23,860
ff22be4db444a7739782a9af798c7850c10a66a3
Python
py
# # Copyright 2018 Analytics Zoo 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 applicable law or agreed to...
pyzoo/test/zoo/chronos/autots/experimental/test_autotstrainer.py
Apache-2.0
15,848
e97e23acc868bcae3a80c9e8735ae30decf7d8c3
Python
py
import logging import random import numpy as np import torch import torchaudio from torch import Tensor from torch.utils.data import Dataset from hw_asr.base.base_text_encoder import BaseTextEncoder from hw_asr.utils.parse_config import ConfigParser logger = logging.getLogger(__name__) class BaseDataset(Dataset): ...
hw_asr/base/base_dataset.py
MIT
4,981
3ad8118f26474ec1197eec514a7a11a0ab0a7230
Python
py
from pytorch_lightning.core.lightning import LightningModule from pytorch_lightning.core.datamodule import LightningDataModule def is_overridden(method_name: str, model: LightningModule) -> bool: # if you pass DataModule instead of None or a LightningModule, we use LightningDataModule as super # TODO - refect...
pytorch_lightning/utilities/model_utils.py
Apache-2.0
1,306
d71e1fd5c08a68552beb2bbaa79886423b409acd
Python
py
from __future__ import print_function import datetime import time import torch import torch.autograd as autograd import torch.nn as nn import torch.optim as optim import codecs from model.crf import * from model.lstm_crf import * import model.utils as utils from model.evaluator import eval_w import argpar...
train_w.py
Apache-2.0
14,607
3ad823671e749373b26ffa5e176d1ae85c4fd56f
Python
py
#!/usr/bin/env python3 import time import sys from codes.e_utils.names import PROJECT_HOME sys.path.insert(0,"c:\\users\\wlckd\\anaconda3\\envs\\link_rl\\lib\\site-packages") import torch import torch.multiprocessing as mp from torch import optim import os print(torch.__version__) from dummy_env import dummy_env fr...
temp/matlab_pendulum_main/MATLAB_pendulum_dqn_main_Test.py
MIT
5,187
3ad82ce39166937c56a7afbd36d731f9ddcb2139
Python
py
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn from mmcv.cnn import ConvModule from mmseg.ops import resize from ..builder import HEADS from .decode_head import BaseDecodeHead class ASPPModule(nn.ModuleList): """Atrous Spatial Pyramid Pooling (ASPP) Module. Args: ...
mmseg/models/decode_heads/aspp_head.py
Apache-2.0
3,947
7059aee961183952ec60ca4d6ccea5d3f9ae3f79
Python
py
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim class FleetwoodNet9V1(nn.Module): def __init__( self, num_classes, init_weights=True, ): super().__init__() # Convolutional Layers self.features = nn.Sequential( ...
src/models/vgg9.py
MIT
2,358
4b884accd8370bdb9a878ead58dcdf56e9519bd5
Python
py
""" Module with examples of common pruning patterns """ from .abstract import Pruning from .utils import get_activations, get_param_gradients, get_gradients import torch class ActivationMixin(Pruning): def update_activations(self, only_prunable=True): assert self.inputs is not None, \ "Inputs...
shrinkbench/pruning/mixin.py
MIT
4,333
e656f68331af1fec02cbbc95d25f541319fadfa3
Python
py
from __future__ import print_function import torch import numpy as np from scipy.ndimage.filters import gaussian_filter from PIL import Image import inspect, re import os import collections # Converts a Tensor into a Numpy array # |imtype|: the desired type of the converted numpy array class util(): def tensor2im(...
util/util.py
MIT
2,770
3ad8df4d80a4c63579b14a9509e273de5a71ab2a
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. # Requires vqa-maskrcnn-benchmark to be built and installed. See Readme # for more details. import argparse import os import time import cv2 i...
script/gt_t2c_extract_features.py
MIT
11,018
5fbda004ca05dcc3c14636bfdc81988c1b1adbcf
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import math from functools import partial import pdb __all__ = [ 'ResNet', 'resnet10', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152', 'resnet200' ] def conv3x3x3(in_planes, out_planes, stride...
models/resnet_comp.py
MIT
11,192
248e3395c597c5459c9c84b3916cc11b034d379e
Python
py
import os from comet_ml import Experiment, ExistingExperiment import sys import json import numpy as np import torch from torch import nn from torch import optim from torchsummary import summary from torch.optim import lr_scheduler from opts import parse_opts from model import generate_model, EmbeddingModel from mean ...
main.py
MIT
8,419
3ad8fc77f2e0d46adf83230a0e9c029d099836f7
Python
py
import numpy as np import random from collections import namedtuple, deque from double_dqn_model import DoubleQNetwork from replay_buffer import ReplayBuffer import torch import torch.nn.functional as F import torch.optim as optim BUFFER_SIZE = int(1e5) # replay buffer size BATCH_SIZE = 128 # minibatch size...
double_dqn_agent.py
MIT
4,919
3ad9113ec4641d5cd1b81f0fa037a41379d183bb
Python
py
#!/usr/bin/env python3 import unittest import torch from Lgpytorch.lazy import LowRankRootLazyTensor from Lgpytorch.test.lazy_tensor_test_case import RectangularLazyTensorTestCase class TestLowRankRootLazyTensor(RectangularLazyTensorTestCase, unittest.TestCase): def create_lazy_tensor(self): root = tor...
test/lazy/test_low_rank_root_lazy_tensor.py
MIT
1,118
3ad91ced48092f18da7e8c90e47e435818570f3e
Python
py
from __future__ import print_function from os import path import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from utils.iterative_trainer import IterativeTrainerConfig, IterativeTrainer from utils.logger import Logger from termcolor import colored from methods impo...
methods/pixelcnn.py
MIT
9,010
3ad91d197bb2df760af0073f1632562b203e78fc
Python
py
import torch import sys import os import shutil from ..constants import OCRD_TOOL from ocrd import Processor from ocrd_models.ocrd_page import parse from ocrd_utils import getLogger, concat_padded from ocrd_modelfactory import page_from_file from ocrd_models.ocrd_page import to_xml,parse import shutil from pathlib ...
ocrd_anybaseocr/cli/ocrd_anybaseocr_dewarp.py
Apache-2.0
3,779
7ce8823edf0d5c3e55d46fdf1ed544eaf88c61b1
Python
py
import importlib import numpy as np import torch from scipy.ndimage import rotate, map_coordinates, gaussian_filter from scipy.ndimage.filters import convolve from skimage.filters import gaussian from skimage.segmentation import find_boundaries from torchvision.transforms import Compose class RandomFlip: """ ...
augment/transforms.py
MIT
20,152
7c1b7ce068c6cab5bcfe550aacd0a99f222eb799
Python
py
import argparse import scipy from scipy import ndimage import numpy as np import sys import torch from torch.autograd import Variable import torchvision.models as models import torch.nn.functional as F from torch.utils import data, model_zoo from model.SEAN import SEANet from dataset.cityscapes_dataset imp...
evaluation.py
MIT
3,275
4b6c098ae197d7956de8970d2d2b7e858b504c4e
Python
py
import torch from torch import nn from torch.utils import model_zoo import pretrainedmodels from pretrainedmodels.models.dpn import adaptive_avgmax_pool2d from pretrainedmodels.models.xception import Xception, pretrained_settings as xception_settings from cnn_finetune.base import ModelWrapperBase, ModelInfo __all__ ...
cnn_finetune/contrib/pretrainedmodels.py
MIT
8,884
3ad9754f17f976d55e0071b58c077378bb780012
Python
py
import numpy as np import torch from torchvision.utils import make_grid from base import BaseTrainer from utils import inf_loop class Trainer(BaseTrainer): """ Trainer class Note: Inherited from BaseTrainer. """ def __init__(self, model, loss, metrics, optimizer, config, data_loader, ...
trainer/trainer.py
MIT
6,187
b290fafabe71d85fdc3276dfb4599fc40587d858
Python
py
import os import warnings os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = "4" warnings.filterwarnings("ignore", category=DeprecationWarning) warnings.simplefilter(action='ignore', category=FutureWarning) warnings.simplefilter(action='ignore', category=UserWarning) import dgl import ...
main/main_clean_model.py
MIT
2,064
f9e8b7b91ca8c0429de54449ce1e931459781960
Python
py
"""LSTM Controller.""" import torch from torch import nn from torch.nn import Parameter import numpy as np class LSTMController(nn.Module): """An NTM controller based on LSTM.""" def __init__(self, num_inputs, num_outputs, num_layers): super(LSTMController, self).__init__() self.num_inputs = ...
ntm/controller.py
BSD-3-Clause
1,625
3ad9afa863b0951c36cc8664ad7dc1c6b2cbc0de
Python
py
# MIT License # Copyright (c) 2021 yzqin # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish...
dataset_utils/eval_score/eval_utils/evaluation_data_generator.py
MIT
28,039
e63196d8701dc6ee8b5fd435c84c6ed4529189f7
Python
py
"""Test script to classify target data.""" from sklearn.metrics import accuracy_score import torch import torch.nn as nn from utils import make_variable def eval_tgt(encoder, classifier, data_loader): """Evaluation for target encoder by source classifier on target dataset.""" # set eval state for Dropout and...
core/test.py
MIT
1,158
800b441833edc48740d8203c3b2c3b886c69c315
Python
py
import os import numpy as np import scipy.sparse from scipy.sparse import csr_matrix from sklearn.preprocessing import normalize import torch import copy import torch.sparse from numpy.linalg import multi_dot from collections import defaultdict from keynet.dense import random_positive_definite_matrix, random_doubly_st...
keynet/sparse.py
MIT
36,424
b23b0dd6af34fd5ad98d636d5218932381b86af9
Python
py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
object_detection/pytorch/tools/train_hvd.py
Apache-2.0
12,216
7080b702ab2667afa3dd96dc3f0f6ebb2f14b371
Python
py
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ## Created by: Hang Zhang ## Email: zhanghang0704@gmail.com ## Copyright (c) 2020 ## ## LICENSE file in the root directory of this source tree ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ResNet variants""" im...
code/OCTA-Net/resnet.py
Apache-2.0
13,203
42255dc4ff324022f0f7ee52b67125262ab6a9b8
Python
py
import os from env.environment import PortfolioEnv import numpy as np import torch as T import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.distributions import Normal import multiprocessing as mp from plot import add_curve, save_plot class ActorCritic(nn.Module): def __in...
algorithms/a2c/agent.py
MIT
6,854
dfb522319a82f541ac6686d0c22b987086453a64
Python
py
import torch from torch.autograd import Variable import utils # import dataset from PIL import Image import glob import os import csv import cv2 # import models.crnn as crnn def predict_this_box(image, model, alphabet): converter = utils.strLabelConverter(alphabet) transformer = dataset.resizeNormalize((200, ...
task2/main.py
MIT
4,851
3ada2aa4fe062c99eceeeceb3204a7da9edff7c0
Python
py
import os import time import torch import pprint import argparse import numpy as np from torch.utils.tensorboard import SummaryWriter from tianshou.policy import DQNPolicy from tianshou.utils import BasicLogger from tianshou.env import SubprocVectorEnv from tianshou.trainer import offpolicy_trainer from tianshou.data ...
examples/minigrid/minigrid_dqn.py
MIT
8,001
b2a21d23145d73eb4bedae9f5c43865dbcb6e142
Python
py
"""Utilities for interacting with precomputed word representations.""" from typing import Any from ldp.utils.typing import PathLike import h5py import torch from torch.utils import data class RepresentationDataset(data.Dataset): """Iterates through a dataset of word representations.""" def __init__(self, p...
ldp/parse/representations.py
MIT
4,125
1ea373e610dac2c6c077b7960d8de8b287580af9
Python
py
# 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, software # distributed under th...
bert/train.py
Apache-2.0
977
f98ff0016bfe99af7396d0faf71d34dbae5c8720
Python
py
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.11.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # -...
modeling/gbert_classifier.py
MIT
18,700
a99790a6c26d47d3f82955db8bb3a0bbe60593d5
Python
py
import os import gym import copy import torch import pprint import random import argparse import numpy as np import pandas as pd import time from ES import CEM from TD3 import TD3 from utils import get_output_folder from Replay_Buffer import ReplayBuffer from Parameters import Set_parameter os.environ['CUDA_VISIBLE_DE...
Main.py
MIT
19,251
3ada81bb410dfa0a104859a94e2ae8fac38038aa
Python
py
import torch from torch.utils.data import TensorDataset, DataLoader, random_split from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F from numpy import sqrt # from parameter import HIDDEN_SIZE, NUM_LAYERS, BATCH_SIZE, FEATURE_SIZE, SEQ_SIZE, OUT_SIZE, USE_GPU class Attn(nn.Module)...
backend/rnn/biLSTM_multi_to_one.py
MIT
3,807
f9e9eeac5ace977efdd8f8f508f3180ceb8366c5
Python
py
from torchvision import transforms class TransformCIFARTrainBaseline(object): def __init__(self, norm_mean=[x / 255.0 for x in [125.3, 123.0, 113.9]], norm_std=[x / 255.0 for x in [63.0, 62.1, 66.7]]): super().__init__() self.transform = transforms.Compose([ transform...
projects/CIFAR10Demo/scripts/TransformCIFARTrainBaseline.py
MIT
571
24ca6a50501ac069469277a343b77618e6340b55
Python
py
import os import torch from gluonnlp.data import SentencepieceTokenizer from kogpt2.model.sample import sample_sequence from kogpt2.utils import get_tokenizer from kogpt2.utils import download, tokenizer from kogpt2.model.torch_gpt2 import GPT2Config, GPT2LMHeadModel import gluonnlp import argparse parser = argparse.A...
generator.py
Apache-2.0
4,160
3adac4c7cdc46a3bc0216ab2713c40b9b4c68b01
Python
py
from __future__ import division import time import torch import torch.nn as nn from torch.autograd import Variable import numpy as np import cv2 from util import * import argparse import os import os.path as osp from DNModel import net from img_process import preprocess_img, inp_to_image import pandas as pd import r...
detect.py
MIT
6,356
cc009033ea00a46328a0e22b7853f611e5e0ff8b
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from .operations import * import random class MixedOp(nn.Module): def __init__(self, C, stride): super(MixedOp, self).__init__() self._ops = nn.ModuleList() for primitive in OPS_POOL: op = OPS[primitive](C, st...
Imagenet_train/timm/models/model_search.py
MIT
4,623
3adacbac0a71c25805ca381c26c332ee446fcf2a
Python
py
import torch def flow_loss_func(flow_preds, flow_gt, valid, gamma=0.9, max_flow=400, **kwargs, ): n_predictions = len(flow_preds) flow_loss = 0.0 # exlude invalid pixels and extremely large diplacements mag = torc...
loss.py
Apache-2.0
1,022
f9f0b0216b2a277f422daab92d5c5b4f53458ae3
Python
py
from torch.utils.data import Dataset from torchvision import transforms import torchvision.transforms.functional as TF import random import torch import numpy as np from PIL import Image import os class WeedDataset(Dataset): def __init__(self, root, random_rotate=True): self.root = root self.random...
setup/dataset.py
MIT
2,993
3adaf905bfd5af090b1f0919347188af6a59b3a8
Python
py
from collections import OrderedDict import numpy as np import torch from torch import nn as nn from torch.nn import init from rlkit.torch.core import PyTorchModule from rlkit.misc.eval_util import create_stats_ordered_dict from rlkit.torch.ddpg import DDPG import rlkit.torch.pytorch_util as ptu import rlkit.torch.net...
rlkit/torch/ddpg/easy_v_ql.py
MIT
5,578
3adb0907bd0c50e5f23d53f3181fcc0fabf8b97e
Python
py
import numpy as np from torch.utils.data import Dataset from .dataset import PairDataset, InstanceDataset from neuron.config import registry from neuron import ops from collections import OrderedDict __all__ = ['Seq2Pair', 'Image2Pair', 'Seq2Instance', 'Subset', 'Slice', 'RandomConcat'] @registry.regist...
utils/neuron/data/datasets/structure.py
MIT
14,525
e93f204e2b33df1e3bfd2d454a5bf351e5343a00
Python
py
import torch import torch.nn as nn from dgl.nn.pytorch import SumPooling, AvgPooling, MaxPooling, GlobalAttentionPooling, Set2Set from conv import GNN_node, GNN_node_Virtualnode class GNN(nn.Module): def __init__(self, num_tasks = 1, num_layers = 5, emb_dim = 300, gnn_type = 'gin', virtual_node...
examples/pytorch/ogb_lsc/PCQM4M/gnn.py
Apache-2.0
2,819
3adb43eccd1bcce1d10d95f663ae81dc5f3b3afc
Python
py
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...
transfer_model/data/build.py
Xnet,RSA-MD,X11
1,701
e9ad474fbba91e3a03dd0545b4c2035731bfa24b
Python
py
import math import torch from torch.optim.optimizer import Optimizer, required class RAdam(Optimizer): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0): defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay) self.buffer = [[None, None, None] for in...
pytorch_utilities/optim/radam.py
MIT
7,961
454f32e7bb2c03e1b5196bee8df09cfa6dba9968
Python
py
import os import torch import sys import logging import time import tqdm import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import statistics from os.path import join #from model.model import EncoderDecoder def get_logger(name, path, fname): """create a logger and return """ logg...
eval/eval_utils.py
MIT
4,275
e630bc35c7016dfbb2d676bb2f6b5a4768c59ec8
Python
py
import os import numpy as np import h5py import pandas as pd import spacy import torch from torch.nn.utils.rnn import pad_sequence from torch.utils.data.dataset import Dataset from torchtext import data # set common-sense features path CSPATH = './data/csfeatures/' def load_multimodal_features_from_h5(feat_h5_video,...
iPerceiveDVC/dataset/dataset.py
MIT
19,952
f9e3c33c6b103e96dfa02abd62aafb36b05bede8
Python
py
from functools import partial import torch from torch import nn as nn from torch.nn import functional as F def conv3d(in_channels, out_channels, kernel_size, bias, padding): return nn.Conv3d(in_channels, out_channels, kernel_size, padding=padding, bias=bias) def create_conv(in_channels, out_channels, kernel_si...
unet3d/buildingblocks.py
MIT
15,443
1e7332f6f354a67e3fdf23272eef68c3954b5b94
Python
py
from custom_types import * from constants import CACHE_ROOT, DATA_ROOT from process_data import mesh_utils import torch import os from options import Options from process_data.mesh_plotter import plot_mesh from process_data import files_utils class MeshHandler: _mesh_dss: List[Union[mesh_utils.MeshDS, N]] = [] ...
models/mesh_handler.py
MIT
9,624
12c78e95bd813f28564d061a349276628dad1e3a
Python
py
import h5py import numpy as np import torch import torch.nn as nn from skimage import measure from pytorch3dunet.augment.transforms import LabelToAffinities, StandardLabelToBoundary from pytorch3dunet.embeddings.contrastive_loss import ContrastiveLoss from pytorch3dunet.unet3d.losses import GeneralizedDiceLoss, Weight...
tests/test_criterion.py
MIT
7,994
3adb86d4839dff61b3fa9eb6865ffdc9c4df8c70
Python
py
from gptlm import GPT2LM import torch import argparse from PackDataset import packDataset_util_bert def read_data(file_path): import pandas as pd data = pd.read_csv(file_path, sep='\t').values.tolist() sentences = [item[0] for item in data] labels = [int(item[1]) for item in data] processed_data...
experiments/test_defense.py
MIT
5,505
3adb9b2e8a48721d0ec5f93f847296e11b5756fa
Python
py
''' Soft Actor-Critic version 2 using target Q instead of V net: 2 Q net, 2 target Q net, 1 policy net add alpha loss compared with version 1 paper: https://arxiv.org/pdf/1812.05905.pdf ''' import math import random import gym import numpy as np import torch import torch.nn as nn import torch.optim as optim import ...
sac_v2_multithread.py
Apache-2.0
18,359
3adbd9a71dbcfaac4e497ef3bb99c7b5950b494f
Python
py
# Adopted from a code base from https://github.com/cetinsamet # -------------------------------------------------- import random random.seed(123) import numpy as np np.random.seed(123) import torch torch.manual_seed(123) criterion = torch.nn.CrossEntropyLoss(reduction='sum') # <-- Loss Function class Network...
model.py
MIT
732
3adbdac390780fcf3fcd8f494db2ce8c903e0b8d
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/lite/wrappers.py
Apache-2.0
6,982
ff95e89d1d2cf6f7a805ddf95c2a3067c9599c3e
Python
py
import tempfile import pytest import torch from torch import nn import mmcv from mmcv.cnn.utils.weight_init import update_init_info from mmcv.runner import BaseModule, ModuleList, Sequential from mmcv.utils import Registry, build_from_cfg COMPONENTS = Registry('component') FOOMODELS = Registry('model') @COMPONENTS...
tests/test_runner/test_basemodule.py
Apache-2.0
20,735
f9e36687a95d91b8ba4c27d151a15cc9c4786165
Python
py
# @Author : FederalLab # @Date : 2021-09-25 16:52:39 # @Last Modified by : Chen Dengsheng # @Last Modified time: 2021-09-25 16:52:39 # Copyright (c) FederalLab. All rights reserved. import json from threading import Lock from typing import Any, Dict, List, Optional, Tuple import torch.distribu...
openfed/federated/props.py
MIT
6,722
3adc1ce018c0a14964bd1960d6dc0904bfc00550
Python
py
# ------------------------------------------------------------------------------------------------ # Deformable DETR # Copyright (c) 2020 SenseTime. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # -------------------------------------------------------------------------...
models/ops/modules/ms_deform_attn.py
Apache-2.0
6,605
12ed0a4f2ead30dc3e20d7682e0f52374c0dc308
Python
py
import argparse import os import time import torch from filelock import FileLock # from torch.nn import Linear from torch.nn.functional import log_softmax, nll_loss from torch_geometric.nn import JumpingKnowledge from tools import file_path from tools import save_data, load_data class ModelEnsemble(torch.nn.Module)...
AutoGraphEnsemble.py
MIT
3,884
45a0a04d4f306af2e3ab4d7e92a01b72c39e37ba
Python
py
# -------------------------------------------------------- # Tensorflow Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Lichao Wang, Jianwei Yang, based on code from Ross Girshick, Jiasen Lu, Jianwei Yang # -------------------------------------------------------- from __future_...
demo.py
MIT
18,155
28ec180b41dcacc5aa40da4e69dbfd7aa6fbbbf8
Python
py
from typing import Callable, List import numpy as np import pytest import torch from torch import Tensor from tests.helpers import seed_all from torchmetrics import Metric seed_all(1337) def _compute_sklearn_metric( metric: Callable, target: List[np.ndarray], preds: List[np.ndarray], behaviour: str, **kwargs )...
tests/retrieval/helpers.py
Apache-2.0
5,286
3adc74e0556c2b8d3ac66aab0e9d05a352f1d4c0
Python
py
import torch from model.model import * from utils.inference_utils import CropParameters, EventPreprocessor, IntensityRescaler, ImageFilter, ImageDisplay, ImageWriter, UnsharpMaskFilter from utils.inference_utils import upsample_color_image, merge_channels_into_color_image # for color reconstruction from utils.timers i...
N-ROD/evrepr/thirdparty/e2vid/image_reconstructor.py
MIT
5,213
1e146e420fed40e75c0131d1b89000552ad1d75c
Python
py
from models.losses.GeneralLoss import GeneralLoss import torch.nn as nn import torch from utils.constants import DEVICE class DefaultDLoss(GeneralLoss): def __init__(self, weight, **kwargs): super(DefaultDLoss, self).__init__(weight=weight) def custom_forward(self, fake_scores, real_scores, smoothin...
models/losses/DefaultDLoss.py
Apache-2.0
848
6b1c0bce93d99ee03f708fced624ba952d801cc6
Python
py
import torch import torch.nn as nn from models.arch_util import ConvGnLelu from models.stylegan.stylegan2_rosinality import Generator class Stylegan2LatentBank(nn.Module): def __init__(self, pretrained_model_file, encoder_nf=64, max_dim=1024, latent_dim=512, encoder_levels=4, decoder_levels=3): super()._...
codes/models/glean/stylegan2_latent_bank.py
Apache-2.0
2,979
3adc97359416619f6a6a0a51f6296381d057598c
Python
py
import math import numpy as np import torch import torch.nn.functional as F from torch import nn from torch.utils.data import DataLoader, random_split from torch.utils.tensorboard import SummaryWriter import torchvision # from torchvision.models.detection.backbone_utils import resnet_fpn_backbone # from torchvision.o...
scripts/condinst.py
MIT
19,324
3adcb0e64f1098771d6fe0dddfcf3ecb6a0a3c9a
Python
py
from __future__ import division from __future__ import print_function import os import glob import time import random import argparse import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable from utils import load_data, accur...
eval_ppi.py
MIT
10,192
4595fd7a1342792c4b1158da3c43b8fca7bb9771
Python
py
import torch import torch.nn.functional as F from torch.nn import Linear from torch_geometric.nn import (GraphConv, SAGPooling, global_mean_pool, JumpingKnowledge) class SAGPool(torch.nn.Module): def __init__(self, dataset, num_layers, hidden, ratio=0.8): super().__init__()...
benchmark/kernel/sag_pool.py
MIT
1,955
ff36007d4a1228f6626c2df54643fb688b50b11e
Python
py
#!/usr/bin/env python # coding: utf-8 # In[2]: import os, shutil from os.path import join as joinpath from os import listdir # In[3]: """ # Expected input format: an `images` folder with all images in flat structure, i.e. as direct children. datadir = "/mnt/beegfs/home/vu/Codalab-MetaDL/data/resisc45" imagedir =...
src/reptile-v4.py
MIT
25,119
ff999973613f63901a7ed420a61cf44920044f37
Python
py
"""A few utility function for the pruner.""" import copy import math import numpy as np import torch from scipy import optimize def _adapt_uniform_sample_size(probabilities, sample_size_target): """Do _adapt_sample_size for a uniform distribution (faster).""" idx = probabilities.nonzero() sample_size_tar...
src/torchprune/torchprune/method/base/base_util.py
MIT
3,738
3adcf29a50f9ad918e33d8fe96cb260cd1dbb566
Python
py
import torch.nn as nn from function import calc_mean_std def adjust_learning_rate(args, optimizer, iteration_count): """Imitating the original implementation""" lr = args.lr / (1.0 + args.lr_decay * iteration_count) for param_group in optimizer.param_groups: param_group['lr'] = lr def calc_conte...
loss.py
Apache-2.0
1,279
3add18f210145808cb6b2459e1950693fa5e45e9
Python
py
""" Sandbox for ECE score. """ import numpy as np import torch from train_joint import get_calibration def old_get_calibration(y, p_mean, num_bins=10): """Compute the calibration. References: https://arxiv.org/abs/1706.04599 https://arxiv.org/abs/1807.00263 Args: y: one-hot encoding of the...
ece_sandbox.py
MIT
4,799
5f159ebcdfac52ee88939e5306ec3f82f3e7a084
Python
py
import pickle import torch import numpy as np import torch.utils.data as data from torch.utils.data import TensorDataset, DataLoader import params import os import gzip from torchvision import datasets, transforms class Descendant_Activations(data.Dataset): def __init__(self, root, train=True, transform=None, do...
datasets/descendant_activations.py
MIT
4,994
03cf1b9d4a2c2057d91ad4908d01245a861a4568
Python
py
# pylint: disable=no-self-use, invalid-name import json import logging import math import numpy import pytest import torch import _jsonnet from allennlp.nn import InitializerApplicator, Initializer from allennlp.nn.initializers import block_orthogonal, uniform_unit_scaling from allennlp.common.checks import Configura...
allennlp/tests/nn/initializers_test.py
Apache-2.0
4,960
f9a3e98b992ec83260a13972c818a688487386f0
Python
py
'''GoogLeNet with PyTorch.''' import torch import torch.nn as nn norm_mean, norm_var = 0.0, 1.0 cov_cfg=[(22*i+2) for i in range(1+2+5+2)] class Inception(nn.Module): def __init__(self, in_planes, n1x1, n3x3red, n3x3, n5x5red, n5x5, pool_planes, cp_rate, tmp_name): super(Inception, self).__init__() ...
hrank/models/googlenet_cifar.py
MIT
6,582
458aedab41694642606f2a6b4a3c50c7d9cc8cdf
Python
py
import torch import geffnet from torch2trt import torch2trt import re from training.zoo.classifiers import DeepFakeClassifier from trustnet_utils import * import onnx print(torch.__version__) x = torch.randn((128, 3, 600, 600), requires_grad=True) with torch.no_grad(): model_path = "weights/model.pth" model = ...
torch2onnx.py
MIT
1,494
7c49e9eeb86bbe25cae72a3a06d84399f0c3bd78
Python
py
import os import inspect from functools import partial import torch.optim as optim from utils.polylr import PolyLR from datasets.cityscapes import CityscapesDataset from datasets.seg_transforms import RandomHorizontalFlip, RandomResize, RandomCrop, ToTensor, Normalize from torchvision.transforms import ColorJitter, Res...
configs/train/cityscapes_efficientnet_b1_hyperseg-s.py
CC0-1.0
2,716
3add6761dea1330b91d13e86615dc1cc5c65bccf
Python
py
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicabl...
lib/dr_utils/rep/Mesh.py
Apache-2.0
42,137
3addb00742350308e2f50ae1155e2ff60c98da5d
Python
py
#!/usr/bin/env python import sys, os import argparse import pygame import torch import numpy as np from PIL import Image from splatting import splatting_function from torch.utils.data.dataloader import default_collate from geofree import pretrained_models import imageio torch.set_grad_enabled(False) from geofree.modu...
scripts/braindance.py
MIT
17,010
b215698843ff290e2d41b54b95f1046e09c3f799
Python
py
import copy from collections import deque import gym import numpy as np import random import time import torch from torch import Tensor import torch.nn as nn import torch.nn.functional as F import warnings from timebudget import timebudget timebudget.set_quiet() from typing import List, Union, NamedTuple, Tuple clas...
rldqn.py
MIT
9,327
3ade124a079f1e305bc708782dfd388a485df819
Python
py
import torch.utils.data from fnet.data.fnetdataset import FnetDataset from fnet.data.tifreader import TifReader import fnet.transforms as transforms import pandas as pd import pdb class TiffDataset(FnetDataset): """Dataset for Tif files.""" def __init__(self, dataframe: pd.DataFrame = None, path_csv: str =...
fnet/data/tiffdataset.py
Unlicense
2,395
3ade2d998368d3c8f837822dd1293b2b6ac50946
Python
py
from functools import partial import torch.nn as nn from catalyst_rl.utils import metrics class IoULoss(nn.Module): """ Intersection over union (Jaccard) loss Args: eps (float): epsilon to avoid zero division threshold (float): threshold for outputs binarization activation (str)...
catalyst_rl/contrib/nn/criterion/iou.py
Apache-2.0
1,816
3ade36cdd09be166ec7455a94a0d5d6d818bb948
Python
py
########################################################################### # Created by: Hang Zhang # Email: zhang.hang@rutgers.edu # Copyright (c) 2017 ########################################################################### from __future__ import division import torch import torch.nn as nn from torch.nn.functio...
models/head/aspp.py
Apache-2.0
3,508
1e620b0c2ce595b904eceb0ab6df1895ec955b78
Python
py
import torch import torch.nn as nn from .utils import _transpose_and_gather_feat import torch.nn.functional as F # def _slow_neg_loss(pred, gt): # '''focal loss from CornerNet''' # pos_inds = gt.eq(1) # neg_inds = gt.lt(1) # neg_weights = torch.pow(1 - gt[neg_inds], 4) # loss = 0 # pos_pred ...
lib/models/losses.py
MIT
8,157
3ade3ad33f121d84a6a20acc284e3c1a393653e7
Python
py
import copy from pathlib import Path import warnings import numpy as np import pandas as pd import pytorch_lightning as pl from pytorch_lightning.callbacks import EarlyStopping, LearningRateLogger from pytorch_lightning.loggers import TensorBoardLogger import torch from pytorch_forecasting import Baseline, TemporalFu...
examples/test.py
MIT
2,582
3ade3bb52f57edba1c00d6a32f986f188fb7fed4
Python
py
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. """ Train a network across multipl...
build/lib.linux-x86_64-3.7/fairseq/trainer.py
BSD-3-Clause
20,506
3ade4856208cd476c435bd5a8ca63c9bc2f035aa
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Parameter import math import config as cfg from torch.cuda import amp # Implementation from https://github.com/HuangYG123/CurricularFace/blob/master/head/metrics.py class ArcFace(nn.Module): def __init__(self,in_features,out_...
src/head.py
MIT
4,180
10d5308087d45e7ebfdfae14aa2a269b3c1b9b6b
Python
py
from threading import Thread import torch import GPUtil from GPUtil import showUtilization as gpu_usage __all__ = ["make_hook", "_add_memory_hooks", "log_mem", "Monitor"] def make_hook(logs, idx, hook_type): def hook(self, *args): torch.cuda.synchronize() logs....
kirigami/utils/memory_utils.py
MIT
1,794
f9afd45e8e8c3282c9f614e7d0349e6d3a01403c
Python
py
import random from typing import List, Tuple import torch from torch import nn from torch.distributions import Normal from torch.nn import functional as f from src.data_process import VCTKBatch from .config import ( DecoderParams, DurationParams, EncoderParams, GaussianUpsampleParams, ModelParams, PostNetPara...
src/model/non_attentive_tacotron.py
MIT
16,053
42325f1f7c6e43a50ab5374eb0ff7b54ab7e495d
Python
py
import copy import random from functools import wraps import torch from torch import nn import torch.nn.functional as F from torchvision import transforms as T # helper functions def default(val, def_val): return def_val if val is None else val def flatten(t): return t.reshape(t.shape[0], -1) def singleto...
byol_pytorch/byol_pytorch.py
MIT
7,887
03cf98148001338566ae7a6a9ee0efab7393440c
Python
py
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ Dataloaders and dataset utils """ import glob import hashlib import json import os import random import shutil import time from itertools import repeat from multiprocessing.pool import Pool, ThreadPool from pathlib import Path from threading import Thread from zipfile im...
utils/datasets.py
MIT
45,236
dffbf2dca612937dd81f1d32b7bbf9b75e3b1aeb
Python
py
from scipy import spatial from lib.utils.img_utils import read_depth from lib.datasets.dataset_catalog import DatasetCatalog from lib.csrc.nn import nn_utils from lib.config import cfg import pycocotools.coco as coco import numpy as np from lib.utils.pvnet import pvnet_pose_utils, pvnet_data_utils import os from lib.ut...
lib/evaluators/linemod/rdopt.py
Apache-2.0
3,902
b2c93a9673d573dc7cb98f430ae57ff7cd0c4e63
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 random import time import numpy as np import torch from fairdiplomacy.agents.searchbot_agent import SearchBotAgent fr...
fairdiplomacy/env.py
MIT
3,507
3adea2bc0ffd133a2b5256f4321f662ed6715c78
Python
py
# -*- coding: utf-8 -*- """Linear module for dqn algorithms - Author: Kh Kim - Contact: kh.kim@medipixel.io """ import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class NoisyLinear(nn.Module): ...
rl_algorithms/dqn/linear.py
MIT
3,859
342c2b4db78a6e7f50270916c404552812b091a2
Python
py
import argparse import os import numpy as np import math import sys import torchvision.transforms as transforms from torchvision.utils import save_image from torch.utils.data import DataLoader from torchvision import datasets from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F i...
projects/wgan/wgan.py
MIT
5,408
d7a65e7eb5ce7eac633b83bef9813e536067680b
Python
py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import os import hparams def to_gpu(x): x = x.contiguous() if torch.cuda.is_available(): x = x.cuda(non_blocking=True) return torch.autograd.Variable(x) def process_text(train_text_path): with open(train_...
utils.py
MIT
3,255
3aded2ec7d6f9fe66b75c1c4f79613bda455aad5
Python
py
from __future__ import print_function, division import numpy as np import torch import torch.nn as nn import networks class VggEncoder(nn.Module): def __init__(self, config): super(VggEncoder, self).__init__() self.config = config self.relu = nn.ReLU(True) self.conv1 = nn.Conv2d(3...
network_nograd/VGGM.py
MIT
5,421
f9e0b413befd7b49ef5c9bf1b2090510a459f26b
Python
py
#/usr/bin/python from __future__ import print_function import argparse import torch import pickle import numpy as np import os import math import random import sys import matplotlib.pyplot as plt import data import scipy.io from torch import nn, optim from torch.nn import functional as F from etm import ETM f...
ETM-master/main.py
MIT
15,708
24b87da8e2e73e8fd5adf13381fdbcfdd0472e0a
Python
py
# # Copyright 2018 Analytics Zoo 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 applicable law or agreed to...
pyzoo/test/zoo/orca/learn/jep/test_pytorch_estimator_for_spark.py
Apache-2.0
2,736
4b548cfe832096c89295545b6a147fd26e3ff819
Python
py