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
from torch.nn.modules import Module import torch import math class Log_Loss(Module): def __init__(self, device): super(Log_Loss, self).__init__() self.device = device def forward(self,outputs,targets,bins,batch_size): loss = torch.zeros([batch_size],requires_grad= True).to(self.device) ...
optimization/log_loss.py
MIT
1,483
3a74f0ae287cc393bcc9059ddc780e66da373901
Python
py
from torch.utils.data import Dataset class Episode: def __init__(self, support_loader, query_loader, base_task, task_id, n_classes, tags): self.support_loader = support_loader self.query_loader = query_loader self.base_task = base_task self.task_id = task_id self.n_classes...
datasets/episode.py
MIT
589
3a74f2f4cceb4fe403c99b20c31e30888d8c2570
Python
py
from __future__ import print_function, with_statement, division import copy import os import torch from tqdm.autonotebook import tqdm from torch.optim.lr_scheduler import _LRScheduler import matplotlib.pyplot as plt try: from apex import amp IS_AMP_AVAILABLE = True except ImportError: import logging ...
pyTorchChitra/modelTraining/lrFinder.py
MIT
18,311
3a74f494d75f98c8a9425b89b373f765df715797
Python
py
# For Binary classification --> nn -- logits -- sigmoid -- BCE loss # For multi-class classification --> nn -- logits -- softmax -- CrossEntropyLoss import sys import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt # adding tenso...
pytorch-tuto/pytorch_rev_tensorboard.py
MIT
4,373
3a74fbefa98328e6605d60f8249ceaaba926f9d4
Python
py
# Adapted from SPFN import torch import torch.nn as nn from .point_convolution_universal import TransitionDown, TransitionUp from .model_util import construct_conv1d_modules, construct_conv_modules, CorrFlowPredNet, set_bn_not_training, set_grad_to_none from .utils import farthest_point_sampling, get_knn_idx, batched_...
model/Poinetnet2.py
MIT
8,255
7c783919a50a80ce2c3993da461e137edbd4900c
Python
py
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
flash/core/utilities/flash_cli.py
Apache-2.0
8,239
7cfb341342f5535282fd874619310f308938451e
Python
py
import torch.nn as nn import torch.nn.functional as F import torch.utils.data import torch class conv_block(nn.Module): """ Convolution Block """ def __init__(self, in_ch, out_ch): super(conv_block, self).__init__() self.conv = nn.Sequential( nn.Conv2d(in_ch, out_ch, ker...
model/AttentionUnet.py
MIT
4,714
3a75512255497d3256a3ed20adcc538c83508438
Python
py
#-*-coding:utf-8-*- # date:2021-06-15 # Author: Eric.Lee # function: handpose 3D Inference import os import argparse import torch import torch.nn as nn import numpy as np import time import datetime import os import math from datetime import datetime import cv2 import torch.nn.functional as F from models.resnet impo...
inference.py
Apache-2.0
13,711
3a75559c95457a1c68943f942714a45ca7add161
Python
py
import matplotlib.pyplot as plt import torch, pandas as pd, numpy as np import sys, os, json from collections import Counter base_path = os.path.dirname(os.path.realpath(__file__)).split('reproduce_results')[0] sys.path.append(base_path) from helper_classes.experiment import Experiment from sklearn.model_selection im...
Method/reproduce_results/train_clp/reproduce_training_length_predictors_carcinogenesis_kb.py
MIT
4,434
3a755ee1644841bd432014da9b76fbb7ea06fe31
Python
py
# camera-ready import torch import torch.utils.data import torch.nn.functional as F from torch.autograd import Variable import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import math import scipy.stats import pickle import cv2 # ############################################...
mdn_cell/datasets.py
MIT
5,402
800dc239577f1a94e151bdb799a65dd6fbe74334
Python
py
import os import torch import datetime import numpy as np import torch.nn.functional as F from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from .ppo import PPO from .gail import GAIL from . import utils from .data import RolloutStorage, FakeDataRollout class Trainer(object): ...
irl_dcb/trainer.py
MIT
10,304
ff222da4c74c3d0c680d1bff545cebdffe99088e
Python
py
import warnings warnings.filterwarnings('ignore') from loguru import logger logger.add('mask_rcnn.log', rotation='100 MB') import os import cv2 import json import random import numpy as np import pandas as pd from tqdm import tqdm from labelme import utils import torch import torch.nn as nn import torch.utils.data as...
unet/train_points.py
Apache-2.0
5,175
b2e39d18728f032edae91e94099d71395fada05f
Python
py
from typing import Sequence import pytorch_lightning as pl import torch import editdistance class CharacterErrorRate(pl.metrics.Metric): """Character error rate metric, computed using Levenshtein distance.""" def __init__(self, ignore_tokens: Sequence[int], *args): super().__init__(*args) se...
lab3/text_recognizer/lit_models/metrics.py
MIT
1,970
b241dc8cdeb18ccfecc4aa86c73eaa619ea401ef
Python
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- '''Main OpenQA training and testing script.''' ''' In order to train and test the model, please follow the following steps: #0. cut uncessary gpu memory used by gnome-shell reexecute gnome-shell: alt-f2 + r + 'enter' systemctl isolate multi-user ...
main.py
MIT
2,904
4241a2a853127b0e56d7be042fa60cfc5b4e60cb
Python
py
import torch import torch.nn as nn class SentencePlanner(nn.Module): def __init__(self, opt): super(SentencePlanner, self).__init__() self.hidden_size = opt.hidden_size self.batch_size = opt.batch_size planner_hidden_size = 300 if opt.task == "arggen": self.se...
src/modules/sentence_planner.py
MIT
8,835
e93e82f8ca8c1b47eb9d480266116f275a76bdd0
Python
py
from typing import Any, ClassVar, Dict import torch from ..decorators import pretty_repr @pretty_repr class Augmentation: TYPE: ClassVar[str] = "none" def transform(self, x: torch.Tensor) -> torch.Tensor: """Returns augmented observation. Args: x: observation. Returns...
d3rlpy-master/d3rlpy/augmentation/base.py
MIT
830
d72ccc372247a6d887b6771c9c2caaca2a9ac20e
Python
py
import torch import torch.nn import torch.nn.functional as nn import torch.autograd as autograd import torch.optim as optim import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import os from torch.autograd import Variable from tensorflow.examples.tutorials.mnist import in...
GAN/ebgan/ebgan_pytorch.py
Unlicense
2,614
454c6670a85c8f7344ba1df8cd2f7b6e8f4d97e9
Python
py
from dgllife.model import GCNPredictor from dgllife.model.gnn import GCN, GAT from dgllife.model.readout import WeightedSumAndMax import dgl from dgl import function as fn from dgl.ops import edge_softmax from dgl.base import DGLError from dgl.utils import expand_as_pair from dgl.nn.pytorch.utils import Identity import...
model.py
CC0-1.0
22,759
3a760e49d4d5d0254b3944cb83e0289c6e77352f
Python
py
################################################################################ # Starlab RNN-compression with factorization method : Lowrank and group-lowrank rnn # # Author: Donghae Jang (jangdonghae@gmail.com), Seoul National University # U Kang (ukang@snu.ac.kr), Seoul National University # # Version : 1....
rnn_compression_factorization/src/module/compressed_deepConv.py
Apache-2.0
3,766
3a764acf8d1caabc98b09accb593cf81261352b2
Python
py
from pytorch_composer import get_layer, Model from torch import rand from random import randint, random, choice, sample, shuffle from pytorch_composer.get_layer import get_layer, layers_list import pytorch_composer from pytorch_composer.CodeSection import Vars, Vocab import torch pytorch_composer.warnings_off() c...
test/layer_lab.py
MIT
8,089
3a764f3668e8b245de2182685b607e6f1ecace35
Python
py
import torch import numpy as np from model import Actor, Critic from replay_buffer import ReplayBuffer from her import HER_sampler from normalizer import Normalizer import utils class Policy: def __init__(self, params): self.relative_goal = params['relative_goal'] env = params['cached_env'] ...
policy.py
MIT
7,182
3a765f51de8e8294831f308748cbdc8393319191
Python
py
# -*- coding: utf-8 -*- import os import pdb import torch import torch.nn as nn import torchvision.models as models from . import util # https://pytorch.org/docs/stable/torchvision/models.html # models.resnet50((pretrained=True, progress=True)), resnet18, inception_v3 #-----------------------------------------...
src/models.py
Apache-2.0
7,802
3a7683c18b1cdffe687161f1df01030967b97054
Python
py
from spinup.utils.run_utils import ExperimentGrid from spinup import vpg import torch if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--cpu', type=int, default=4) parser.add_argument('--num_runs', type=int, default=3) args = parser.parse_args() ...
spinup/examples/bench_vpg_cartpole.py
MIT
687
45a62880b680160c3f30bf1a5df4070af7bf0f7f
Python
py
import torch.nn as nn import torch.nn.functional as F class TemporalConv(nn.Module): """Some Information about TCN""" def __init__(self, in_dim, out_dim, kernel_size, dilation): super(TemporalConv, self).__init__() self.padding_size = dilation*(kernel_size-1) self.temporal_conv = nn.C...
TCN/model.py
MIT
1,343
3a76cb70c5d9ede5b1cf4e70d98ba5a747fa6f89
Python
py
import torch from torch import nn from torch.nn import functional as F from math import log, pi, exp import numpy as np from scipy import linalg as la logabs = lambda x: torch.log(torch.abs(x)) class ActNorm(nn.Module): def __init__(self, in_channel, logdet=True): super().__init__() ...
model.py
MIT
11,187
3a76d4419bdd47807ee200b2b7772746a9d18cec
Python
py
import numpy as np import torch from ..base import Storage as S class ReplayBuffer(S): """ Storage class for Off-Policy algorithms. Parameters ---------- size : int Storage capacity along time axis. device: torch.device CPU or specific GPU where data tensors will be placed and...
pytorchrl/core/storages/off_policy/replay_buffer.py
MIT
6,744
dfeb7e14b0a1aaa18d2a554807b8c4e1ee72bb9d
Python
py
from __future__ import division import os import mock import torch import torchvision.transforms as transforms import torchvision.transforms.functional as F from torch._utils_internal import get_file_path_2 import unittest import math import random import numpy as np from PIL import Image try: import accimage excep...
test/test_transforms.py
BSD-3-Clause
60,688
3a76f3a1adb03d0bb2aa2b06779f231ca05893c9
Python
py
import pytest import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import syft from syft.frameworks.torch.tensors.interpreters.autograd import AutogradTensor from syft.generic.pointers.pointer_tensor import PointerTensor def test_wrap(): """ Test the .on() wrap funct...
test/torch/tensors/test_autograd.py
Apache-2.0
27,434
b29f1f5d756ed81058bff23d8d7675eaed8bbd86
Python
py
import os import json import multiprocessing as mp import time import shutil import torch.cuda from utils import config from data import data_path, load_embeddings from probe import train, summarize, report def run_layer(train_data, dev_data, test_data, task_name, model_name, mode, layer): task_dir = os.path.jo...
probing/main.py
Apache-2.0
5,508
3a7719aadc1fd4820ec83b14b5ea9d7d69ca177d
Python
py
# Program trains the network 3000 episodes or until its good enough # and then it shows the result by playing couple demo runs. # # Usage: # cargo build --lib # python python_pytorch.py # # You need Pytorch version 1.2.0 # Cargo builds lib to target/debug/librusted_cart_pole.so and it's used with FFI # https://cf...
examples/python_pytorch.py
MIT
6,958
3a7723838e34659c43e904a56634763d29048928
Python
py
# -*- coding: utf-8 -*- # # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import dgl import os import torch from dgl.data.utils import download, extract_archive, get_download_dir, _get_dgl_url from torch.utils.data import Dataset from .mol_tree import Vocab,...
examples/generative_models/jtnn/jtnn/datautils.py
Apache-2.0
9,335
425bf4287c9bbedabf2986751da5b7745dad4884
Python
py
#!/usr/bin/env python3 import torch from ..constraints import Positive from ..distributions import base_distributions from .likelihood import _OneDimensionalLikelihood class LaplaceLikelihood(_OneDimensionalLikelihood): r""" A Laplace likelihood/noise model for GP regression. It has one learnable parame...
gpytorch/likelihoods/laplace_likelihood.py
MIT
1,458
3a7736cddb63c98fdcda330bf195a138917a5614
Python
py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
tests/core/test_exp_manager.py
Apache-2.0
16,059
4284622edaa7fcc4581d55ba9ad05e6ac073ccdf
Python
py
#!/usr/bin/env python # 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/LI...
examples/pytorch/speech-recognition/run_speech_recognition_ctc.py
Apache-2.0
27,168
3a7747e79117f7aabd6cf0584f549ac7fc051e08
Python
py
#-*- coding: utf-8 -*- import sys import random import re import time import torch from torch.autograd import Variable from torch import optim import torch.nn as nn import torch.nn.functional as F from seq2seq_model import MemN2N_Seq2Seq from data_utils import * def init_command_line(argv): from argparse import ...
MemN2N/MemN2N/predict.py
MIT
6,234
3a775837fedc2eac6374351cae81b40ddcfa853c
Python
py
import math import time import numpy as np from torch import cat, matmul def batchify(*arrays, batch_size=10, shuffel=True): """Function that defines a generator that keeps outputting new batches for the input arrays infinit times. Arguments: *arrays: a number of arrays all assume to have sam...
sggm/baselines/utils.py
Apache-2.0
2,423
6b3df68b75112608142c82d9e44a63d07b883e88
Python
py
''' Visualize the trained model's feature maps. ''' import os from tqdm import tqdm import cv2 import numpy as np import torch from torch.utils.data import DataLoader from torchvision import transforms import matplotlib.pyplot as plt from load_dataset import LoadInputImages from attention_cnn import AttentionCNN from...
visualize.py
MIT
3,850
1eaf9b00b0c96cb0249dcf9b197f4173fc57a500
Python
py
import math import os import argparse import yaml import wandb from math import sqrt from pathlib import Path from easydict import EasyDict # torch from PIL import Image import torch from torch.optim import Adam from torch.optim.lr_scheduler import ExponentialLR # vision imports from torch.utils.data import DataLoad...
vqgan/train_vae.py
MIT
6,533
702ea850f92d04553a3294e7e3bc9a506278b10f
Python
py
''' load lottery tickets and evaluation support datasets: cifar10, Fashionmnist, cifar100 ''' import os import time import random import shutil import argparse import numpy as np from copy import deepcopy import matplotlib.pyplot as plt import torch import torch.optim import torch.nn as nn import torch.utils.data...
calculate_flops_regroup.py
MIT
8,273
5e92b8a3dc4372d7ffdb01790ed00b82f626e77a
Python
py
import torch from torch.nn import functional as F from torch.nn.modules import loss from mmcv.runner import load_checkpoint from mmcv import Config from ..builder import CLASSIFIERS, build_backbone, build_head, build_neck, build_classifier from .image import ImageClassifier from ..backbones.binary_utils.binary_blocks...
mmcls/models/classifiers/distiller.py
Apache-2.0
8,461
b29677208e2ae0c476aeeaa899b786a2ac05798f
Python
py
# Modified by Microsoft Corporation. # Licensed under the MIT license. from convlab.modules.word_dst.multiwoz.trade.trade_utils import * from convlab.modules.util.multiwoz.multiwoz_slot_trans import REF_SYS_DA, REF_USR_DA from convlab.modules.dst.state_tracker import Tracker from convlab.modules.dst.multiwoz.dst_util ...
convlab/modules/word_dst/multiwoz/trade/trade.py
MIT
10,532
5e3db9c1b7bf28d18e3c531bfc3b5759e6d1a645
Python
py
import torch from torch.autograd import Function from torch.autograd import Variable class Linear(Function): @staticmethod def forward(ctx, input, weight, bias=None): ctx.save_for_backward(input, weight, bias) output = input.new(input.size(0), weight.size(0)) output.addmm_(0, 1, input...
torch/nn/_functions/linear.py
MIT
3,117
708fb6b0d7859d873dec83dc1eaed8a6b797de0f
Python
py
import random from collections import defaultdict from typing import Any, Dict, List, Optional, Tuple, cast import torch from allennlp.common.checks import check_dimensions_match from allennlp.data.fields.text_field import TextFieldTensors from allennlp.data.vocabulary import Vocabulary from allennlp.models import Mod...
date/models/date.py
MIT
10,130
3a77b5ec48207f79a65335eee243b901591dd4eb
Python
py
import torch import torch.nn as nn import torch.nn.functional as F import dgl """ GAT: Graph Attention Network Graph Attention Networks (Veličković et al., ICLR 2018) https://arxiv.org/abs/1710.10903 """ from layers.gat_layer import GATLayer from layers.mlp_readout_layer import MLPReadout c...
nets/molecules_graph_regression/gat_net.py
MIT
2,435
24fed387e4abe78c3e442bac5bd0214faa459d23
Python
py
from typing import Optional from torch.utils.data import Dataset import collections from torch.utils.data._utils.collate import default_collate import numpy as np class DatasetOfSequences(Dataset): """ A Dataset which concatenates data into for a small window of frames Takes a list of Datasets, each corr...
slam/dataset/sequence_dataset.py
MIT
3,838
456398833ee1d883b16859ea45466ae8fbdde311
Python
py
import numpy as np import matplotlib.pyplot as plt import torch from torchvision import datasets, transforms, models from torch import nn from torch import optim import torch.nn.functional as F from PIL import Image from fx_training import loading_data from fx_training import build_and_train_model impor...
train.py
MIT
1,573
45c01996209e329c6fba315adf70e87e693c32f7
Python
py
from __future__ import print_function import sys import os import argparse import numpy as np from lib.dataset.voc import VOC_CLASSES if '/data/software/opencv-3.4.0/prlib/python2.7/dist-packages' in sys.path: sys.path.remove('/data/software/opencv-3.4.0/prlib/python2.7/dist-packages') if '/data/software/opencv-...
inference_dir.py
MIT
3,097
a936f8f3cc9e0b319cc0dc87cc228bc686696d7e
Python
py
import torch from catalyst.callbacks import BatchMetricCallback from torch import nn from dnn_cool.dsl import IFeaturesDict, IOut, ICondition, IFlowTaskResult from dnn_cool.utils import any_value class ReducedPerSample(nn.Module): def __init__(self, loss, reduction): super().__init__() self.loss...
dnn_cool/losses.py
MIT
15,503
e9c5a9f0ed8d683487a727b37d15367d27f97bc4
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from .box_head.box_head import build_roi_box_head from .mask_head.mask_head import build_roi_mask_head from .maskiou_head.maskiou_head import build_roi_maskiou_head class CombinedROIHeads(torch.nn.ModuleDict): """ Combines a ...
maskrcnn_benchmark/modeling/roi_heads/roi_heads.py
MIT
2,694
1e16c4f65676b125cdd91e7afd9959d2ccf1803d
Python
py
import math import torch from torch.optim.optimizer import Optimizer from .types import Betas2, OptFloat, OptLossClosure, Params __all__ = ('DiffGrad',) class DiffGrad(Optimizer): r"""Implements DiffGrad algorithm. It has been proposed in `DiffGrad: An Optimization Method for Convolutional Neural Netw...
torch_optimizer/diffgrad.py
Apache-2.0
5,635
a989f8a286ce0a47f20a0e94d5bbf64206a9e2d9
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import warnings from typing import Any, Union import numpy as np import torch class TensorAccessor(object): """ A helper class to be used with the __getitem__ method. This can be used for getting/setting the values for an attribute...
pytorch3d/renderer/utils.py
BSD-3-Clause
11,776
3afd600353f1d0f41c591d93a64c07c23f045850
Python
py
import torch from util.image_pool import ImagePool from .base_model import BaseModel from . import networks class Pix2PixModel(BaseModel): def name(self): return 'Pix2PixModel' @staticmethod def modify_commandline_options(parser, is_train=True): # changing the default values to match the ...
models/pix2pix_model.py
BSD-3-Clause
4,467
3a783e152499169b6bc450718fb768ec9d1e7f32
Python
py
import torch from torch import Tensor, cat from torch.nn import functional as F from models.building_blocks.covariates_feature_extractor import \ CovariatesFeatureExtractor from models.building_blocks.mlp import MLP from models.building_blocks.neural_network import NeuralNetworkEstimator from models.building_block...
Structured/models/cat.py
MIT
1,975
038858723904a693ca1ff4038268cf704d82c9e5
Python
py
import argparse import os import sys import cv2 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import kornia as tgm def load_data(root_path, sequence_name, frame_id): # index paths file_name = 'frame_%04d' % (frame_id) image_file = os.pa...
examples/depth_regression/main.py
ECL-2.0,Apache-2.0
7,458
4b79e0fccfd35dbc5f89634350ff6820b9eaf3b6
Python
py
""" script for generating samples from a trained model """ import torch as th import argparse import matplotlib.pyplot as plt import os from torch.backends import cudnn # define the device for the training script device = th.device("cuda" if th.cuda.is_available() else "cpu") # th.manual_seed(3) # set manual seed ...
sourcecode/latent_space_interpolation.py
MIT
4,751
1ed1c90b2f25fb4df3a36f9ff3d46d3dc1fbf693
Python
py
# -*- coding: utf-8 -*- import sys import torch from torch._C import _add_docstr, _linalg # type: ignore[attr-defined] LinAlgError = torch._C._LinAlgError # type: ignore[attr-defined] Tensor = torch.Tensor common_notes = { "experimental_warning": """This function is "experimental" and it may change in a futur...
torch/linalg/__init__.py
Intel
94,089
3436b3fa4de744268faa9bae5025b4c0c797218b
Python
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 6 16:45:16 2018 @author: landrieuloic """ from __future__ import division from __future__ import print_function from builtins import range import random import numpy as np import os import functools import torch import torchnet as tnt import h5py i...
learning/skitti_dataset.py
MIT
7,313
3a7870e9a2e686337f7588a021caf0937f90e7d8
Python
py
from __future__ import print_function from __future__ import division import argparse import random import torch import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data from torch.autograd import Variable import numpy as np from warpctc_pytorch import CTCLoss import os import utils imp...
train.py
MIT
7,314
ff1381bb24a27e9aa58fdf04083f6a38d382ad02
Python
py
import re import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader, random_split from tqdm import tqdm from reformer_pytorch import Reformer, ReformerLM from transformers import BertTokenizer, PreTrainedTokenizer from fairseq.optim.adafactor import Adafactor ...
pretraining/self-supervised.py
MIT
15,486
3a788522a8416614056ceb421dcd1d60e6780500
Python
py
import torch from cleverhans.torch.utils import optimize_linear def fgm(model_fn, x, eps, norm, loss_fn=None, clip_min=None, clip_max=None, y=None, targeted=False): x = x.clone().detach().to(torch.float).requires_grad_(True) if y is None: _, y = torch.max(model_fn(x), 1) if loss_fn is Non...
adversarial/fgm.py
Apache-2.0
693
3a788ee59754bc7c6c8a87fc7c3ee73a7a4e23fd
Python
py
""" Author: Parag Mali Data reader for the GTDB dataset Uses sliding windows to generate sub-images """ from .config import HOME import os.path as osp import sys import torch import torch.utils.data as data import cv2 import numpy as np from gtdb import box_utils from gtdb import feature_extractor import copy import u...
data/gtdb_new.py
MIT
9,726
4b38b1f0dc0323800cb95225238205bb55e5da98
Python
py
from collections import OrderedDict from torch import nn class ConvBNReLU(nn.Sequential): def __init__(self, in_planes, out_planes, kernel_size=3, stride=(1, 1), groups=1): padding = (kernel_size - 1) // 2 super(ConvBNReLU, self).__init__( nn.Conv2d(in_planes, out_planes, kernel_size, s...
recognition/src/models/modules/mobile_conv.py
MIT
1,360
52aed2131ea29cfbebe713c95c693809c8371384
Python
py
import numpy as np import torch import torch_geometric import utils.metrics.metric as module_metric from base.base_trainer import BaseTrainer from datasets.scannetlabelgraph_dataloader import ScanNetGraphDataLoader from models.singleconvmeshnet import SingleConvMeshNet from utils import MetricTracker from utils.metric...
trainers/segmentation_trainer.py
MIT
12,701
3a78f6ec5d4823166943de8ebf9f4da2e60fc52b
Python
py
import argparse import json import logging import os import glob import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler from tqdm import tqdm, trange from attrdict import AttrDict from transformers import ( BertConfig, BertTokenizer, AdamW, get_linear...
run_goemotions.py
Apache-2.0
11,410
fceec334a88de9e842d86400b54cb23cc045c188
Python
py
import glob import numpy as np import os.path as osp from PIL import Image import random import struct from torch.utils.data import Dataset import os import scipy.ndimage as ndimage import h5py import cv2 import xml.etree.ElementTree as et from skimage.transform import resize import scipy.ndimage as ndimage class Batc...
PointCloud/dataLoader.py
MIT
20,232
d72a98cc54841908b4ea29d4be0e8c73ae57c96b
Python
py
# -------------------------------------------------------- # Licensed under The MIT License [see LICENSE for details] # -------------------------------------------------------- import sys sys.path.insert(0, "HCG") import argparse import datetime import numpy as np import torch from core.bc import BC from core.ddpg impo...
robot_clipseg.py
MIT
16,802
3a7919fb2bf018f65db478a52562f1ca2a401400
Python
py
""" Created on Feb 26, 2018 @author: Siyuan Qi Description of the file. """ import os import random import numpy as np import scipy.misc import torch import torchvision import cv2 import scipy.io as sio import matplotlib.pyplot as plt import metadata import config # TODO: Check if needed modification def parse_c...
gpnn-master/src/python/datasets/HICO/roi_feature_model.py
MIT
8,415
5e37652c32efe7b619d0f97dfb93e31b60e1cafb
Python
py
# -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch from torch import nn from cvpods.structures import ImageList from ..postprocessing import detector_postprocess, sem_seg_postprocess __all__ = ["PanopticFPN"] def build_roi_heads(cfg, input_shape): pass ...
cvpods/modeling/meta_arch/panoptic_fpn.py
Apache-2.0
8,463
d7ba58f43dcdc73c7ea048d2f3083ac8c24ef56f
Python
py
import torch import torch.nn as nn import torchvision from models import resnet from lib.nn import SynchronizedBatchNorm2d import pandas as pd import numpy as np class SegmentationModuleBase(nn.Module): def __init__(self): super(SegmentationModuleBase, self).__init__() def pixel_acc(self, pred, labe...
models/object_net.py
MIT
11,232
a971d06a91580393a1bce9b165211ee00d4145d3
Python
py
# Copyright (c) 2022, Kwanhyung Lee. All rights reserved. # # Licensed under the MIT License; # you may not use this file except in compliance with the License. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTI...
builder/models/detector_models/cnn2d_lstm_v8_6.py
MIT
7,759
3a7944d4abb1945abcbc31977647229327acc31d
Python
py
import argparse import os import random import shutil import warnings import numpy as np import torch import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.optim import torch.multiprocessing as mp import torch.utils.data import torch.utils.data.distributed import to...
image_classification_experiments/train_base_init_network_from_scratch.py
MIT
19,556
805296ce28673119c038b8726c7f11526bc71cf1
Python
py
import torch from allennlp.common.registrable import Registrable class MatrixAttention(torch.nn.Module, Registrable): """ ``MatrixAttention`` takes two matrices as input and returns a matrix of attentions. We compute the similarity between each row in each matrix and return unnormalized similarity s...
allennlp/modules/matrix_attention/matrix_attention.py
MIT
885
24be3b11fe49d566368a0ea838adf79c38356390
Python
py
# coding: utf-8 from __future__ import print_function from __future__ import division import torch from torch.autograd import Variable import numpy as np import pickle from collections import deque, Counter import pdb class RnnParameterData(object): def __init__(self, loc_emb_size=500, uid_emb_size=40, voc_emb_s...
train_simple.py
MIT
12,672
3a79711bdd49dc059a2cdded7a7b0faf886e8c25
Python
py
import torch.nn as nn import torch.nn.functional as F from models.VAGCN_utils import PointNetSetAbstraction, knn import torch def sphg(pos, r, B, flow='source_to_target', max_num_neighbors=48, fpsi=None, resetFpsi=False, random_replace=True): # Make sure "batch" is ascending assert flow in ['source_t...
models/VAGCN_part_seg.py
MIT
11,655
5f667e835d1f37564ce0e801f2d4a0d23dece9e9
Python
py
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 ...
tests/test_modeling_xlnet.py
Apache-2.0
28,389
12b3e13f3f9e87aa643295c9caf5aef8b85173f2
Python
py
# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and # Technical University of Darmstadt. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source ...
Pyrado/pyrado/exploration/stochastic_params.py
DOC,Zlib,BSD-3-Clause
9,405
3a798b15994da076eee2f033832f290e47aa8649
Python
py
""" Copyright 2020 The Secure, Reliable, and Intelligent Systems Lab, ETH Zurich 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 appl...
Finance/common/utils.py
Apache-2.0
6,011
3a798ebecce81f66bb6373b17e9dfe04716b041e
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/utilities/__init__.py
Apache-2.0
2,311
5e6b99f1cea0caea05bfefa47682458229a1db3e
Python
py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import unittest from typing import cast, List from unittest.mock import MagicMock impor...
torchrec/distributed/planner/tests/test_proposers.py
BSD-3-Clause
9,176
3a79be3660cd0af2d776f6113749dc3872710904
Python
py
import torch import torch.nn.functional as F from torch.optim import Adam from utils.misc import soft_update, hard_update, enable_gradients, disable_gradients from utils.agents import AttentionAgent from utils.critics import AttentionCritic from utils.attention_medium import AttentionMedium from utils.error_detector im...
algorithms/MAFTRL.py
MIT
15,506
4237d22ca15473faf0716f88589012b77b56741e
Python
py
import torch from BGNN import BGNNPredictor import pandas as pd import numpy as np import json import os from dgl.data.utils import load_graphs from dgl.nn.pytorch import GATConv as GATConvDGL, GraphConv, ChebConv as ChebConvDGL, \ AGNNConv as AGNNConvDGL, APPNPConv from torch.nn import Dropout, ELU, Sequential, Li...
examples/pytorch/bgnn/run.py
Apache-2.0
6,834
3a79fee5113548ebf76460453a79c126501fa588
Python
py
import warnings import matplotlib.pyplot as plt import mmcv import numpy as np import pycocotools.mask as maskUtils import torch from mmcv.parallel import collate, scatter from mmcv.runner import load_checkpoint from mmdet.core import get_classes from mmdet.datasets.pipelines import Compose from mmdet.models import b...
mmdet/apis/inference.py
BSD-2-Clause
10,262
3a7a07dc533d1936e2acae131b6ef3cd3bafd845
Python
py
import argparse import datetime import os import time import sys sys.path.append("/home1/machen/meta_perturbations_black_box_attack") import glog as log import numpy as np import torch import torch.nn as nn from adversarial_defense.prototype_conformity_loss.contrastive_proximity import Con_Proximity from adversarial_d...
adversarial_defense/prototype_conformity_loss/pcl_training_adversarial_pgd.py
Apache-2.0
14,421
e9d3f5ed06fce0f52294606a861c30f2d06e4d56
Python
py
""" eureka_train.py Zhiang Chen, Feb 2020 train mask rcnn with eureka data """ import transforms as T from engine import train_one_epoch, evaluate import utils import torch from rock_c3 import Dataset from model import get_rock_model_instance_segmentation import numpy as np import time class ToTensor(object): def...
rock_c3_train2.py
Apache-2.0
4,495
3a7a4322e341bb95fceeb660e3e9fc345165c7f6
Python
py
import numpy as np import jax.numpy as jnp from jax import config import tensorflow as tf import torch import pytest import tensornetwork from tensornetwork import backends config.update("jax_enable_x64", True) np_real = [np.float32, np.float64] np_complex = [np.complex64, np.complex128] np_float_dtypes = np_real + np...
tensornetwork/tests/testing_utils.py
Apache-2.0
3,192
52b6f6cc3e926b608855354abaffcc924d7f61e1
Python
py
from collections import namedtuple import math import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd.function import InplaceFunction, Function QParams = namedtuple('QParams', ['range', 'zero_point', 'num_bits']) _DEFAULT_FLATTEN = (1, -1) _DEFAULT_FLATTEN_GRAD = (0, -1) ...
quantize.py
MIT
16,209
dfaa71f9bae8b6f6bb94b20b65d9856fd9f67b60
Python
py
# ==================================================== # Library # # ==================================================== import os import gc import sys import math import time import random import shutil from requests import get from pathlib import Path from contextlib import contextmanager from collections import def...
code/014/ver07/siim-014-train-eff-4class-step3-ver05.py
CC-BY-4.0
33,338
7c7cb9da4c401a1c1fd29c4589e5e259aa68b983
Python
py
import torch import torch.autograd as autograd import torch.nn as nn import pdb import torch.nn.functional as F import numpy as np START_TAG = -2 STOP_TAG = -1 # Compute log sum exp in a numerically stable way for the forward algorithm def log_sum_exp(vec, m_size): """ calculate log of exp sum ...
model/crf.py
Apache-2.0
14,106
3a7a6f9682c286b1f282fcec379a6e225c3a9cc2
Python
py
from argparse import ArgumentParser from typing import Tuple import pytorch_lightning as pl from torchvision import transforms from transformers import T5Tokenizer from .dataset import DocVQADataset class DocVQADataModule(pl.LightningDataModule): def __init__(self, hparams) -> None: super().__init__() ...
src/data/docvqa/data_module.py
MIT
3,561
ff37a5932fd7dc46146d1b676a6bf776b80df8c4
Python
py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -------------------------------------------------------------------------- from . import (_utils, _io, _logger, ...
orttraining/orttraining/python/training/ortmodule/_training_manager.py
MIT
21,253
29ffb0dc7091fc123f818dc495787c2bcfd10d7d
Python
py
# camera-ready from datasets import ToyDatasetEvalKL # (this needs to be imported before torch, because cv2 needs to be imported before torch for some reason) from model import ToyNet import torch import torch.utils.data import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import numpy a...
1dregression/2/mlis_eval.py
MIT
3,332
e922ea8a1dc7ff0ad81bc604462209c71a35fd3e
Python
py
import json import logging import os import shutil import torch class Params(): def __init__(self, json_path): """ ### Función `__init__` Almacena los parámetros contenidos en json_path sobre la instancia self. #### Parámetros: * `self`: instancia a inicializar. ...
code/ner/utils.py
CC-BY-4.0
5,611
3a7aacee366a32cd2aee71a9bace3c2e1b416307
Python
py
import os import sys import json import numpy as np from PIL import Image from datetime import datetime from env.thor_env import ThorEnv from eval import Eval import torch import constants import torch.nn.functional as F from torchvision.utils import save_image from torchvision.transforms.functional import to_tensor f...
alfred/models/eval_moca/eval_subgoals_seq.py
MIT
15,358
34009656bf3093981d6cfaacca21f408a9482380
Python
py
import torch import torch.nn as nn import torch.nn.functional as F class InitialConv(nn.Module): def __init__(self, out_channels=16): super().__init__() self.out_channels = out_channels self.conv = nn.Conv3d(in_channels=1, out_channels=out_channels, kernel_size=5, stride=1, padding=2) ...
models/vnet3d.py
MIT
7,789
3a7b0398ea9f5d363f60d541c8b3295c85e2e4f8
Python
py
from __future__ import annotations import logging from typing import Any, cast, Dict, List, Optional import torch from lightkit import ConfigurableBaseEstimator from lightkit.data import collate_tensor, DataLoader, dataset_from_tensors, TensorLike from lightkit.estimator import PredictorMixin, TransformerMixin from .li...
pycave/clustering/kmeans/estimator.py
MIT
9,849
5f5ece876bfcbb013d42184acc0b2303b770e134
Python
py
import zipfile from torch.hub import download_url_to_file import argparse import os # If the link is broken you can download the MS COCO 2014 dataset manually from http://cocodataset.org/#download MS_COCO_2014_TRAIN_DATASET_PATH = r'http://images.cocodataset.org/zips/train2014.zip' # ~13 GB after unzipping PRETRAINE...
utils/resource_downloader.py
MIT
2,029
3a7b3312fed3ce46ca9eb0a571c62d008f88ec69
Python
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2020 Patrick Lumban Tobing (Nagoya University) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) from __future__ import division from __future__ import print_function import argparse from dateutil.relativedelta import relativedelta from distutils.ut...
src/bin/train_nstages-sparse-wavernn_dualgru_compact_lpc_mband_16bit.py
Apache-2.0
76,198
3a7b468b00c0a90dfc58d4161c510dd4ff6f8960
Python
py
#!/usr/bin/python3 import argparse import os import sys import torch # Aimet-related imports from aimet_torch.model_validator.model_validator import ModelValidator # TDDFA-related imports import models from utils.tddfa_util import load_model def main(): parser = argparse.ArgumentParser(description='3DDFA Compr...
check_model.py
MIT
855
3a7b49cd360e5765ea3adc01f5ea4f047340530e
Python
py
import random import torch import torch.nn as nn from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence class LSTM(nn.Module): """ LSTM-RNN (text) network implementation """ def __init__(self, n_classes=10, vocabulary_size=26, hidden_dim=2...
models/lstm.py
MIT
2,820
d7515d9f87e32fb4ac14e068724834534cd0ea62
Python
py
import cvxpy as cp import math import numpy as np import torch import torchvision import torchvision.transforms as transforms import torch.backends.cudnn as cudnn ''' Global Constants: TASK_NAME: Name of the verification task (deprecated) PATH: The path of the model file. (Initialized in...
verify/mnist.py
Apache-2.0
14,832
7cfb108a6570abbe0c923e6564963deaf8c48a7e
Python
py