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
#!/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 import argparse import logging import math import os import sys import numpy as np import torch import torch.multiproce...
baseline/src/bin/calc_rec_gru-cyclevae-mult-mix-scpost_laplace.py
MIT
13,262
a987274e9342fa28707b8f9a202071dcfa08bd1e
Python
py
from __future__ import division """ Creates a ResNeXt Model as defined in: Xie, S., Girshick, R., Dollar, P., Tu, Z., & He, K. (2016). Aggregated residual transformations for deep neural networks. arXiv preprint arXiv:1611.05431. import from https://github.com/facebookresearch/ResNeXt/blob/master/models/resnext.lua ...
cifar10-code/models/imagenet/resnext.py
Apache-2.0
7,780
fef3b86cc919e0605e17185511522d940bbf06b7
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/callbacks/test_gpu_stats_monitor.py
Apache-2.0
4,874
4223a7e7b9e3fdb65cc3c9927d3379eeed3ae2ae
Python
py
import math import torch from torch import nn class MultiheadAttention(nn.Module): """ A multihead attention implementation. """ def __init__( self, *, num_heads: int, input_state_dimension: int, key_query_dimension: int, value_dimension: int, ...
buglab/models/layers/multihead_attention.py
MIT
3,681
f93bc6460d145b72c63587aeb0e36ecfc2607db6
Python
py
import math from collections import OrderedDict import numpy as np import torch from torch import nn as nn from torch.nn import functional as F from utils.misc import param_ndim_setup import matplotlib.pyplot as plt class LossFn(nn.Module): def __init__(self, sim_loss_fn, reg_l...
model/loss.py
MIT
16,224
fef3edfbe5a391cb242c734504d8876e6b647268
Python
py
#!/usr/bin/python # coding:utf-8 """ @author: yyhaker @contact: 572176750@qq.com @file: model.py @time: 2019/3/9 15:40 """ import torch import torch.nn as nn from myutils import GRU, SelfAttention, Linear, seq_mask class RNNAttention(nn.Module): """Text RNN Attention model.""" def __init__(self, config, pret...
src/model/text_rnn_att.py
MIT
1,632
b2d125546c16b99e4bb6cf68d26d77a22fb3b787
Python
py
import os import torch try: import ujson as json except ImportError: import json from tqdm import tqdm if torch.__version__ >= '1.6.0': from torch.cuda.amp import autocast else: from ..torch_amp_dummy import autocast from .base import BaseTester from ..seg_utils import ConfusionMatrix from ..lane_det_u...
utils/runners/lane_det_tester.py
BSD-3-Clause
5,668
7c567f8f52ad2ceee751c3ff64ce01627186bce2
Python
py
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2017 Kai Arulkumaran # # 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,...
agent.py
MIT
8,779
7ceb9b498acb0a92209da0ab25ccefeb4d5af2f9
Python
py
# Copyright (c) MONAI Consortium # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, so...
tests/test_label_to_contour.py
Apache-2.0
6,691
fef40af08dc3f260551662ce7dfc8f0174c0243a
Python
py
import torch.nn.functional as F def get_activation(activation): if callable(activation): return activation if activation is None: return lambda x: x if not isinstance(activation, str): raise ValueError("'activation' is expected a 'string', " f"but got {ty...
graphgallery/nn/layers/pytorch/get_activation.py
MIT
557
65277db519562c89b0a2604bae593db0d237d4e7
Python
py
""" A simple walkthrough of how to code a convolutional neural network (CNN) using the PyTorch library. For demonstration we train it on the very common MNIST dataset of handwritten digits. In this code we go through how to create the network as well as initialize a loss function, optimizer, check accuracy and more. P...
ML/Pytorch/Basics/pytorch_simple_CNN.py
MIT
3,939
e93c7e81a614c68da72e85fe851cafd7eb62f45e
Python
py
import copy import datetime from termcolor import colored from tqdm import tqdm import torch import numpy as np import training.utils as utils import torch.nn.functional as F from data_utils import EnvSampler from torch.utils.data import DataLoader def train_loop(train_loaders, model, opt, ep, args): stats = {} ...
src/training/dro.py
MIT
6,356
d706efce0798b3683c474c0f008c123b28991b50
Python
py
from typing import Dict, Union from overrides import overrides import torch from pytorch_pretrained_bert.modeling import BertModel from allennlp.data.vocabulary import Vocabulary from allennlp.models.model import Model from allennlp.modules.token_embedders.bert_token_embedder import PretrainedBertModel from allennlp....
bert_mcq/bert_mcq_model.py
MIT
5,899
4b47c7ede80aa8d9bc3649c5fe8c9c38ba6e31eb
Python
py
import os import sys os.environ['TOKENIZERS_PARALLELISM'] = 'false' sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import random import argparse import numpy as np import torch from torch.utils.data import DataLoader import pytorch_lightning as pl from pytorch_lightning.callbacks.early_s...
seq2seq/lightning/run_lightning.py
Apache-2.0
2,377
7c2c718f600a91695d023549874d1e13257a302f
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 appli...
examples/nlp/language_modeling/megatron_gpt_test.py
Apache-2.0
2,737
24770fac0e3caffad794f1c247a1b5605ee1b40d
Python
py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import os import unittest import pytest import sys import copy import numpy as np from numpy.testing import assert_allclose, assert_array_equal import onnx import torch import torch.nn as nn import torch.nn.functional as F f...
onnxruntime/test/python/onnxruntime_test_ort_trainer.py
MIT
32,836
d77cd6569988155d23d178f4809e362748c382fb
Python
py
from test_pytorch_common import TestCase, run_tests import torch import torch.onnx from torch.onnx import utils, OperatorExportTypes, TrainingMode, register_custom_op_symbolic from torch.onnx.symbolic_helper import _set_opset_version, _set_operator_export_type, _set_onnx_shape_inference import torch.utils.cpp_extensio...
test/onnx/test_utility_funs.py
Intel
46,908
28c2979ff2c11a5479ae7936e8bc6f4e1283fc88
Python
py
"""BackPACK implementation of operations used in ``vivit.optim``.""" from test.implementation.backpack import BackpackExtensions from typing import Any, Dict, List, Optional from backpack import backpack from torch import Tensor from vivit.optim import GramComputations from vivit.optim.computations import BaseComput...
test/implementation/optim_backpack.py
MIT
8,130
fef46454a07edd64a06f07a4c983be324f82205b
Python
py
# -*- coding: utf-8 -*- """Implementation of NTN.""" from typing import Any, ClassVar, Mapping, Optional import torch from torch import nn from ..base import EntityEmbeddingModel from ...constants import DEFAULT_EMBEDDING_HPO_EMBEDDING_DIM_RANGE from ...nn.emb import EmbeddingSpecification from ...typing import Hin...
src/pykeen/models/unimodal/ntn.py
MIT
9,068
24e9e3a663c5a3a9196cd71bebbf05ef0f663399
Python
py
import numpy as np import torch import os from a2c_ppo_acktr.arguments import get_args from eval import plot_env, play_env, benchmark_env, robustness_test from a2c_ppo_acktr.envs import make_vec_envs from a2c_ppo_acktr.utils import get_vec_normalize # initialize args = get_args(is_train=False) device = args.device ...
test.py
MIT
1,670
e666e635b5e09bbc8171e46a888164b46350d9d9
Python
py
# Here are some basic settings. # It could be overwritten if you want to specify # some configs. However, please check the correspoding # codes in loadopts.py. import torchvision.transforms as T import random from PIL import ImageFilter from .dict2obj import Config class _GaussBlur: def __init__(self...
src/config.py
MIT
4,599
7cdc6ef5cf40767c00b505a23eef1f3b85bcf297
Python
py
""" This subpackage was borrowed from `torchvision`__. __ https://github.com/pytorch/vision """ import numpy as np import torch def to_tensor(pic: np.ndarray) -> torch.Tensor: """Convert ``numpy.ndarray`` to tensor. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Retu...
catalyst/contrib/data/cv/transforms/torch.py
Apache-2.0
4,848
28c96b4370af007e0775ffbe5b4fc2c6397cc8a5
Python
py
# ------------------------------------------------------------------------------ # Portions of this code are from # CornerNet (https://github.com/princeton-vl/CornerNet) # Copyright (c) 2018, University of Michigan # Licensed under the BSD 3-Clause License # -------------------------------------------------------------...
src/lib/models/losses.py
MIT
9,560
fde55191762a0a3881e847173726fee2f62798ea
Python
py
import torch import torch.nn as nn from utils.global_variables import Global from model.layers import embedding, outputLayer class Bilstm(nn.Module): def __init__(self, config): super(Bilstm, self).__init__() self.config = config self.embedding = embedding.Embedding(config) self.rnn...
baselines/DMCNN_BiLSTM_(CRF)/model/Bilstm.py
MIT
3,216
7027ab409aad8a583780e1e7411abc5cff25724b
Python
py
import typing from typing import Optional, Any import gym import gym_minigrid.minigrid import numpy as np import torch from babyai.utils.format import InstructionsPreprocessor from gym_minigrid.minigrid import MiniGridEnv from core.base_abstractions.sensor import Sensor, prepare_locals_for_super from core.base_abstra...
plugins/minigrid_plugin/minigrid_sensors.py
MIT
4,254
fef4b53f026f0879f8be13166b110a80e812f024
Python
py
import math import torch from kge import Config, Dataset from kge.model.kge_model import KgeEmbedder, KgeModel, RelationalScorer class RescalScorer(RelationalScorer): r"""Implementation of the RESCAL KGE scorer.""" def __init__(self, config: Config, dataset: Dataset, configuration_key=None): super(...
kge/model/rescal.py
MIT
2,890
6523968f59ad19fbfed17525fa511d86b82d40be
Python
py
import datetime import logging import sys from collections import defaultdict from copy import deepcopy import joblib import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torchvision import datasets from torch.utils.data import Dataset, DataLoader SCRIPT_NAME = "fully-connected-e...
section2/fully-connected-ewc-si.py
MIT
10,343
b2dba0c096f88cfeed91c6edcfcf07029e5a1652
Python
py
import uuid import pandas as pd from typing import * import torch from torch import nn from fastai.vision.all import * idx2lbl = {0:"Cassava Bacterial Blight (CBB)", 1:"Cassava Brown Streak Disease (CBSD)", 2:"Cassava Green Mottle (CGM)", 3:"Cassava Mosaic Disease (CMD)", 4:"...
experiments/cassava_utils.py
MIT
4,379
4b24e9f8c0bee8c072b645b7593e5cb0e2841dc3
Python
py
#!/usr/bin/env python3 import os import random import unittest from math import pi import gpytorch import torch from gpytorch.likelihoods import GaussianLikelihood from gpytorch.models import AbstractVariationalGP from gpytorch.test.utils import least_used_cuda_device from gpytorch.variational import CholeskyVariatio...
test/examples/test_batch_whitened_svgp_gp_regression.py
MIT
5,726
1283244c859ef5b0de3356dabeb9ce082eea420c
Python
py
################ # # train.py # # Trains a FasterRCNN-based detector for the wildlife classification project. # # Most of the actual training is deferred to the FasterRCNNTrainer class in trainer.py. # ################ import os import matplotlib from tqdm import tqdm import time import numpy as np import tensorboardX...
FasterRCNNDetection/train.py
MIT
12,305
1ee2db742c81f13422d0e823d3b5e7c5431976c2
Python
py
import torch from torch import nn from collections import OrderedDict class ChannelAttention(nn.Module): def __init__(self, in_channels: int, out_channels: int, n_layers: int = 1) -> None: super(ChannelAttention, self).__init__() self.attn = nn.Sequential() channels = [in_channels] + [out_...
torchop/conv/bam.py
MIT
3,983
dfc7073b7625c3152f2a738c7fd9f615dfa2790e
Python
py
# https://github.com/pranz24/pytorch-soft-actor-critic import argparse import collections import os import random import time from distutils.util import strtobool import gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from gym.spaces import Box fro...
cleanrl/sac_continuous_action.py
MIT
15,610
7cdf40bc9194bb28d147d2844345d781e28e8eec
Python
py
""" Copyright 2019-present NAVER Corp. 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, so...
loader.py
Apache-2.0
6,556
e9b5506dfdcd0698147a05f6f9aeeec4c6df5196
Python
py
import sys import inspect import torch import torch.nn as nn import torch.nn.functional as F class Base(nn.Module): def __init__(self): super(Base, self).__init__() self.criterion = nn.CrossEntropyLoss() def _initialize_weights(self): for m in self.modules(): if isinstance...
lth/models/utils.py
MIT
1,964
10beea9bec77d85ce9f950652deb58f1f687ef3a
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 from typing import List, Optional import torch from torch import nn from fairseq.models import ( FairseqEncoder, Fair...
fairseq/models/text_to_speech/tts_transformer.py
MIT
17,002
fef56af6d533ea904cd433db71188742a5cb3e6a
Python
py
"""This module defines a configurable SSTDataset class.""" import pytreebank import torch from loguru import logger from pytorch_transformers import BertTokenizer from torch.utils.data import Dataset logger.info("Loading the tokenizer") tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") logger.info("Load...
bert-sentiment-master/bert_sentiment/data.py
MIT
2,817
455db84f5a93700ebb13130d5be7cc51989d0897
Python
py
import torch import torch.nn as nn import torch.nn.functional as F class Encoder(nn.Module): def __init__(self): super(Encoder, self).__init__() self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=2, padding=1, bias=False) # out: 64 x 64 x ...
models/encoder.py
Apache-2.0
2,183
ff94326934dbef58cc09b873621bbef51d000111
Python
py
import numpy as np import torch from mpi4py import MPI def setup_MPI(): try: comm = MPI.COMM_WORLD # Convert the Object to a Class so that it is possible to add attributes later class A(MPI.Intracomm): pass comm = A(comm) except: comm = None return comm ...
mpi4pytorch.py
MIT
3,115
d78ee7a8a4c2763a365c12f3eeab155b68c4e61c
Python
py
from typing import Dict, Union, Set import logging from overrides import overrides import torch from allennlp.data.fields.field import Field from allennlp.data.vocabulary import Vocabulary from allennlp.common.checks import ConfigurationError logger = logging.getLogger(__name__) class LabelField(Field[torch.Tensor...
allennlp/data/fields/label_field.py
Apache-2.0
4,798
fef5f20539df46b868e215bf05dca727e3a90fa5
Python
py
import sys import torch from os.path import join from args import get_argparser, parse_args, get_aligner, get_bbox if __name__ == '__main__': parser = get_argparser() parser.add_argument('--block_size', help='batch size for regularization; batches are necessary to prevent large vectors from accumulating durin...
inference/_archive/render_regularized.py
MIT
1,418
fef601df096b623bb9fe2ce497201f5eaa321ffc
Python
py
import os import matplotlib.pyplot as plt import matplotlib import numpy as np import torch from PIL import Image matplotlib.use('Agg') def render(data, mode, name, colour_map=None, offset=0, out_dir=""): if isinstance(data, torch.Tensor): if data.is_cuda: data = data.cpu() data = dat...
IIC/utils/segmentation/render.py
MIT
4,559
fef609e3f1a6ea42e4702f5580b0a58826356123
Python
py
import sys import inspect import torch from torch_geometric.utils import scatter_ special_args = [ 'edge_index', 'edge_index_i', 'edge_index_j', 'size', 'size_i', 'size_j' ] __size_error_msg__ = ('All tensors which should get mapped to the same source ' 'or target nodes must be of same size ...
models/conv/message_passing.py
MIT
3,697
dfe115e35b3ee13fbb740c1d991510eb184d9a02
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/text/question_answering/input_transform.py
Apache-2.0
1,601
fef63ccabd69bf636d6ea0c413aba74c6ea85068
Python
py
import os from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F import torchvision.transforms as transforms from torch.utils.data import DataLoader from torchvision.models import densenet121 from wilds.common.data_loaders import get_eval_loader from wilds.datasets.camelyon17_data...
src/models/camelyon.py
MIT
2,514
7c24239f0760e58c951884869b4cdee3d1b594ab
Python
py
import numpy as np import torch import random from model import metric from base.base_trainer import base_trainer from utils import h36m_utils, visualization from utils.logger import Logger class fk_trainer(base_trainer): def __init__(self, model, resume, config, data_loader, test_data_loader): super(fk_...
trainer/trainer.py
BSD-2-Clause
6,074
804c58362514a841984c73a7cb203cfe1c1869a9
Python
py
import logging import os import os.path as osp import sys import time import torch import numpy as np import torch.nn as nn import torch.optim as optim from ray import tune from torch.utils.data import Subset from cords.utils.config_utils import load_config_data from cords.utils.data.data_utils import WeightedSubset fr...
text_train_sl.py
MIT
32,321
fef66a944eb97da63ad4b3bd46600a038c0b2f81
Python
py
import torch import torch.nn as nn import torch.nn.functional as F class ResidualBlock(nn.Module): def __init__(self, inchannel, outchannel, stride=1): super(ResidualBlock, self).__init__() self.left = nn.Sequential( nn.Conv2d(inchannel, outchannel, kernel_size=3, stride=stride,...
nn.py
MIT
2,369
e964e9cfadff2cec35b6b9ec2e264ca2906e722e
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/helpers/reference_metrics.py
Apache-2.0
10,818
fef679e492487f89509949cb6abd3d571618e6d9
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/scripts/training/qq-su_sac.py
DOC,Zlib,BSD-3-Clause
4,364
e9cc5c266db6131282489c4871ca67d6722ea801
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...
nemo/collections/asr/parts/rnnt_beam_decoding.py
Apache-2.0
33,319
24998391372600b5be44595acb8fcfb2a06a51ad
Python
py
# dataloader for KITTI / when training & testing F-Net and MaGNet import os import random import glob import numpy as np import torch import torch.utils.data.distributed from PIL import Image from torch.utils.data import Dataset, DataLoader from torchvision import transforms import pykitti class KittiLoader(object...
data/dataloader_kitti.py
MIT
8,475
e90fd383baf30a43c9c65dd2c49d510af0162236
Python
py
import os import re import sys sys.path.append('.') import cv2 import math import time import scipy import argparse import matplotlib import numpy as np import pylab as plt import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from collections import OrderedDict from sci...
demo/picture_demo.py
MIT
1,844
d7332f0b753589667bf18b78a5d566ff12e25f67
Python
py
""" ****************** COPYRIGHT AND CONFIDENTIALITY INFORMATION ****************** Copyright (c) 2019 [Thomson Licensing] All Rights Reserved This program contains proprietary information which is a trade secret/business \ secret of [Thomson Licensing] and is protected, even if unpublished, under \ applicable Copyrigh...
sodeep_master/utils.py
BSD-3-Clause
3,880
fef6acbefe42eb7c2c21a287c479747eb3cd8469
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 math from typing import Dict, Optional, Tuple import logging import torch import torch.nn.functional as F from fairseq import utils fro...
fairseq/modules/multihead_attention.py
MIT
51,684
4554996089516cf659f896b7914921e4f82442dd
Python
py
import torch from transformers import BertPreTrainedModel, BertModel class BertForMultiLabelSequenceClassification(BertPreTrainedModel): """BERT model for Multilabel classification. This module is composed of the BERT model with a classifier (linear) layer on top of the pooled output. Params: ...
src/model.py
MIT
2,851
52b631efcce4a8770336cb33a111eae5ad6564eb
Python
py
from PIL import Image import numpy as np import matplotlib.pyplot as plt import torch from torchvision import datasets, transforms, models from torch import nn , optim from collections import OrderedDict def process_image(image): ''' Scales, crops, and normalizes a PIL image for a PyTorch model, returns an...
utils.py
MIT
3,264
7c8976e38ab5d192b911752ffac9e33516d08153
Python
py
import argparse import glob import logging import os import time import torch from torch.utils.data import DataLoader from pathlib import Path from transformer_base import BaseTransformer, add_generic_args, setup_trainer, get_linear_schedule_with_warmup from utils import SummarizationDataset logger = logging.getLogg...
examples/summarization/bart/run_bart_sum.py
Apache-2.0
8,237
fef6d6d5e90c6efd674f922ce2906916477c5b7b
Python
py
"""" TextCNN模型训练 """ import os import sys import time import torch from fastNLP import Const from fastNLP.embeddings import BertEmbedding from fastNLP.models import BiLSTMCRF from fastNLP import SpanFPreRecMetric from fastNLP import Trainer from fastNLP import LossInForward from torch.optim import Adam from fastNLP i...
ner/weibo_NER/train_bilstm_crf_bert_embed.py
Apache-2.0
3,247
1e65c755c4e307259c55197aa105acee12c0ff9e
Python
py
import torch import torch.nn as nn import torch.nn.functional as F class ActorNetwork(nn.Module): def __init__(self, input_dims, layer1_dims, layer2_dims, action_dim): super(ActorNetwork, self).__init__() self.fc1 = nn.Linear(input_dims, layer1_dims) self.fc2 = nn.Linear(layer1_dims, layer...
network.py
MIT
1,608
fef7118e34fba83b0a9787bf9d41e5e032672f1d
Python
py
import unittest import torch from torch import nn import sys import kgbench as kg from kgbench import tic, toc class TestLoad(unittest.TestCase): stats = { 'amfull' : { 'num edges' : 5988321, 'num relations' : 133, 'num entities' : 1666764, ...
tests/loadtests.py
MIT
2,637
1e026134dd1c5842a1d4216f13130db88e1e5711
Python
py
import mmcv import numpy as np import pycocotools.mask as mask_util import torch import torch.nn as nn from torch.nn.modules.utils import _pair from mmdet.core import auto_fp16, force_fp32, mask_target from mmdet.ops import ConvModule, build_upsample_layer from mmdet.ops.carafe import CARAFEPack from ..builder import ...
mmdet/models/mask_heads/fcn_mask_head.py
Apache-2.0
8,248
fef7603aba66c9bf78c5a1dabcc4daa6ea940eac
Python
py
################################################# ### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ### ################################################# # file to edit: dev_nb/SparseImageWarp.ipynb import torch import numpy as np def sparse_image_warp(img_tensor, source_control_point_locations, ...
exp.py
Apache-2.0
14,965
fef76a35be1e54fbea9be99f8c3dc0e91be7b922
Python
py
# Defined in Section 4.6.8 import sys import torch from torch import nn, optim from torch.nn import functional as F from torch.nn.utils.rnn import pad_sequence from torch.utils.data import DataLoader, Dataset from tqdm.auto import tqdm from nlptoolkit.data.embeddings.pos_encding import PositionalEncoding from nlptool...
examples/sentence_polarity/transformer_sent_polarity.py
Apache-2.0
4,650
fef776f2a479fa169b887920839cb544c237f4e4
Python
py
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this sof...
train.py
BSD-Source-Code
16,405
d78f9f7649f2816a248e55d6639a7897fefb99bb
Python
py
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 # model file: example-models/misc/irt/irt2.stan import torch import pyro import pyro.distributions as dist def init_vector(name, dims=None): return pyro.sample(name, dist.Normal(torch.zeros(dims), 0.2 * torch.ones(dims)).to_event(...
pyro_models/misc/irt2.py
Apache-2.0
1,592
fef78c6d6534cad2acc151d09a7194669e09ed83
Python
py
import sys sys.path.insert(0, "/home/igor/code/mestrado/REDN/opennre/framework") sys.path.insert(0, "/home/igor/code/mestrado/REDN/opennre/dataset") import torch from ..dataset.utils import is_normal, is_multi_label, is_over_lapping from .data_loader import SentenceREDataset import random import pandas as pd CORRECT...
opennre/framework/f1_metric.py
MIT
9,072
a963484d23b6684cf9f6c6a6a16eee931f3316a0
Python
py
import argparse import sys import os import copy import datetime import socket import cv2 import torchvision from common.utils.yamlConfig import YamlConfig from common.utils.logger import CreateLogger import numpy as np import pprint import torch from fvcore.nn.precise_bn import get_bn_modules, update_bn_stats from ...
azure/run.py
Apache-2.0
4,892
7c1d2e4b3387f6e53867584f5afcdc05bc091a89
Python
py
import torch from torch.utils.data import DataLoader, Dataset import torch.nn as nn import torch.nn.functional as F import torchvision import torchvision.transforms as transforms import torch.optim as optim from warmup_scheduler import GradualWarmupScheduler import math from torch.nn.modules.loss import _WeightedLoss f...
src/utils.py
Apache-2.0
11,962
29f6aa16d9ff667e168e0d404137aa61c7ad3f3c
Python
py
# -*- coding: utf-8 -*- """ Torch version of hyperparams TODO: [ ] - need to extract relavent params from loaders [ ] - need to extract relavent params from datasets [ ] - ensure monitor is handled gracefully [ ] - prevent non-relevant params from being used in the hash CommandLine: python ~/code/...
netharn/hyperparams.py
Apache-2.0
41,870
fef7b35d848c5ae6ca43f38de0997765c39690ec
Python
py
# -*- coding: utf-8 -*- # @Author: Jie Yang # @Date: 2017-10-17 16:47:32 # @Last Modified by: Jie Yang, Contact: jieynlp@gmail.com # @Last Modified time: 2019-02-13 11:49:38 from __future__ import print_function from __future__ import absolute_import import torch import torch.nn as nn import torch.nn.functiona...
model/.ipynb_checkpoints/seqlabel-checkpoint.py
Apache-2.0
5,275
fef7c904b250d642a5cab459ebece245c755536f
Python
py
# help function from transfer_learning import NeuralNet from Functions.dataset_loader import data_loader, get_descriptors, one_filter, data_scaler # modules import torch import torch.nn as nn import torch.optim as optim import os import numpy as np import pandas as pd from sklearn.model_selection import train_test_s...
Batch_runs/batch_run_32.py
MIT
4,550
fef7efed21c01b1307e958a3b4c73aac176078c5
Python
py
# Copyright 2020 trueto # 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 writi...
bertology_sklearn/models/focal_loss.py
Apache-2.0
2,810
f9bba445c749a13203e51bf07761a0343d52ff59
Python
py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def hidden_init(layer): fan_in = layer.weight.data.size()[0] lim = 1. / np.sqrt(fan_in) return (-lim, lim) class Actor(nn.Module): """Actor (Policy) Model.""" def __init__(self, state_size, action_size, seed=0,...
p2_continuous-control/ddpg_model.py
MIT
3,465
fef7f86430641d513caa6017da27ef99e1ca94d3
Python
py
import argparse import math import subprocess import tempfile from pathlib import Path import numpy as np import pretty_midi import soundfile import torch import torch.nn.functional as F from mir_eval.util import midi_to_hz from constants import HOP_SIZE, MIN_MIDI, SAMPLE_RATE from evaluate import extract_notes, save...
hw3/transcribe.py
MIT
3,406
24a2d7d0fd59952b34007e2da0430ae64d63ea92
Python
py
import numpy as np import matplotlib.pyplot as plt import cv2 as cv from sklearn.metrics import f1_score from tqdm import tqdm from PIL import Image from imutils.paths import list_images import torch import torch.nn as nn from torchvision import transforms from torch.utils.data import Dataset import copy, random impo...
pv_vision/defective_cell_detection/model/cnn_train_val.py
BSD-3-Clause
9,538
80329e391d0e98372557b60bcc2187559bd77a51
Python
py
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import os class Linear_QNet(nn.Module): def __init__(self,input_size,hidden_size,output_size): super().__init__() self.linear1 = nn.Linear(input_size,hidden_size).cpu() self.linear2 = nn.Linear(hi...
model.py
MIT
3,190
802313aa63ab185a25dd695c992543d28bb0800d
Python
py
import autograd.numpy as np import tensorflow as tf import torch import pymanopt from examples._tools import ExampleRunner from pymanopt.manifolds import Sphere from pymanopt.optimizers import SteepestDescent SUPPORTED_BACKENDS = ("autograd", "numpy", "pytorch", "tensorflow") def create_cost_and_derivates(manifold...
examples/dominant_eigenvector.py
BSD-3-Clause
2,917
fef814385deadc08a6485ee68437ad3e9e4aa1d0
Python
py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import pickle import numpy as np import torch from torch.utils import data as tds from copy import deepcopy def underdirt(schematic, labels=None, max_shift=0, nothing_id=0): # todo fancier dirt! # FIXME!!!! label as ground where appropriate shift =...
droidlet/perception/craftassist/voxel_models/detection-transformer/datasets/house.py
MIT
13,556
b2fc895b66aae31d0e6b0676ef56a1c52478b2de
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from torchvision import models from torchvision.models.utils import load_state_dict_from_url # Inception weights ported to Pytorch from # http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz FID_WEIGHTS_URL = ('https://github.c...
pytorch_gan_metrics/inception.py
Apache-2.0
12,415
fef82562454e8718a9c5bc9eaed7d108dfee98ea
Python
py
import torch from torch_geometric.nn.conv import MessagePassing from torch_geometric.utils import remove_self_loops, add_self_loops from ..inits import reset def point_pair_features(pos_i, pos_j, norm_i, norm_j): def get_angle(v1, v2): return torch.atan2( torch.cross(v1, v2, dim=1).norm(p=2, ...
torch_geometric/nn/conv/ppf_conv.py
MIT
3,396
fef833f447a07c652f9b0a170d9978ce0c402a8d
Python
py
import torch def get_mask(attention_mask: torch.Tensor, # (b, seq) ng_token_mask: torch.Tensor, # (b, seq, case, seq) ) -> torch.Tensor: # (b, seq, case, seq) extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) # (b, 1, 1, seq) return extended_attention...
src/model/sub/mask.py
MIT
342
fef856039d748fcef87e6370d0cdbcc94e24155b
Python
py
import os import random from skimage import io import torch class DataLoader: def __init__(self, root, phase, batch_size): self.batch_size = batch_size self.dataset_sizes = {'train': 800 * 2, 'val': 200 * 2} self.root = root self.phase = phase self.path = os.path.join(r...
src/data_loader.py
Apache-2.0
5,651
fef85ba25cd1e0ed97fe8bc3ccf6bdb24560ae5d
Python
py
from mylib.dataloader import DataLoader import torch from argparse import ArgumentParser # Arguments parser = ArgumentParser(description='Testing Model') parser.add_argument('--model', type=str, default='models/model_cuda.pkl', help='Path of Previous Trained Model') parser.add_argument('--imgs', type=str, default='d...
evaluation_cuda.py
MIT
1,659
52b96849d9f5b3452876b6f2ad74fb46cc951451
Python
py
#!/usr/bin/env python3 # Copyright 2021, Ludwig Kürzinger, Takaaki Saeki # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Perform CTC Re-Segmentation on japanese dataset. Either start this program as a script or from the interactive python REPL. # Recommended model: # Japanese Transformer Model by Shinj...
scripts/align.py
Apache-2.0
17,049
a9972578a25635e964e0bd2966a6cb22e764c2cd
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from .bounding_box import BoxList from maskrcnn.layers import nms as _box_nms def boxlist_nms(boxlist, nms_thresh, max_proposals=-1, score_field="score"): """ Performs non-maximum suppression on a boxlist, with scores speci...
maskrcnn/structures/boxlist_ops.py
MIT
3,695
fef8e7202b5b06191ddb2f367cee6444eb55b377
Python
py
import copy import json import os from pathlib import Path import pickle import shutil import time import re import fire import numpy as np import torch from google.protobuf import text_format import second.data.kitti_common as kitti import torchplus from second.builder import target_assigner_builder, voxel_builder f...
second/pytorch/train.py
MIT
26,632
fef8e89f531a08d4b5c986bf7b8d715d2bb9c763
Python
py
import torch from torch import nn from ..backbone import * class SegBaseModule(nn.Module): def __init__(self, num_classes=1): super(SegBaseModule, self).__init__() self.num_classes = num_classes def train_backbone(self): self.backbone.train() self.backbone.requires_grad_(True)...
blseg/model/base.py
MIT
4,321
fef903b7d68f34eac65ea0a85b107702e9d5173a
Python
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ TensorRT Object detection. Copyright (c) 2021 Nobuo Tsukamoto This software is released under the MIT License. See the LICENSE file in the project root for more information. """ import argparse import colorsys import os import random import time impo...
python/segmantation/torchvision_segmantation_capture.py
MIT
5,196
a9698c0f31536742cdb0e278b456c88f9d00fbda
Python
py
# Copyright 2019 Ondrej Skopek. # # 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...
mt/mvae/distributions/wrapped_distributions.py
Apache-2.0
1,692
fef94cf7641426286f25604007ddceb57f310a48
Python
py
# This file contains Att2in2, AdaAtt, AdaAttMO, TopDown model # AdaAtt is from Knowing When to Look: Adaptive Attention via A Visual Sentinel for Image Captioning # https://arxiv.org/abs/1612.01887 # AdaAttMO is a modified version with maxout lstm # Att2in is from Self-critical Sequence Training for Image Captioning ...
models/TransformerModel.py
MIT
23,140
fef987e8a15a2b7d87732eaee8a7e2de88264d92
Python
py
from fixtures import * # noqa: F401,F403 from lightning import RpcError from utils import DEVELOPER, wait_for, only_one, sync_blockheight import copy import pytest import random import string import time import unittest def test_pay(node_factory): l1, l2 = node_factory.line_graph(2) inv = l2.rpc.invoice(1...
tests/test_pay.py
MIT
36,771
03db1708633c819ff9cdd7f661f9437c3de5c69e
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from seq2seq import utils from seq2seq.models import Seq2SeqModel, Seq2SeqEncoder, Seq2SeqDecoder from seq2seq.models import register_model, register_model_architecture @register_model('lstm') class LSTMModel(Seq2SeqModel): """ Defines the sequen...
seq2seq/models/lstm.py
MIT
17,558
fef99e39ca9a9233c225516f7633494483e8ee1a
Python
py
import os import torch import torch.utils.data from torchvision import transforms import torch.nn.functional as F from tqdm import tqdm def test(dataloader, model, device, source_target, epoch = 0, tb_writer=None): model = model.eval() with torch.no_grad(): model = model.to(device) target_iter = tqdm(enume...
vlcs-2sources/baseline_test_2sources.py
MIT
1,244
fef9a72b408a5b8927592824343c8181dbe5fbcf
Python
py
import torch import torch.nn as nn import torch.nn.functional as F import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt import numpy as np class ConvNet(nn.Module): def __init__(self): super(ConvNet, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) ...
save_load_17/model.py
Apache-2.0
771
129a125e6a468e4329e98c3d16c7b9864b4b2bb2
Python
py
# -*- coding: utf-8 -*- # @Author : William # @Project : TextGAN-william # @FileName : instructor.py # @Time : Created at 2019-04-25 # @Blog : http://zhiweil.ml/ # @Description : # Copyrights (C) 2018. All Rights Reserved. import numpy as np import os import torch import torch.nn as nn...
instructor/oracle_data/instructor.py
MIT
9,793
70817174fabd852a1febae687220ff75d1502358
Python
py
# Copyright (c) OpenMMLab. All rights reserved. import warnings from typing import Callable, List, Optional, Union import torch from ..dist_utils import master_only from .hook import HOOKS, Hook @HOOKS.register_module() class ProfilerHook(Hook): """Profiler to analyze performance during training. PyTorch P...
mmcv/runner/hooks/profiler.py
Apache-2.0
8,059
fef9adc13927df463c7ad37bc4c2f0b89c90a1f1
Python
py
import os import sys # Append TensorBreeze root directory to sys this_dir = os.path.dirname(os.path.realpath(__file__)) root_dir = os.path.abspath(os.path.join(this_dir, os.pardir)) sys.path.append(root_dir) # import pytest import numpy as np import torch import tensorflow as tf from torchvision import models as tor...
test/test_resnet.py
MIT
1,432
12782092080052a939a20ec7e4c9a66c3388aba6
Python
py
import math import os import pytest import torch from torchvision.io import _HAS_GPU_VIDEO_DECODER, VideoReader try: import av except ImportError: av = None VIDEO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets", "videos") @pytest.mark.skipif(_HAS_GPU_VIDEO_DECODER is False, reason="...
test/test_video_gpu_decoder.py
BSD-3-Clause
3,658
fef9bc6dc9eba9493002ae356d055d6cdbbf8846
Python
py
from fusions.robotics.sensor_fusion import SensorFusionSelfSupervised, roboticsConcat from torchvision import transforms from torch.utils.data.sampler import SubsetRandomSampler from torch.utils.data import DataLoader from datasets.robotics.data_loader import get_data from robotics_utils import set_seeds from training_...
deprecated/dataloaders/deprecated_examples/robotics/unimodal_force-pred.py
MIT
2,732
fef9bcaf155be8d78600ebb11315a5efe7448500
Python
py
import pytorch_lightning as pl import torch from torch import nn as nn from models.mdn import mdn class LitMDN(pl.LightningModule): def __init__(self, in_features, out_features, hidden_size, gaussians, noise_regularization=0.0): super().__init__() self.save_hyperparameters() self.noise_r...
models/mdn/lit_mdn.py
MIT
2,127
d7fa4ed39793178e26c0eb16e34bbe9f44bed3a2
Python
py