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 PIL import Image import numpy as np import torch def to_pil(array): if isinstance(array, torch.Tensor): array = array.cpu().detach() if len(array.shape) > 3 and array.shape[2] != 3: array = array.permute(1, 2, 0).numpy() return Image.fromarray(np.uint8(array * 255)) def to_p...
src/utils.py
MIT
893
24cdd28acd8f79d9c5ac3ad734f4ffaf6f960d7a
Python
py
import json import argparse from konlpy.tag import Mecab import torch from pytorch_pretrained_bert.tokenization import BertTokenizer, whitespace_tokenize from pytorch_pretrained_bert.modeling import BertForQuestionAnswering import run_squad device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') def arg...
question-answering-SQuAD/main.py
MIT
8,569
1eb571756cc48eeaf3c2cf9030e174f54066495c
Python
py
import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import numpy as np import random first_HL = 128 def conv3x3(in_channels, out_channels, stride=1): """3x3 kernel size with padding convolutional layer in ResNet BasicBlock.""" return nn.Conv2d( in_channe...
model/spinalresnet.py
Unlicense,MIT
5,342
4b787b89073a9bf9688527202ba75546efebec66
Python
py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import os import shutil from pathlib import Path from typing import Generator import pytest import torch from _pytest.fixtures import SubRequest from _pytest.monkeypatch import MonkeyPatch import torchgeo.datasets.utils fro...
tests/datasets/test_gid15.py
MIT
2,180
7cc90edd92403fb78d373a8b8b8a202e5c112e5d
Python
py
import torch import argparse from domainbed.lib import misc from domainbed.datasets import PACS from domainbed import hparams_registry from domainbed.lib.fast_data_loader import InfiniteDataLoader, FastDataLoader import os from domainbed import algorithms import torch.nn as nn if torch.cuda.is_available(): device...
domainbed/scripts/get_features_and_logits.py
MIT
3,482
703ec5e40177d501950a2cdf0398621e91221da3
Python
py
# coding=utf-8 """Inference EVA""" import os import torch import torch.nn.functional as F from arguments import get_args from utils import load_checkpoint from tokenization_eva import EVATokenizer import mpu import deepspeed import torch.distributed as dist from model import EVAModel, EVAConfig from fp16 import FP16_...
src/eva_interactive.py
MIT
6,772
fec0a58145d0675e4644858973bc433840943552
Python
py
""" Run transfer learning on FashionProductImages dataset. This will first fine-tune a chosen model from the ImageNet model zoo on classifying the 20 most common product and then in a second pass will fine-tune the network further on the remaining, less common, product classes. """ import os import random import time i...
few_shot_learning/train_transfer.py
MIT
14,468
fec0b5ee72850ab5c55496b5550cefaaba06318b
Python
py
#!/usr/bin/env python 3 # -*- coding: utf-8 -*- # # Copyright (c) 2020 Baidu.com, Inc. All Rights Reserved # """ 模型 Authors: panxu(panxu@baidu.com) Date: 2020/05/18 10:08:00 """ from typing import Any, Dict import torch from torch.nn import Module from .model_outputs import ModelOutputs class Model(Module): ...
easytext/model/model.py
MIT
545
425454f656ec09f27f5186850c04c56a7d5e1a24
Python
py
import torch import torch.nn as nn import numpy as np from cnnseq import utils from cnnseq.utils_models import set_optimizer, flatten_audio from skimage.io import imsave import json import os # Recurrent neural network (many-to-one) class Seq2Seq(nn.Module): def __init__(self, params, device=torch.device('cpu')):...
cnnseq/Seq2Seq.py
MIT
11,288
fec0bce1e5c4eb1b17d4fe3fbf1968c68e03d4c9
Python
py
import logging import six import numpy as np import torch import torch.nn.functional as F from torch.nn.utils.rnn import pack_padded_sequence from torch.nn.utils.rnn import pad_packed_sequence from espnet.nets.e2e_asr_common import get_vgg2l_odim from espnet.nets.pytorch_backend.nets_utils import make_pad_mask from e...
espnet/nets/pytorch_backend/encoders.py
Apache-2.0
11,712
fec0be0d33f071edb8bf37aa21d4e1fbab7b69c7
Python
py
from __future__ import division import torch import random import numpy as np import cv2 def confidence_filter(result, confidence): conf_mask = (result[:,:,4] > confidence).float().unsqueeze(2) result = result*conf_mask return result def confidence_filter_cls(result, confidence): max_score...
detector/yolo/bbox.py
Apache-2.0
3,388
b2d15ac94c5f449da53cdcd6cd237087e8eb7d03
Python
py
# -*- coding: utf-8 -*- """Prediction workflows.""" import itertools as itt import logging from typing import Optional, Tuple, Union import numpy as np import pandas as pd import torch from .base import Model from ..triples import CoreTriplesFactory, TriplesFactory from ..typing import MappedTriples, ScorePack __a...
src/pykeen/models/predict.py
MIT
20,574
fcecaf1bd4bc6f6e21576a84f799b686071f108b
Python
py
import abc import logging import random import numpy as np import torch from torch.autograd import Variable class Algorithm(metaclass=abc.ABCMeta): def __init__(self, module_name, name, seed, details=False): self.logger = logging.getLogger(module_name) self.name = name self.seed = seed ...
src/algorithms/algorithm_utils.py
MIT
2,010
fec0fd6caa8b216ade1b20e117bdd713918fd59b
Python
py
import numpy as np import torch import torch.nn as nn import pdb class BaseBEVBackbone(nn.Module): def __init__(self, model_cfg, input_channels): super().__init__() self.model_cfg = model_cfg if self.model_cfg.get('LAYER_NUMS', None) is not None: assert len(self.model_cfg.LAYE...
pcdet/models/backbones_2d/base_bev_backbone.py
Apache-2.0
4,384
fec13e1b9feabe4f2a9741952e9025cd6a7b25f1
Python
py
import torch import torch.nn as nn class GCN_module(nn.Module): def __init__(self,c,out_c,k=7): super(GCN_module, self).__init__() self.conv_l1 = nn.Conv2d(c, out_c, kernel_size=(k,1), padding =((k-1)//2,0)) self.conv_l2 = nn.Conv2d(out_c, out_c, kernel_size=(1,k), padding =(0,(k-1)//2)) ...
model/GCN/GCN_module.py
MIT
971
7c6374419cb03b7d25fc29c90cc537f35bd8c216
Python
py
import torch.nn as nn import math class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels, retain_activation=True, activation='ReLU'): super(ConvBlock, self).__init__() self.block = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, p...
code/protonet/model.py
MIT
2,327
fec15fe1e3554956795598408e1461a1b345c50b
Python
py
import torch import torch.nn as nn import torch.nn.functional as F import spconv from functools import partial from ..model_utils.resnet_utils import SparseBasicBlock from ...config import cfg from ...utils import common_utils, loss_utils from ...ops.roiaware_pool3d import roiaware_pool3d_utils class UNetHead(nn.Mod...
pcdet/models/rpn/rpn_unet.py
Apache-2.0
23,189
fec18f9633885f57eda8325a0435d63ee93edbfd
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Parameter from einops import repeat, rearrange from quant_noise import quant_noise class Zformer(nn.Module): def __init__( self, input_dim, num_heads, dropout=0.0, scalar=700., ...
zformer_pytorch/zformer_pytorch.py
Apache-2.0
2,492
fdbcee47e544409ad4772b14445f0e845272c7e7
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...
torch_utils/misc.py
MIT
11,872
fec19dc99ceb91dedcbb3f6992028abf41026eb4
Python
py
# options file import time, os, sys, torch, torchvision import torchnet.meter as meter from pathlib import Path from torch.autograd import Variable import torch def init_settings(force_new_model, pretrained_model_path=None): global opt opt = dict() opt["dataroot"] = "../datasets/sysu_mm01" opt["batch_...
src_py/settings.py
Apache-2.0
995
709a220013d8d68202bc6442be87ed9d5e6dd223
Python
py
# pylint: disable=protected-access from typing import List, Optional, Tuple, cast import torch import torch.nn.functional as F from torch import nn from torch.distributions import Normal from torch.nn.utils import spectral_norm from .encoders import EncoderWithAction def _compute_ensemble_variance( observation...
d3rlpy/models/torch/dynamics.py
MIT
8,035
038573122c6c4f2464d3d63194eeccca4988fba2
Python
py
import torch import torch.nn as nn import torchvision.models as models #case1: numlayers =2, dropout=0.2 in lstm; train bn parameters; Adam(with L2 regularization]; xavier initialization class EncoderCNN(nn.Module): def __init__(self, embed_size): super(EncoderCNN, self).__init__() resnet = models....
model_case1.py
MIT
5,062
342c07224e7b9ab416444af5468a95332be71c67
Python
py
import mmcv import torch import torch.nn as nn from ..builder import LOSSES from .utils import weighted_loss @mmcv.jit(derivate=True, coderize=True) @weighted_loss def smooth_l1_loss(pred, target, smooth_l1_s, beta=1.0): """Smooth L1 loss. Args: pred (torch.Tensor): The prediction. target (t...
mmdet/models/losses/smooth_l1_loss.py
Apache-2.0
6,100
fec2126697061b46572ed3fcb20d72dcb004e645
Python
py
import torch import json import os import argparse import copy import torch.optim as optim import torch.nn as nn from torch.utils.data import DataLoader from datetime import datetime from collections import defaultdict from tqdm import tqdm import datasets.edge_imageprovider as image_provider import math import cv2 imp...
CODE/test.py
MIT
10,301
fec22043e39a0ab60e81f1ee7fc03adb33318a41
Python
py
import logging from functools import partial from typing import Dict, Iterable, Optional, Sequence, Union import numpy as np import pandas as pd import torch from anndata import AnnData from scvi import _CONSTANTS from scvi._compat import Literal from scvi._docs import doc_differential_expression from scvi._utils imp...
scvi/model/base/_rnamixin.py
BSD-3-Clause
19,789
fec2259114c6512404f80dba0d9f3d285f707780
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...
nemo/collections/nlp/models/duplex_text_normalization/duplex_decoder.py
Apache-2.0
15,204
03bd60e208d06fbf25cbf852207ff00e87a68bc6
Python
py
import torch import torch.nn as nn import torch.nn.functional as F def weight_init(module): for n, m in module.named_children(): print('initialize: '+n) if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_in', nonlinearity='relu') if m.bias is not None:...
fine/net.py
MIT
14,573
fec249498c6069b4e8b94a4d138bd0a0eb98fae7
Python
py
""" Copyright 2019 The Microsoft DeepSpeed Team """ import os import re import stat import math import torch import warnings import hashlib import torch.distributed as dist from collections import defaultdict, OrderedDict from shutil import copyfile from torch.nn.modules import Module from torch.nn.parameter import P...
deepspeed/runtime/engine.py
MIT
126,051
f99d3effcb5c2625d0eb2450428e13047bebcd51
Python
py
import importlib import numpy as np import time import torch def load_model(script, model, config): module = importlib.import_module(script) Network = getattr(module, model) return Network(config) class AverageMeter(object): def __init__(self): self.reset() def reset(self): self.v...
M2_util_train_test.py
MIT
4,940
fcdf24891d5ffd04762b156481dad669b1f05984
Python
py
from __future__ import absolute_import, division, print_function, unicode_literals import torch from tests import utils class SimpleToModel(torch.nn.Module): def __init__(self, *conversions): super(SimpleToModel, self).__init__() self.conversions = conversions def forward(self, tensor): ...
torch_glow/tests/nodes/to_test.py
Apache-2.0
3,138
fec26d07452b97f599dbb2df6d8594d4e4f006d7
Python
py
#!/usr/bin/env python3 import time import math from datetime import datetime from time import sleep import numpy as np import random import cv2 import os import argparse import torch import sys sys.path.append('./Eval') sys.path.append('./') import matplotlib.pyplot as plt from scipy.spatial.transform import Rotation...
simulation/env_152.py
MIT
5,293
fec26f7d124dc2012d0754c4038883854e9a65b9
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/loggers/test_tensorboard.py
Apache-2.0
11,635
5e82c79463598818c2994579d9eae77b29a498cb
Python
py
import os import sys import traceback import types import torch import torch.nn as nn import torch.optim as optim from diora.net.diora import DioraTreeLSTM from diora.net.diora import DioraMLP from diora.net.diora import DioraMLPShared from diora.logging.configuration import get_logger import transformers import t...
pytorch/diora/net/trainer.py
Apache-2.0
36,137
3455c317e4ffbf7cad030a65fc3e164789fcebbc
Python
py
import copy import importlib import os import os.path import subprocess import sys import time import numpy import ray import torch from torch.utils.tensorboard import SummaryWriter import models import replay_buffer import self_play import shared_storage import trainer class MuZero: """ Main class to manag...
muzero.py
MIT
6,371
fec2b0b10eaf9668204f383d2aa64805dba748f0
Python
py
from abc import ABCMeta, abstractmethod import torch import torch.nn as nn from torch.nn.modules.utils import _pair from mmdet import ops class OBBBaseRoIExtractor(nn.Module, metaclass=ABCMeta): """Base class for RoI extractor. Args: roi_layer (dict): Specify RoI layer type and arguments. o...
mmdet/models/roi_heads/roi_extractors/obb/obb_base_roi_extractor.py
Apache-2.0
2,656
12dd9afae40b8f3bf361bce13020c14d05ee5def
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/strategies/test_ddp_spawn.py
Apache-2.0
2,570
fec2e71ee91af7a543505fe9533c3d61438982ac
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/trainer/distrib_parts.py
Apache-2.0
12,105
10f26d3be0aa5ba3a8d7435785046195ca87b9bf
Python
py
from typing import List, Union # isort:skip from collections import OrderedDict from pathlib import Path import torch import torch.nn as nn import torchvision from catalyst_rl import utils from .core import _take, EncoderSpec RESNET_PARAMS = { "resnet18": { "channels": [64, 64, 128, 256, 512], "...
catalyst_rl/contrib/models/cv/segmentation/encoder/resnet.py
Apache-2.0
3,915
fec2f11b0ee0eb6a595b9049658b831a5704b3b8
Python
py
import os import torch from pytorch_pretrained_bert.modeling import BertModel from torch import nn class BertModule(nn.Module): def __init__(self, bert_model_name, cache_dir="./cache/"): super().__init__() # Create cache directory if not exists if not os.path.exists(cache_dir): ...
superglue/modules/bert_module.py
MIT
1,621
7ca4d2f75abfbb7f6f14b0677381588969580448
Python
py
from copy import deepcopy import numpy as np import torch from ignite.engine import Engine from ignite.engine import Events from ignite.metrics import RunningAverage from ignite.contrib.handlers.tqdm_logger import ProgressBar from mnist_classification.utils import get_grad_norm, get_parameter_norm VERBOSE_SILENT = 0 V...
src/05_cnn/mnist_classification/trainer.py
MIT
6,539
fec307dd3290d84492d13fc7fb06f4a227f03616
Python
py
""" A Gaussian mechanism used in Axiothea to ensure differential privacy. """ from collections import OrderedDict import math import torch import numpy as np from plato.config import Config def gaussian_mechanism(weights, channel_type): """"Apply Gaussian mechanism.""" clipped_weights, clipping_bound = cli...
plato/utils/dp_gaussian.py
Apache-2.0
3,690
f9e1afc9bdf8777bf95de867b8eb2f8f6e5ee6ed
Python
py
import numpy as np import gym import random import torch import cv2 from config import * class Atari(object): """ Wrapper used to simplify interactions with the environment """ def __init__(self, device, save_gif = False): self._env = gym.make('Breakout-ramNoFrameskip-v4') if save_gif...
atari/atari.py
MIT
3,009
29f79ff9d63915612a3689ad6727eec428203ed5
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from omegaconf import II from dataclasses import dataclass, field from fairseq.tasks import FairseqTask from . import register_task from .translation import TranslationTask, TranslationConfig from fairseq.optim.amp_optimizer import AMPOptimizer from f...
fairseq/tasks/translation_with_actor_critic.py
MIT
3,945
7019c63d96d083b3650b2d55e8d30ec60ac11de2
Python
py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class Actor(nn.Module): def __init__(self, state_size, action_size, seed, fc_units=600, fc1_units=300): super(Actor, self).__init__() self.seed = torch.manual_seed(seed) self.fc1 = nn.Linear(state_size,...
BipedalWalker/pretrained/model.py
MIT
1,879
70a894b959656cd3ffeb475cb1d7fb45ec9806ae
Python
py
import torch import numpy as np import matplotlib.pyplot as plt from pathlib import Path from .utils import box_iou def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()): # Precision-recall curve fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) py = np.stack(py, axis=1) if ...
red0orange/object_detection/metrics.py
MIT
14,583
fec35a6ff2883c228022fd9ce314f11234963a4b
Python
py
"""Abstract base class for evaluating models""" from abc import ABC, abstractmethod from datasets import Dataset from transformers.models.auto.auto_factory import _BaseAutoModelClass import transformers.utils.logging as tf_logging from transformers import ( PreTrainedTokenizerBase, AutoTokenizer, AutoConfi...
scandeval/benchmarks/abstract/base.py
MIT
46,034
fec360f5b58126a9710d4879449081368fb51b94
Python
py
# encoding: utf-8 """ @author: l1aoxingyu @contact: sherlockliao01@gmail.com """ import logging import os import torch from torch._six import string_classes from collections import Mapping from project.fastreid.config import configurable from project.fastreid.utils import comm from . import samplers from .common im...
project/fastreid/data/build.py
MIT
6,190
5e11829647ab52073f5f42dfaa54ca34ac800cad
Python
py
# Copyright (c) Meta Platforms, Inc from typing import Optional import flowtorch import torch from flowtorch.bijectors.elementwise import Elementwise from flowtorch.bijectors.ops.affine import Affine as AffineOp class Affine(AffineOp, Elementwise): r""" Elementwise bijector via the affine mapping :math:`\ma...
flowtorch/bijectors/affine.py
MIT
953
42a58bc2ee39ffb8adc9809d5c4cde65f7be786a
Python
py
from __future__ import absolute_import from __future__ import print_function import torch AVAI_SCH = ['single_step', 'multi_step', 'cosine', 'warmup_db', 'warmup_sb'] def warmup_db(ep, stepsize): ep +=1 if ep < stepsize[0]: lr = 1e-4*(ep//5+1) elif ep < stepsize[1]: lr = 1e-3 elif ep...
torchreid/optim/lr_scheduler.py
MIT
4,206
fec393d5fe8bd139d3727684bdcc031b4397bc30
Python
py
import unittest import os import random import torch import apex from torch.autograd import Variable class TestFusedLayerNorm(unittest.TestCase): def setUp(self): # bias and weight are set to 0 and 1 respectively, so no need to copy parameters from cpu module to the gpu one self.module_cpu_ = ape...
tests/L0/run_fused_layer_norm/test_fused_layer_norm.py
BSD-3-Clause
4,138
fec3b764eb1575b4136f7b4068af4150785ecacd
Python
py
import torch import numpy as np from torch.utils.data import DataLoader from torch.utils.data.sampler import SubsetRandomSampler, SequentialSampler import math class Dataloader(): def __init__(self, dataset, batch_size, small=False, shuffle_indices=False): self.batch_size = batch_size self.dataset ...
dataset/dataloader.py
Apache-2.0
1,326
fec3c780c8e8f3c77b280d6329ee2025cb802ae5
Python
py
import torch import torch.nn as nn from models import DiscreteVAE, return_mask_lengths class VAETrainer(object): def __init__(self, args): self.args = args self.clip = args.clip self.device = args.device self.vae = DiscreteVAE(args).to(self.device) params = filter(lambda ...
vae/trainer.py
Apache-2.0
2,368
fec3c7bbbd4972cc5cf1a689b8748f86771e05d5
Python
py
# -*- coding: utf-8 -*- import numpy as np import os import pickle import argparse import time import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torchvision.transforms as trn import torchvision.datasets as dset import torch.nn.functional as F from tqdm import tqdm from models.allconv import...
CIFAR/oe_scratch.py
Apache-2.0
9,585
e94d292965c51ad863406246ef444cac0ca2a8cc
Python
py
# -*- coding: utf-8 -*- # A Survey on Negative Transfer # https://github.com/chamwen/NT-Benchmark import numpy as np import argparse import torch as tr import torch.optim as optim import torch.utils.data as Data import os.path as osp import os from utils import network, loss, utils from utils.loss import CELabelSmooth ...
NT_SSDA/source_train_seed_finetune.py
MIT
6,008
28efc67c5c0b4a76e676ecb37551261ad32236c7
Python
py
import torch from torch import nn, Tensor from torch.nn.modules.utils import _pair from torch.jit.annotations import BroadcastingList2 from torchvision.extension import _assert_has_ops from ._utils import convert_boxes_to_roi_format, check_roi_boxes_shape def roi_pool( input: Tensor, boxes: Tensor, outp...
torchvision/ops/roi_pool.py
BSD-3-Clause
2,392
fec3fe7febe748e7bcd0a182190fec5df58a1b77
Python
py
import time import torch import typing import datetime from fba import logger, metrics, utils from .build import HOOK_REGISTRY, HookBase from fba.utils.vis_utils import draw_segmentation_masks @HOOK_REGISTRY.register_module class TimeLoggerHook(HookBase): def __init__( self, num_ims_per_l...
fba/engine/hooks/stat_logger.py
MIT
8,043
fec40a9ccd1ed1654f9a96a6a6fbf6b24b342b82
Python
py
import os import random import math import torch import numpy as np import torch.optim as optim from typing import List, Optional, Tuple, Any, Dict from torch import nn from scipy.special import softmax from medcat.config_meta_cat import ConfigMetaCAT from medcat.tokenizers.meta_cat_tokenizers import TokenizerWrapperBa...
medcat/utils/meta_cat/ml_utils.py
MIT
10,744
4223b4cbd00722f5302a3fa19fe6f54a71e24ec7
Python
py
import argparse import numpy as np from pathlib import Path import re import matplotlib.pyplot as plt from analyse_result import double_visualize plt.rcParams.update({'font.size': 6}) from adjustText import adjust_text import torch import torch.nn.functional as F from metrics import compute_all_metric...
analyse_rec.py
MIT
2,883
fec43829282548305cd92bbdd7320ba67c8a5012
Python
py
""" Copyright (C) 2019 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ from __future__ import absolute_import from __future__ import division from __future__ import print_function __all__ = ['PacConv2d', 'PacConvTra...
lib/extensions/pacnet/pac.py
MIT
42,415
e622f03e18aee71e0ff4d107e3d577283a46fb0e
Python
py
# Pytorch Tabular # Author: Manu Joseph <manujoseph@gmail.com> # For license information, see LICENSE.TXT """Tabular Model""" from collections import defaultdict from pytorch_lightning.utilities.seed import seed_everything import logging import os from typing import Callable, Dict, Iterable, List, Optional, Tuple, Unio...
pytorch_tabular/tabular_model.py
MIT
35,335
12f9b5f6156f06884b16c2c8cdf199c80bf6c8eb
Python
py
import configs as ori_configs from torch.utils.data import DataLoader, TensorDataset from Model.matching import FT_Match from sklearn.metrics import f1_score, accuracy_score import transformers as trans import _pickle as pk import torch import torch.nn as nn import random from UtilPack.ExpUtil import set_random_seed fr...
BERT_Main.py
MIT
6,577
42834956118bc7c512e89f5bb1e14995d6fba2f0
Python
py
import torch from torch.nn.parameter import Parameter from torch.nn.modules.module import Module import torch.nn as nn import torch.nn.functional as F from pythia.modules.layers import ReLUWithWeightNormFC, LinearTransform class Hard_Output(Module): def __init__(self, l_dim, i_dim, s_dim, inter_dim, vocab_size):...
pythia/modules/hard_output.py
BSD-3-Clause
2,516
fec47a20c5bb3c00aff3f8c1992aef337643a8ba
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 numpy as np import torch import torch.nn.functional as F from fairseq.models import register_model, register_model_architecture from f...
fairseq/models/insertion_transformer.py
MIT
10,278
1296333b5e5ef2cf3bcfb86919da447924520058
Python
py
import os import time import torch import pickle import numpy as np from torch import nn from sklearn import metrics from models.utils import generateBatch, classListToTensor, updateProgress, valueToKey from models.BiLstmCRF.decoder import Decoder from models.BiLstmCRF.encoder import BiLSTMEncoder class Model: de...
src/models/BiLstmCRF/model.py
MIT
16,831
fec4a970ec6ccd0b8c891889ffd694a471f7b66b
Python
py
# -*- coding: utf-8 -*- from functools import lru_cache import numpy as np import torch from torch.utils.data import Dataset from ..utils.misc import pbar class NumpySequenceDataset(Dataset): """Read a sequence of numpy arrays. Arguments: fname (str or Path): Path to a list of paths to Numpy `.npy` f...
nmtpytorch/datasets/numpy_sequence.py
MIT
3,168
fec4ac967f7d6ac018d87e69297096c803add25f
Python
py
import torch import torch.nn.functional as F from typing import Optional from src.dl.utils import one_hot from ..weighted_base_loss import WeightedBaseLoss # This is adapted from: Catalyst package class WeightedSCELoss(WeightedBaseLoss): def __init__( self, alpha: float=0.5, b...
src/dl/losses/criterions/sce.py
MIT
3,374
1edbe561e8e757a72a079ce9034f7feb8fecc838
Python
py
#!/usr/bin/env python # coding: utf-8 import matplotlib.pyplot as plt import numpy as np import time import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms import helper #from network_class import Network # Define a transform to normal...
adaptive_learning_rate_stop.py
MIT
5,146
e97674503b4ab400445ba487a2213303806ae56c
Python
py
import numpy as np import torch.nn as nn from catalyst.contrib import registry @registry.Model class SimpleGenerator(nn.Module): def __init__( self, noise_dim=10, hidden_dim=256, image_resolution=(28, 28), channels=1 ): super().__init__() self.noise_di...
examples/mnist_gan/model.py
Apache-2.0
1,584
fec4b90ca9118d562126a0bedebf56590f074544
Python
py
import sys import skorch import torch.nn as nn import numpy as np import pandas as pd from torch import optim from Optimization import MedRecGRUCover, MedRecGRUCoverTrainer from skopt.space import Real, Integer, Categorical from skopt.utils import use_named_args from skopt import gp_minimize from skopt import load as ...
codes/GRUCoverOptim.py
Apache-2.0
8,619
706dc8be7ed8707c88d26bfe9fb8b9fc0d8c29d1
Python
py
import pytest import torch import treetensor.torch as ttorch from treetensor.utils import replaceable_partial from ..tests import choose_mark_with_existence_check choose_mark = replaceable_partial(choose_mark_with_existence_check, base=ttorch.Size) @pytest.mark.unittest class TestTorchModule: def test_float32(s...
test/torch/test_module.py
Apache-2.0
873
fec4e08c04ab51ec906abf2ff224c8725e2b2a01
Python
py
# Copyright (c) 2018-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. # import torch import numpy as np # PyTorch-backed implementations def qmul(q, r): """ Multiply quaternion(s) q with q...
learning3d/pnlk_utils/quaternion.py
MIT
6,793
fec4e61e3cae3f98ac390a95fec88214999ddea1
Python
py
import argparse import logging import torch import data import pyro import pyro.distributions as dist import pyro.poutine as poutine from pyro.infer.mcmc import NUTS from pyro.infer.mcmc.api import MCMC logging.basicConfig(format='%(message)s', level=logging.INFO) pyro.enable_validation(__debug__) pyro.set_rng_seed(...
examples/eight_schools/mcmc.py
MIT
1,764
45f708b1fc9bff0baecafbd2897a939129f47f60
Python
py
import argparse import os from typing import Dict, Optional, Sequence, Union import pytorch_lightning as pl import torch.nn as nn from loguru import logger from ray.tune.integration.pytorch_lightning import TuneReportCallback from slp.plbind.helpers import EarlyStoppingWithLogs, FixedWandbLogger from slp.util.system i...
slp/plbind/trainer.py
MIT
20,525
fec4f453409ec1a48ff3f5038166770a10445e0b
Python
py
#!/usr/bin/env python3 # Copyright 2020 The Johns Hopkins University (author: Jiatong Shi) import torch import numpy as np import copy import time import librosa from scipy import signal device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def create_src_key_padding_mask(src_len, max_len): bs...
model/utils.py
Apache-2.0
5,357
fec52c2604350d8367a9d6afb7a2aba2523069d6
Python
py
#!/usr/bin/env python3 # encoding: utf-8 import re import torch.nn.functional as F import torch.utils.model_zoo as model_zoo from collections import OrderedDict import torch import torch.nn as nn import math import numpy as np import time import os import sys import torchvision #__all__ = ['DenseNet121','DenseNet169...
model/model.py
MIT
15,651
fec53b83ec7fd5f6934299927d9b62a05930c8f5
Python
py
import random import torch from torch import nn import torch.nn.functional as F import pytorch_lightning as pl import spacetimeformer as stf class LSTM_Encoder(nn.Module): def __init__( self, input_dim: int = 1, hidden_dim: int = 256, n_layers: int = 2, dr...
spacetimeformer/lstm_model/lstm_model.py
MIT
5,393
4b2a4b125ef141e49012a85e6b364a173b4bb4ed
Python
py
import warnings import matplotlib.pyplot as plt import mmcv import numpy as np import torch from mmcv.ops import RoIAlign, RoIPool 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...
mmdet/apis/inference.py
Apache-2.0
7,353
fec570ddab96f961c0cf9c14f4b9dab986ddd7cf
Python
py
from __future__ import absolute_import, division, print_function, unicode_literals import unittest import torch from tests.utils import jitVsGlow class TestExp(unittest.TestCase): def test_exp_basic(self): """Test of the PyTorch exp Node on Glow.""" def test_f(a): b = torch.exp(a) ...
torch_glow/tests/nodes/exp_test.py
Apache-2.0
443
fec57ac086e686810625260719f25e4651ca759c
Python
py
import torch import math import numpy as np def get_rotated_data(raw_data, n_rotations): ''' Computes n-way rotation on the data. ''' x_avg = torch.mean(raw_data[:, 0].float()) y_avg = torch.mean(raw_data[:, 1].float()) x = raw_data[:, 0] - x_avg y = raw_data[:, 1] - y_avg ss = torch...
transforms.py
MIT
2,619
1ed1289d8ca07f544da28b26b0792a2e0b0f11a9
Python
py
import os from PIL import Image import numpy as np import torch from torchvision.io import read_video, write_jpeg from torch.utils.data import Dataset from torchvision import transforms as T __all__ = ('MVTecDataset', 'StcDataset') # URL = 'ftp://guest:GU.205dldo@ftp.softronics.ch/mvtec_anomaly_detection/mvtec_anom...
custom_datasets/loader.py
BSD-3-Clause
9,370
fdef25b8975f0938ac06adebc05e484329e417ff
Python
py
import torch import torch.nn as nn # model class net_Softmax(nn.Module): def __init__(self): super().__init__() self.op = nn.Softmax() def forward(self, input): return self.op(input) _model_ = net_Softmax() # dummy input for onnx generation _dummy_ = torch.randn(1, 2, 3, 3)
res/PyTorchExamples/examples/Softmax/__init__.py
Apache-2.0
313
fec589d468d1d05028198223dc2c8a566c5963ab
Python
py
import torch import torch.utils.data import numpy as np import cv2 import math import os from abc import ABC, abstractmethod try: import face_alignment from face_alignment.detection.sfd import FaceDetector except ImportError: raise ImportError( "Please install face alignment package from " ...
utils/crop_as_in_dataset.py
Apache-2.0
24,725
fec59c4668f5e7dba0139c043c336d94aebedca4
Python
py
# coding=utf-8 # 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 re...
megatron/model/bert_model.py
MIT
7,614
fec5a436624b10765d8ddcad793f353c4f82032f
Python
py
from .reduced_basis import SVDBasis import h5py import numpy as np from pathlib import Path import json import functools from tqdm import tqdm from pycbc.waveform import (get_td_waveform, get_fd_waveform, get_waveform_filter_length_in_time) from pycbc.types.frequencyseries import FrequencyS...
lfigw/waveform_generator.py
MIT
78,308
b25b65355f72a51bba600cf488e07c50895adc2e
Python
py
import math import torch import torch.nn.functional as F from torch import nn from .inference import make_retinanet_postprocessor from .loss import make_retinanet_loss_evaluator from ..anchor_generator import make_anchor_generator_retinanet from fcos_core.modeling.box_coder import BoxCoder class Retina...
fcos_core/modeling/rpn/retinanet/retinanet.py
BSD-2-Clause
5,444
fec5b4ca980f996076ca08cb77a12efff1be44b0
Python
py
"""Common training loop parts.""" import copy import logging import pathlib from typing import Any, Generic, Iterable, List, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union import torch from torch import nn from torch.optim import Optimizer from kgm.utils.common import NonFiniteLossError, get_value_from_nest...
src/kgm/training/base.py
MIT
14,748
b2b94e1d4590fb9768de861f449189293d8b5513
Python
py
import argparse import pandas as pd import torch from torch.autograd import Variable from torch.utils.data import DataLoader, Dataset, ConcatDataset import os import json import resource import sys import pickle sys.path.insert(1, 'src') from model import Model from utils import * from data import * from time import ...
train_baseline.py
Apache-2.0
8,338
4213bbb75e53a62bed9cb002658323a70df1b32a
Python
py
import math from torch import nn from quati.modules.positional_encoding import PositionalEncoding class PositionalEmbedding(nn.Module): """Implements an Embedding Layer with absolute Positional Encoding. Args: vocab_size (int): vocabulary size size (int): embeddings size max_seq_len...
quati/modules/positional_embedding.py
MIT
1,002
5e46203b204796b678388b1d884fd9ddd7041b9f
Python
py
# Copyright (c) 2020 Graphcore Ltd. All rights reserved. import numpy as np import operator import popart import pytest import torch import itertools from op_tester import op_tester # `import test_util` requires adding to sys.path import sys from pathlib import Path sys.path.append(str(Path(__file__).resolve().parent....
tests/integration/operators_test/shapeddropout_test.py
MIT
10,560
7cfeee514266b3050c1f49f45e7fffc5f711a526
Python
py
#!/usr/bin/env python3 import os import models import decoder from train_test import train, validate import create_dataloader import tqdm import argparse import logging from collections import OrderedDict import warnings warnings.filterwarnings("ignore") import numpy as np import torch import torch.nn as nn import to...
shivam_machine/run.py
MIT
6,465
10f2d1fd5417e39902539fc295165cfc05e899fa
Python
py
import torch import torch.nn as nn from torch.autograd import Variable nllloss = nn.NLLLoss() def losses_joint(out, labels: torch._C._TensorBase, time_steps: int): """ Defines loss :param out: output from the network :param labels: Ground truth labels :param time_steps: Length of the program :...
src/Models/loss.py
MIT
505
24e10131d166ec426710b0ba789ab1bd63cd2477
Python
py
import os import pickle import os import pickle import argparse import time import subprocess import torch from torch.autograd import Variable import numpy as np from utils import DataLoader from helper import getCoef, sample_gaussian_2d, get_mean_error, get_final_error from helper import * from grid import getSeque...
gym_collision_avoidance/envs/policies/social_lstm/test.py
MIT
26,093
d7f2ded36aa4c48c07c9ce21389e4443831f359e
Python
py
# torch imports import torch.nn.functional as F import torch.nn as nn class BinaryClassifier(nn.Module): """ Define a neural network that performs binary classification. The network should accept your number of features as input, and produce a single sigmoid value, that can be rounded to a label: 0 or ...
source_pytorch/model.py
MIT
1,717
f9a88371a3e05d98a9e027de30dbf57919d759e1
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # Set up custom environment before nearly anything else is imported # NOTE: this should be the first import (no not reorder) from maskrcnn_benchmark.utils.env import \ setup_environment # noqa F401 isort:skip import argparse import os import ...
tools/test_net.py
MIT
10,947
24c606a82ffc049b6c5adbbbbdb352264616a3ff
Python
py
from typing import Any, Union import torch from torch.nn import CrossEntropyLoss from saifooler.attacks.attack import SaifoolerAttack from saifooler.viewers.viewer import Viewer3D class FGSMOptimizer(torch.optim.Optimizer): def __init__(self, params, epsilon): if epsilon < 0.: raise ValueE...
saifooler/attacks/fgsm_attack.py
MIT
1,364
fec67152ff341364d70e2fb500a0a191c17964d7
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 argparse import tempfile import unittest import tests.utils as test_utils import torch from fairseq import search from fairseq.data.di...
tests/test_sequence_generator.py
MIT
22,827
429d1801f3074be75d8fd86e91fe46d9d457fdae
Python
py
import os from typing import List, Tuple from tqdm import tqdm import torch from torch.autograd import Variable from DA2Lite.trainer.common import TrainerBase from DA2Lite.core.log import get_logger logger = get_logger(__name__) class Classification(TrainerBase): def __init__(self, cfg_util, ...
DA2Lite/trainer/classification.py
MIT
4,809
1041e81d01df3c97d45d47b70e28502980fc8cca
Python
py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, 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 cop...
examples/run_squad.py
Apache-2.0
24,672
ff7ae1afa82f0e4322daf0280f24a59d657d1b06
Python
py
from __future__ import print_function import torch import torch.utils.data as data import torchvision import torchnet as tnt import torchvision.datasets as datasets import torchvision.transforms as transforms # from Places205 import Places205 import numpy as np import random from torch.utils.data.dataloader import defa...
data/rotationloader.py
Apache-2.0
7,834
fec6b42a2335555e53317d54972b37c18f5e6e6f
Python
py
# -*- coding:utf-8 -*- import argparse import string import csv import os import pandas as pd import cv2 import torch import torch.backends.cudnn as cudnn import torch.utils.data import torch.nn.functional as F from utils import CTCLabelConverter, AttnLabelConverter from dataset import RawDataset, AlignCo...
deep-text-recognition-benchmark/recognize.py
MIT
18,671
fec6dec7452412c289b4b4a2b54541b3b5e7a19e
Python
py