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 |
|---|---|---|---|---|---|---|---|
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Transformer speech recognition model (pytorch)."""
from argparse import Namespace
from distutils.util import strtobool
import logging
import math
import torch
from espnet.nets.asr_interface import ASRInterface
from espne... | espnet/nets/pytorch_backend/e2e_asr_transformer.py | Apache-2.0 | 19,181 | fece95561f0e24717a14e648dffcf3cf1bafcce6 | Python | py | |
from torchf1 import info_str, profile_macs, profile_flops
import torchvision.models as models
import torch
if __name__ == '__main__':
alexnet = models.alexnet()
# tree based ; similar to print (model)
info_str(alexnet, 1, (3, 224, 224))
# flat; similar to torchsummary
info_str(alexnet, 2, (3, 224,... | examples/demo_info.py | MIT | 620 | 7044734e3151830ef9aaea80efdd3e3444ed2586 | Python | py | |
from model import common
import torch.nn as nn
class Discriminator(nn.Module):
'''
output is not normalized
'''
def __init__(self, args):
super(Discriminator, self).__init__()
in_channels = args.n_colors
out_channels = 64
depth = 7
def _block(_in_channels,... | src/loss/discriminator.py | MIT | 1,595 | 4581dfeb1a5539daddf03419cff527a20bebe7a0 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import pdb
class QNetwork(nn.Module):
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed, fc1_units=64, fc2_units=64):
"""Initialize parameters and build model.
Params
======
state_... | vanilla_DoubleDQN/model.py | Python-2.0,OLDAP-2.7 | 2,966 | 422fc209a2cae1838db6dcd24cb5a9c3bf00b23e | Python | py | |
import argparse
import time
import math
import numpy as np
import torch
import torch.nn as nn
import data
import model
from utils import batchify, get_batch, repackage_hidden
parser = argparse.ArgumentParser(description='PyTorch PennTreeBank RNN/LSTM Language Model')
parser.add_argument('--data', type=str, default='... | main.py | BSD-3-Clause | 13,074 | a94321e0a1e1ce078ae74382f0fec1cbeeb0e951 | Python | py | |
#In Token Mixing I used traditional transpose but in Channel mixing i tried Rearrange from "Einops" library
#Einops Rearrange Docs: https://einops.rocks/1-einops-basics/
#Token Mixing: Rearrange('b h w c -> h (b w) c')
#Channel Mixing: Rearrange('b c h w -> b (h w) c')
import torch
import torch.nn as nn
from einops.l... | MLPMixer/mlpmixer.py | MIT | 10,303 | 7ca0064dc5b31505def9222bff9e11f105134903 | Python | py | |
import sys
sys.path.append('/home/tonne/code/TrafficSignDetection/data/thirdparty/efficientdet-pytorch/')
from typing import Optional, Dict, List
import torch
import numpy as np
import cv2
import matplotlib.pyplot as plt
from model.efficientdet import EfficientDetTrain
from dataset.dataset import get_train_transforms,... | test.py | MIT | 5,174 | feced696cc6c4ec8055f6bf4293162bfd07db863 | Python | py | |
import os
import argparse
import math
import torch
import torchvision
from torch.utils.tensorboard import SummaryWriter
from torchvision.transforms import ToTensor, Compose, Normalize
from tqdm import tqdm
from model import *
from utils import setup_seed
if __name__ == '__main__':
parser = argparse.ArgumentParser... | mae_pretrain.py | MIT | 3,582 | feced75a06efeae9b30aa029257038992457fd46 | Python | py | |
import torch
from model.PredRNN.PredRNN import PredRNN
from model.PredRNN.SpatiotemporalLSTM import SpatiotemporalLSTM
def test_ST_LSTM():
lstm = SpatiotemporalLSTM(in_channels=1, hidden_channels=64, kernel_size=3).cuda()
x = torch.ones(2, 1, 128, 128).cuda()
h = torch.ones(2, 64, 128, 128).cuda()
c ... | src/model/RainNet/PredRNN_test.py | Apache-2.0 | 742 | f9afd8d019422083ab76aef86b4b3ec6ab1233ff | Python | py | |
# coding=utf-8
# Copyright 2020 The SqueezeBert authors and The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... | src/transformers/models/squeezebert/modeling_squeezebert.py | Apache-2.0 | 43,415 | 455bc4881d450a040c4a40957ef277ed1c202e52 | Python | py | |
"""
Definition of custom layers for the ESIM model.
"""
# Aurelien Coet, 2018.
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.activation import MultiheadAttention
from vaa.utils import sort_by_seq_lens, masked_softmax, weighted_sum, normal_softmax
# Class wi... | vaa/droped/layers.py | MIT | 21,520 | fecef0bdb7720f607594bf6bd7a9f19af367ae08 | 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... | simpletransformers/classification/classification_utils.py | Apache-2.0 | 23,783 | fecef8a781ca3a2aabf21fa80e78b05bb7ad9f6e | Python | py | |
import copy
import logging
import torch
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import (ConvModule, build_activation_layer, constant_init,
normal_init)
from torch.nn.modules.batchnorm import _BatchNorm
from ..registry import BACKBONES
from .base_backbone import Ba... | mmpose/models/backbones/shufflenet_v1.py | Apache-2.0 | 11,907 | 108344aa5ea64976282146fba814d0912c2c1a30 | 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... | futureWork/bertConstitution/pybert/model/albert/modeling_bert.py | MIT | 59,643 | fecf1e4de87fca0ec72e837a2bb92942ca3beff0 | Python | py | |
# ==============================================================================
# Copyright 2019 Florent Mahoudeau. 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
#
# ... | mictnet/models/mictresnet.py | Apache-2.0 | 12,905 | fecf2bdb1d00f384fe631aa47bc69fcf963413f2 | Python | py | |
import copy
import json
import os
import torch
from datasets import DatasetDict
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from transformers import AutoTokenizer
from utils.processor import get_default_processor
class Constructor(object):
def __init__(self, args):
sel... | seq2seq_construction/multi_woz_22_response.py | Apache-2.0 | 16,070 | fecf3e19675e6ea0ebee9fb59c1479eed8314975 | Python | py | |
from collections import defaultdict
import cv2
import json
import logging
import numpy as np
import os
import pathlib
from PIL import Image,ImageFile
import torch
from torch.utils.data import Dataset
from ssd.structures.container import Container
class MammalDataset(Dataset):
class_names = ('__background__','ma... | ssd/data/datasets/mammal_dataset.py | MIT | 6,180 | ff30fdece0f82c4deaedfa4f49a286ebf3661498 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class Network(nn.Module):
'''DQN Network.
Attribute:
fc1: the first fully connected layer
fc2: the second fully connected layer
output_layer: the output layer
Arg:
input_di... | value-based/DQN/models.py | MIT | 1,700 | 70068f2c10f18d3fa0f0d45d3417c0dd5e4915ef | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import math
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import checkpoint_utils... | fairseq/models/fconv_self_att.py | MIT | 24,180 | ffb36fbf146b42b56b7b5aa65fd5ca4463330834 | Python | py | |
"""Abstract base classes for RL algorithms."""
import io
import pathlib
import time
from abc import ABC, abstractmethod
from collections import deque
from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, Union
import gym
import numpy as np
import torch as th
from stable_baselines3.common import utils
... | stable_baselines3/common/base_class.py | MIT | 35,272 | 10fe7af275dbfb3d629aedef018dc2a44004b8df | Python | py | |
from ..torch_core import *
from ..basic_data import DataBunch
from ..callback import *
from ..basic_train import Learner,LearnerCallback
from torch.utils.data.sampler import WeightedRandomSampler
__all__ = ['UnderSamplingCallback']
class UnderSamplingCallback(LearnerCallback):
def __init__(self,learn:Learner,weig... | fastai/callbacks/undersampling.py | Apache-2.0 | 1,191 | 28e37f812abb55102d777c839b8594d318da5c51 | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from il_offline_rl.utils import AddBias
# TODO: In order to make this code faster:
# 1) Implement _extract_patches as a single cuda kernel
# 2) Compute QR decomposition in a separate process
# 3) Actually make ... | il_offline_rl/algo/kfac.py | MIT | 7,713 | fecf86942ca09d3b8bbe21e95cb453893f8b4c61 | Python | py | |
""" BigGAN: The Authorized Unofficial PyTorch release
Code by A. Brock and A. Andonian
This code is an unofficial reimplementation of
"Large-Scale GAN Training for High Fidelity Natural Image Synthesis,"
by A. Brock, J. Donahue, and K. Simonyan (arXiv 1809.11096).
Let's go.
"""
import torch
impo... | load_and_test.py | MIT | 5,323 | 708405cc27450ace78a74d73e16ec5a0aabcd43e | Python | py | |
import torch
import math
import torch.nn as nn
class Identity(torch.nn.Module):
def forward(self, input):
return input
class SegmentConsensus(torch.autograd.Function):
def __init__(self, consensus_type, dim=1):
self.consensus_type = consensus_type
self.dim = dim
self.shape = ... | ops/basic_ops.py | BSD-2-Clause | 1,965 | fecfb70afc9a6d6d44c8da70a567c2447c143c86 | Python | py | |
"""
Train Async-VFL on ModelNet-10 dataset
"""
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
from torch.autograd import Variable
import torchvision.transforms as transforms
import argparse
import numpy as np
import time
import os
import copy
import ra... | vafl.py | MIT | 12,924 | fecfcc99a179e70f417575a7c41786a2ff21686e | Python | py | |
import copy
import torch
class Callback:
def __init__(self):
self._iteration = 0
self._in_training = True
@property
def in_training(self):
return self._in_training
def on_epoch_begin(self):
pass
def on_epoch_end(self, metric=None):
self._iteration += 1
... | inclearn/lib/callbacks.py | MIT | 1,949 | 703d13fff6db4257a28a43ae87982c0490952f8a | Python | py | |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: RainbowSecret
## Microsoft Research
## yuyua@microsoft.com
## Copyright (c) 2018
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in the root directory of this source tree
##+++... | lib/models/nets/base_ocnet.py | Apache-2.0 | 2,372 | 701e6a2bc1e030eec77e7e358fbd31827b0ea0c4 | Python | py | |
"""
This class is used for defining the scoring function(s) which can be used during
fine-tuning.
"""
# load general packages and functions
from collections import namedtuple
import torch
from rdkit import DataStructs
from rdkit.Chem import QED, AllChem
import numpy as np
import sklearn
from sklearn import svm
class S... | graphinvent/ScoringFunction.py | MIT | 7,329 | fecfff2c9fbb67cd41110ba07cb59a03f2dcc444 | Python | py | |
"""prepare CIFAR and SVHN
"""
from __future__ import print_function
import torch
import torchvision
import torchvision.transforms as transforms
import numpy as np
crop_size = 32
padding = 4
def prepare_train_data(dataset='cifar10', datadir='/home/yf22/dataset', batch_size=128,
shuffle=True,... | cpt_cifar/modules/data.py | MIT | 4,333 | fed0241d9a5968ed89a45dfa89a6b9fb1266d7c3 | Python | py | |
#################################
#本文件用于存储archs中调试好的结构代码,用于简化archs代码长度
#当需要使用相关结构模型时
#################################
import torch
from torch import nn
######the header file from CRDN.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
from torch.nn import *
#UNetRNNC... | archs_backup.py | MIT | 80,642 | 03bd8c822c649770c463c9d9515b539e391ed76d | Python | py | |
# copy from DepthHints (https://arxiv.org/pdf/1909.09051.pdf), please follow their license.
""" Script to precompute depth hints using the 'fused SGM' method """
from __future__ import absolute_import, division, print_function
import os
import random
import numpy as np
import copy
from PIL import Image # using pill... | precompute_depth_hints.py | MIT | 10,143 | ff98fcd9325b48e862b7bd2545beadf23af8d372 | Python | py | |
import logging
from typing import Sequence, Optional
import torch
import torch.nn as nn
from mmcv.runner import load_checkpoint
__all__ = ['filter_by_out_idices', 'BaseBackbone', 'ClassifierPretrainWrapper']
def filter_by_out_idices(forward_func):
def _filter_func(self, x):
outputs = forward_func(self, ... | mmdet/models/backbones/base_backbone.py | Apache-2.0 | 1,773 | 6b1216fb40c40ed1a6e02f7e3f6a44ec3c65452f | Python | py | |
#!/usr/bin/env python3
# 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 collections
import unittest
import torch
import torchvision.models
from classy_vision.generic.util import get_t... | test/models_resnext_test.py | MIT | 9,465 | e9af51417d2a7aa69ff625f2df3ca4de8370779b | Python | py | |
# source: https://github.com/adambielski/siamese-triplet/blob/master/losses.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class ContrastiveLoss(nn.Module):
"""
Contrastive loss
Takes embeddings of two samples and a target label == 1 if samples are from the same c... | netharn/criterions/losses.py | Apache-2.0 | 3,911 | fed06dc896e54b1a10d15a2bee8d0da7c85d544c | Python | py | |
# global
torch_scatter = None
import torch
from typing import Tuple, Union
# Array API Standard #
# -------------------#
def min(x: torch.Tensor,
axis: Union[int, Tuple[int]] = None,
keepdims: bool = False) \
-> torch.Tensor:
if axis == (): return x
if not keepdims and not axis and ax... | ivy/functional/backends/torch/statistical.py | Apache-2.0 | 747 | 7c6d9e68ae0fd59825b382218d285ceee751a3e6 | Python | py | |
import torch
from torch import nn
from torch.nn import Parameter
jit_scripts = {}
class StochasticModule(torch.nn.Module):
def __init__(self, *args, **kwargs):
super(StochasticModule, self).__init__(*args, **kwargs)
class BDropout(StochasticModule):
"""
Extends the base Dropout layer by ad... | prob_mbrl/models/modules.py | MIT | 12,400 | fed097a2ef9f6f01a54c0ffd153f1f6c674cd8b2 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
from mmdet.core import (auto_fp16, build_bbox_coder, force_fp32, multi_apply,
multiclass_arb_nms, get_bbox_dim, bbox2type)
from mmdet.models.builder import HEADS, build_loss
from mmdet.mo... | mmdet/models/roi_heads/bbox_heads/obb/obbox_head.py | Apache-2.0 | 14,630 | fed0a432737f769afad24ae7d820202150aa989a | Python | py | |
import torch
import torch.nn as nn
#from torch.utils.checkpoint import checkpoint
class Conv2D(nn.Module):
def __init__(self, in_channels:int, out_channels:int, ksize:int, stride:int=1, padding:int=-1, bn:bool=True, bias:bool=True):
"""Constructor
Args:
in_channels (int): Number of inp... | IRN/network/layers/conv2d.py | Apache-2.0 | 1,533 | 5e13f11bd5c4fb29bae7733b148cede228031fde | Python | py | |
import torch
import os
import glob
from torch.utils.data import Dataset
import numpy as np
import scipy.stats as scipy_stats
import numpy.matlib
from PIL import Image
from torchvision import transforms
from xmuda.data.utils.preprocess import create_img_grid, create_voxel_grid, select_points_in_frustum, compute_local_fr... | xmuda/data/NYU/nyu_dataset.py | Apache-2.0 | 23,450 | 8052f7eb46d814278619fef18b177c97a688de23 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torch.nn.functional as F
from torch import nn
class FPN(nn.Module):
"""
Module that adds FPN on top of a list of feature maps.
The feature maps are currently supposed to be in increasing depth
order, and must b... | maskrcnn_benchmark/modeling/backbone/fpn.py | MIT | 4,706 | 4ba37d31a5bd9654f9eeda134c50507db7a15f5c | Python | py | |
from modules.cnn_encoder_block import CnnEncoderBlock
import torch
import torch.nn as nn
class Encoder(nn.Module):
def __init__(self, latent_size: int):
super().__init__()
self.__sequential_blocks = [
CnnEncoderBlock(3, 64),
CnnEncoderBlock(64, 128),
... | src/architecture/encoder/svhn_encoder.py | MIT | 768 | fd6cdda7a109162382ca883000aa7893256dca9b | Python | py | |
import sys
import os
import numpy as np
import argparse
import logging
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import itertools
import collections
import torch
import torch.nn as nn
from torch.nn.functional import interpolate
from torchvision import transforms, datasets, models, u... | utils/commons.py | MIT | 28,823 | 7cef4637354544d88f0d9d29827fa8ec9dbfa5e3 | Python | py | |
# pylint: disable=not-callable
# pylint: disable=no-member
import sys
import time
import pathlib
import argparse
import numpy as np
import torch
from gym.wrappers.monitoring.video_recorder import VideoRecorder
sys.path.append(str(pathlib.Path(__file__).parent.parent))
from pmbrl.envs import GymEnv
from pmbrl.traini... | scripts/train.py | MIT | 4,261 | 28d32af3686ddd30ac9312b9c2bc92de72caba54 | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
import torch
class Encoder(nn.Module):
def __init__(self, in_size, out_size, num_layers, dropout=0.3, bi=True):
super(Encoder, self).__init__()
self.in_size = in_size
self.out_size = out_size
self.lstm = nn.LSTM(in_size, out_siz... | Model/G2E/seq2seq/Layers/Encoder.py | MIT | 481 | fed1221f20a9bec305ba133319fb400a620961f9 | Python | py | |
# TODO! set the loss to the exact same one that I eventually settle on
from datasets import DatasetEvalSeq, BboxEncoder # (this needs to be imported before torch, because cv2 needs to be imported before torch for some reason)
from retinanet import RetinaNet
from utils import onehot_embed
import torch
import torch.ut... | eval_retinanet_val_seq.py | MIT | 9,026 | 65267ebfe8c8687b3d83fd94acb574dc28803220 | Python | py | |
"""
Copyright (c) 2019-2020 Intel Corporation
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 w... | examples/torch/object_detection/main.py | Apache-2.0 | 22,332 | fed136bdcb18076f909f83214a8e8380286947e6 | Python | py | |
import inspect
from argparse import ArgumentParser
import torch
from torch import nn
from lasaft.source_separation.conditioned.LaSAFT import TFC_LaSAFT, TFC_LightSAFT
from lasaft.source_separation.conditioned.cunet.dcun_gpocm import DenseCUNet_GPoCM, DenseCUNet_GPoCM_Framework
from lasaft.source_separation.conditione... | lasaft/source_separation/conditioned/cunet/models/dcun_tfc_gpocm_lightsaft.py | MIT | 6,859 | a93daacc16e4832a8a5d17de6c1105b0b3cbb984 | 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/connectors/debugging_connector.py | Apache-2.0 | 4,026 | 429e9638420276729cfa609a8ca8ae37fc46d0fd | Python | py | |
import torch
import pandas as pd
import numpy as np
from torch.utils.data import Dataset, DataLoader
from sklearn.model_selection import train_test_split
from deepfm import DeepFM
torch.manual_seed(2022)
data = pd.read_csv('./temp_data.csv').reset_index(drop=True)
category_cols = ['CODE_GENDER', 'FLAG_OWN_CAR', 'FLA... | main.py | MIT | 2,920 | 03eb69118d4b94f9a0e2f97a2953a6accdfb7dbd | Python | py | |
import logging
import os
import shutil
import sys
import time
import numpy as np
import torch
import torch.nn as nn
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.avg = 0
self.sum = 0
self.cnt = 0
def update(self, val, n=1):
se... | tools/utils.py | Apache-2.0 | 5,645 | 45fd63c02aca8edcf7eb776f29e626d4838c404c | Python | py | |
"""
Based on original code sourced from Cloudera's Fast Forward Labs (https://qa.fastforwardlabs.com/)
Authors: Melanie R. Beck, PhD; Andrew Reed
Accessed: May 2021
Availability: https://qa.fastforwardlabs.com/pytorch/hugging%20face/wikipedia/bert/transformers/2020/05/19/Getting_Started_with_QA.html,
https://qa.fastfor... | gamechangerml/src/search/QA/QAReader.py | MIT | 13,424 | 1e591f54dd5fbaa71ccf7029e318a4e104137803 | Python | py | |
import torch
from torch import nn
from torch.nn import functional as F
import torchvision
def main():
print('cuda device count: ', torch.cuda.device_count())
net = torchvision.models.googlenet(pretrained=True)
#net.fc = nn.Linear(512, 2)
net = net.eval()
net = net.to('cuda:0')
print(net)
tm... | googlenet/googlenet.py | MIT | 499 | 5f5c037a35d3680f87d83dfdcbdca11ddd609bce | Python | py | |
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... | nnunet/inference/predict.py | Apache-2.0 | 44,721 | 24e21196a583dcd8b627fffa47e30b55c1cbcdc2 | Python | py | |
import torch
from torch_audiomentations.utils.fft import rfft, irfft
_NEXT_FAST_LEN = {}
def next_fast_len(size):
"""
Returns the next largest number ``n >= size`` whose prime factors are all
2, 3, or 5. These sizes are efficient for fast fourier transforms.
Equivalent to :func:`scipy.fftpack.next_f... | torch_audiomentations/utils/convolution.py | MIT | 2,809 | fed1e293c19b1759fbd8f261ce62d6c706de5aa8 | Python | py | |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 4 19:50:21 2019
@author: yuguangyang
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
#create a fully connected layer from m to n units
n_feature = 3
n_out = 5
layer = nn.Linear(n_feature, n_out)
# we can use layer.weight to see the weight parame... | tutorial-contents/107_TorchBasic_nnoverview.py | MIT | 961 | fed2030096d71055a1b87a8f8e4338b57a41b075 | Python | py | |
import torch
import torch.nn as nn
from Sublayers import FeedForward, MultiHeadAttention, Norm
class EncoderLayer(nn.Module):
def __init__(self, d_model, heads, dropout=0.1):
super().__init__()
self.norm_1 = Norm(d_model)
self.norm_2 = Norm(d_model)
self.attn = MultiHeadAttention(h... | services/wikihow-bert/Layers.py | Apache-2.0 | 1,730 | 345806b1b65d1e8175e6f47fd437942ab68d1492 | Python | py | |
import matplotlib.pyplot as plt
import torch
from torch import nn, optim
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
import torch.nn.functional as F
import pandas
import random
import time
import argparse
import collections
from torch.nn.utils.rnn import PackedSequence
from ... | script/utils.py | MIT | 57,644 | 1027fe9d36758bb8799b2885cd73f1f10360f999 | Python | py | |
from collections import OrderedDict
import torch.nn as nn
class VGGa(nn.Module):
def __init__(self, n_channels, n_classes, conv_params):
super().__init__()
conv_blocks = OrderedDict()
for i in range(len(conv_params)):
out_channels, pool_size, order = conv_params[i]
... | mtl/system/models/vgg.py | 0BSD | 2,392 | 10c2426eaa3668ff7d033bdbb9500e7e6e3b043a | Python | py | |
# dataloader add 3.0 scale
# dataloader add filer text
import numpy as np
from PIL import Image
from torch.utils import data
import util
import cv2
import random
import torchvision.transforms as transforms
import torch
import pyclipper
import Polygon as plg
import os
cur_path = os.path.abspath(os.path.dirname(__file__... | dataset/ctw1500_test_loader.py | Apache-2.0 | 2,073 | 129bb0d63a2919df77053e099fa53d75aae50249 | Python | py | |
import torch
from utils.base_model import BaseModel
import torch.nn as nn
import torch.nn.functional as F
from pathlib import Path
from models.operations import *
from models.decoding_formulas import Decoder
import pdb
from operations import *
def find_nn(sim, ratio_thresh, distance_thresh):
sim_nn, ind_nn = sim... | models/matcher.py | MIT | 13,985 | b2cdbe291191fc5ee29977c1d20c7787002daf48 | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Adversarial attacks with Foolbox 3.0.
Implementing adversarial attacks with constrainted distances with
newest version of Foolbox: 3.0. (Still testing if viable.)
Todo:
* L2DeepFoolAttack and L2CarliniWagnerAttack have not been
successfully constrained. Still wo... | adversarial_attack/future/foolbox3_test.py | MIT | 4,394 | fed28cf4127f12ca905942f30518150fb536762d | Python | py | |
import os
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
class FaceDataset(Dataset):
def __init__(self, filepath_list, transform=None):
self.images = []
self.labels = []
for filepath in filepath_list:
basename = os.path.basename(filepath... | data.py | MIT | 957 | fed2a2f57d1715afbff41aa1accd53d9f5b0a859 | Python | py | |
import argparse
import os, sys
import os.path as osp
import torchvision
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import transforms
from torch.utils.data import DataLoader
import random, pdb, math, copy
from tqdm import tqdm
from scipy.spatial.distance import cdi... | wasserstein_loss.py | MIT | 2,174 | 28efaf88a67c7fb740c5b7cd7f5b0632022f1985 | Python | py | |
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from torch.nn import functional as F
import numpy as np
from .Embedding import My_Entity_Aware_Embedding
from .Encoder import MyPCNN_V
from .HierEncoder import HierEncoder
class MyHierRelLayer(nn.Module):
def __init__(self, linear_in, line... | Net/MyModel.py | MIT | 8,029 | 24ec19e36d895e0bd6bccad73f69b3a6ebcfb749 | Python | py | |
import torch
import random
import gdown
import cv2
import argparse
import pickle
import os
import glob
import re
import numpy as np
from torchvision import io
from torchvision import transforms as T
from PIL import Image
from utils.utils import show_models
from pathlib import Path
from models import get_model
from data... | semantics/test_seg_hardnet.py | MIT | 3,926 | e65c5559723ace294c98f4a25726de4965d7917c | Python | py | |
from abc import ABC, abstractmethod
from copy import copy
from enum import Enum
import torch
from nitorch.core.pyutils import make_list
from nitorch.core import dtypes
from nitorch.spatial import affine_sub, affine_permute, voxel_size as affvx
from .indexing import (expand_index, guess_shape, compose_index, neg2pos,
... | nitorch/io/mapping.py | MIT | 44,872 | 2494ac43693d49ef6561d1f121249504b8f472fb | Python | py | |
# flake8: noqa
from .python.roi_align import RoIAlignPool
from .python.psroi_align import PSRoIAlign
from .python.psroi_pool import PSRoIPool
from .python.nms import naive_nms,softer_nms
from .python.deformable_conv import DeformableConv
from .python.focal_loss import (
SigmoidFocalLossFunction,
Soft... | up/extensions/__init__.py | Apache-2.0 | 3,164 | 344b0fa892b46a44ce4885a57fbc88178730f71c | Python | py | |
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from tqdm import tqdm
from argparse import ArgumentParser
from dataset import *
from model import *
DEFAULT_EPOCHS = 10
DEFAULT_OUTPUT = "model"
DEFAULT_BATCH_SIZE = 256
def get_opts():
parser = ArgumentParser()
parse... | train.py | MIT | 4,308 | fed2c913980b21612949b3f0439a5633dd478f4b | Python | py | |
import cv2
import numpy as np
import torch
from torchvision.transforms import CenterCrop
class AddCircles:
"""
Adds concentric circles on the images
"""
def __init__(self, max_num_circles, circle_width, alpha, color):
self.max_num_circles = max_num_circles
self.circle_width = circle_w... | src/transforms.py | MIT | 3,057 | fed2c966f1a8b14d54093a610c9670c38dc8bd0e | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import copy
import logging
import os
from collections import defaultdict
from typing import Any
from typing import Optional, List, Dict, NamedTuple, Tuple, Iterable
import numpy as np
import torch
import torch.nn as nn
from... | fastreid/utils/checkpoint.py | Apache-2.0 | 17,741 | 28b8e7cb442c36f2e1ce4cefed34460e64bc257f | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
class FSPool(nn.Module):
"""
Featurewise sort pooling. From:
FSPool: Learning Set Representations with Featurewise Sort Pooling.
"""
def __init__(self, in_channels, n_pieces, relaxed=False):
"""
in_channels... | fspool.py | MIT | 6,790 | fed2d510d08640093171a04fd9ffc8599acd5b39 | Python | py | |
import argparse
import os
import cv2
import mmcv
import torch
import numpy as np
from mmcv import Config
from mmcv.parallel import collate, scatter
from mmdet.core import get_classes
from mmdet.datasets.pipelines import Compose
from mmdet.apis import inference_detector, init_detector
class LoadImage(object):
d... | tools/line_profiler.py | Apache-2.0 | 2,536 | fed2de97be53381a6fe17d62e3c0be2751784155 | Python | py | |
import torch
import math
from ....ops.center_ops import center_ops_cuda
class MMAssigner(object):
def __init__(self, assigner_cfg, num_classes, no_log, grid_size, pc_range, voxel_size):
"""Return CenterNet training labels like heatmap, height, offset"""
self.out_size_factor = assigner_cfg.out_size_... | pcdet/models/dense_heads/target_assigner/mm_assigner.py | Apache-2.0 | 5,739 | fed2de9bc35ad4d0d4424e68f9fcff5427d5fe39 | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import torch as T
import torch.nn as nn
import torch.nn.functional as F
from .network import DNINetwork
from dni.util import *
class Conv2dDNI(DNINetwork):
def __init__(
self,
input_size,
hidden_size,
output_size,
convolutions=16,
... | dni/dni_nets/conv.py | MIT | 2,189 | 12b63c310821a08a054f85ef65dd6aa93a8ea29f | Python | py | |
from functools import wraps
from typing import Callable
import torch
from torch import Tensor
from .context_managers import RandContext
def cached(func: Callable[..., Tensor]):
"""
A decorator that takes a model call function into a cached compatible version.
:param func: A function that calls the model... | src/grad_cache/functional.py | Apache-2.0 | 1,968 | fed30b30e76ca2458999186294f50c3bffb363fb | Python | py | |
import argparse
import os
import os.path as osp
import pprint
import random
import warnings
import numpy as np
import yaml
import torch
from torch.utils import data
from advent.model.deeplabv2 import get_deeplab_v2
from advent.dataset.gta5 import GTA5DataSet
from advent.dataset.cityscapes import Citysca... | rda/scripts/train.py | MIT | 5,832 | fed30e2ee1f96d4356fd2e4f613c8d02a2706100 | Python | py | |
import copy
import numpy as np
np.random.seed(2)
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from ARLO.environment import LQG
from ARLO.block import ModelGenerationMushroomOnlineSAC
from ARLO.rl_pipeline import OnlineRLPipeline
from ARLO.tuner import TunerGenetic
fr... | experiments/LQG/lqg_sac_seed_3.py | MIT | 10,092 | a9a3fb78fda07b5f25458f34498c15d933404eb1 | Python | py | |
# Copyright (c) 2021 PPViT Authors. 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 applicable... | image_classification/HVT/port_weights/load_hvt_ti_1_pytorch_weights.py | Apache-2.0 | 5,399 | 6b1c91e7f054760b813f9390b63f28e4b400f5de | Python | py | |
from __future__ import absolute_import
import torch
class InputVariationalDropout(torch.nn.Dropout):
u"""
Apply the dropout technique in Gal and Ghahramani, "Dropout as a Bayesian Approximation:
Representing Model Uncertainty in Deep Learning" (https://arxiv.org/abs/1506.02142) to a
3D tensor.
Th... | pymagnitude/third_party/allennlp/modules/input_variational_dropout.py | MIT | 1,367 | 12fdec405eea8b8cf9c0cd7bdae692794d26ad80 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from torch.autograd import Variable
import sys
import numpy as np
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
class wide_ba... | models/wide_resnet.py | BSD-3-Clause | 4,155 | b23a71493f9ef9583555a8e289644551f53173cb | Python | py | |
"""Model setup."""
import os
import torch
import utils, lstm
def setup(opt, checkpoint):
"""Create new model or reload from checkpoint model"""
# Resume model if checkpoint is provided, create a new model otherwise.
if checkpoint is not None:
model_path = os.path.join(opt.resume, checkpoint['model... | init.py | MIT | 977 | 5e16954691f34a16efd6367a5ab21a6dc8b24a2d | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from model.base_model import Base_Model
from utils.pytorch_helper import FF, get_init_function
class SNUH(Base_Model):
def __init__(self, hparams):
super().__init__(hparams=hparams)
self.tau = torch.Tensor([0.99])
... | model/SNUH.py | MIT | 6,409 | fed363b7cf4fbf8e25e701774812f51f85ca3668 | Python | py | |
# Copyright (c) 2021. TsumiNa. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from collections import OrderedDict
from copy import deepcopy
from datetime import datetime, timedelta
from pathlib import Path
from platform import version as sy... | xenonpy/model/training/extension/persist.py | BSD-3-Clause | 6,113 | fce47a613c8b0fce5c86bb3d2bb7059edd072044 | Python | py | |
import os
import logging
import random
from argparse import ArgumentParser
from itertools import chain
from pprint import pformat
import warnings
import torch
import torch.nn.functional as F
from transformers import OpenAIGPTLMHeadModel, OpenAIGPTTokenizer, GPT2LMHeadModel, GPT2Tokenizer
from train import build_input... | kogpt2/cmdinput.py | MIT | 7,167 | e6691835f673b34b51c87e13c4ce077788e140e5 | Python | py | |
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch.optim as optim
import numpy as np
import pandas as pd
"""
Return a list of the test losses at the end of each epoch.
"""
def train_test_trajectory(model, optimizer, train_loader, test_loader, criterion, epoc... | logistic_regression/scripts/fmnist.py | MIT | 6,253 | fed398fb882711db784baecee45999ed09e3b2f3 | Python | py | |
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import time
import os
import sys
import json
from dataset_utils import AverageMeter
from json import JSONEncoder
class MyEncoder(JSONEncoder):
def default(self, o):
return o.__dict__
def calculate_video_results... | test.py | MIT | 2,541 | 7033e82161ef5be76a4aae7e87df4e680fae11b4 | Python | py | |
# 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 math
import unittest
import torch
from common_testing import TestCaseMixin
from pytorch3d.transforms i... | tests/test_transforms.py | MIT,BSD-3-Clause | 46,464 | 5e136112f47b1900abb7d26342d4c5ccf1832081 | Python | py | |
import argparse
from collections import Counter
import torch
import pickle
import pykp.io
import config
def read_tokenized_src_file(path, remove_eos=True):
"""
read tokenized source text file and convert them to list of list of words
:param path:
:param remove_eos: concatenate the words in title and c... | preprocess.py | MIT | 15,444 | fed3dd40f201888ea6930e02e8a0b7c55d103b95 | Python | py | |
import argparse
import logging
import json
import os
import torch
from torch.utils.data import DataLoader, Dataset, RandomSampler
from tqdm import tqdm, trange
from transformers import GPT2Config, GPT2LMHeadModel, GPT2Tokenizer, AdamW, get_linear_schedule_with_warmup
from dataset import QueryRewriteDataset
from uti... | cqr/run_training.py | MIT | 13,446 | fed3e4e82580fc174dcb370551ec7c7e1d2abd59 | Python | py | |
import torch
import numpy as np
# def my_metric(output, target):
# with torch.no_grad():
# pred = torch.argmax(output, dim=1)
# assert pred.shape[0] == len(target)
# correct = 0
# correct += torch.sum(pred == target).item()
# return correct / len(target)
# def my_metric2(output... | modeling/model/metric.py | MIT | 1,745 | 6537e9f25ff1be49f338e4d165ed4bc4b6a52dd4 | Python | py | |
"""
Implementation of "Attention is All You Need"
"""
import torch.nn as nn
from onmt.encoders.encoder import EncoderBase
from onmt.modules import MultiHeadedAttention
from onmt.modules.position_ffn import PositionwiseFeedForward
class TransformerEncoderLayer(nn.Module):
"""
A single layer of the transforme... | onmt/encoders/transformer.py | MIT | 4,063 | f9a3a476aa6724ef01cf644b7727375e8a5d3a47 | Python | py | |
import itertools
import os
import os.path as osp
import time
import re
from collections import OrderedDict
from datetime import datetime
from pathlib import Path
import numpy as np
from mani_skill_learn.env import ReplayMemory
from mani_skill_learn.env import save_eval_statistics
from mani_skill_learn.utils.data impo... | mani_skill_learn/apis/train_rl.py | Apache-2.0 | 10,686 | fcef18995e794d347eb4dfe0420b9916fb7f39f8 | 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/training_loop.py | Apache-2.0 | 45,090 | fed3ffcba04941c06a7fe4cf0494964c74ca7c82 | Python | py | |
'''
BSpline TransMorph
Junyu Chen
jchen245@jhmi.edu
Johns Hopkins University
'''
import math
import torch
from torch import nn as nn
from torch.nn import functional as F
import models.transformation as transformation
import models.TransMorph as TM
import models.configs_TransMorph_bspl as configs
def ... | RaFD/TransMorph2D/models/TransMorph_bspl.py | MIT | 6,858 | ff9c80cb38eb01aec52d61efd9ebf2bc9a74a2e9 | Python | py | |
import sys
import torch
import shutil
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from progressbar import ProgressBar, Percentage, Bar
class FFNN(nn.Module):
def __init__(self, input_size,
hidden_size,
output_size,
num... | FFNN/FFNN.py | MIT | 10,085 | fed40c295f52514ba33ade7c3495d1535b137d91 | 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/collections/tts/test_waveglow.py | Apache-2.0 | 3,921 | fed4142ba3ac87911132440315bb7f887da7fbce | Python | py | |
import os
import numpy as np
import numpy.testing as npt
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
def set_weights_encoder(net):
for child in net.children():
if isinstance(child, (nn.GRU, nn.GRUCell)):
if isinstance(child, nn.GRU):
... | tests.py | MIT | 10,390 | 10fc9f0d3db867108e65e3447f7a3746f9b72fb1 | Python | py | |
from machin.frame.algorithms import DQN
from machin.utils.logging import default_logger as logger
import torch as t
import torch.nn as nn
import gym
# configurations
env = gym.make("CartPole-v0")
observe_dim = 4
action_num = 2
max_episodes = 1000
max_steps = 200
solved_reward = 190
solved_repeat = 5
# model definiti... | examples/framework_examples/dqn.py | MIT | 2,624 | fed4449f53fafc076093102dda8ec22828132a86 | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
from ..utils import ConvModule
class SSDNeck(nn.Module):
def __init__(self, in_channels = [1024,2048],out_channels = 256,out_map=None,start_level = 0,end_level = None):
super(SSDNeck,self).__init__()
self.in_channels = in_channels
if is... | SSD/SSD_FPN_GIoU/model/neck/ssd_neck.py | MIT | 2,276 | fed457364c30491a6e520c7bf8aee44813f0f046 | Python | py | |
import torch
import torch.nn as nn
def get_dice_loss(gt_score, pred_score):
inter = torch.sum(gt_score * pred_score)
union = torch.sum(gt_score) + torch.sum(pred_score) + 1e-5
return 1. - (2 * inter / union)
def get_geo_loss(gt_geo, pred_geo):
d1_gt, d2_gt, d3_gt, d4_gt, angle_gt = torch.split(gt_geo, 1, 1)
... | EAST_box_supervision/network/loss.py | Apache-1.1 | 1,670 | f94511381b21cef08710b5ebe7390b2c7cbad57e | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.