content stringlengths 200 198k | repo stringlengths 4 186 | path stringclasses 1
value | license stringclasses 101
values | size int64 200 198k | sha stringlengths 40 40 | lang stringclasses 1
value | ext stringclasses 1
value |
|---|---|---|---|---|---|---|---|
import logging
import torch.nn.functional
import typing as _typing
import torch_geometric
from torch_geometric.nn.conv import GATConv
from .. import base_encoder, encoder_registry
from ... import _utils
class GATUtils:
@classmethod
def to_total_hidden_dimensions(
cls, per_head_output_dimensions: _... | autogl/module/model/encoders/_pyg/_gat.py | MIT | 6,971 | b23f708cc80076e4a22b3233b529cbf17055dddb | Python | py | |
import math
import warnings
import torch
import torch.nn as nn
from .modules import IBN
__all__ = ['ResNet_IBN', 'resnet18_ibn_a', 'resnet34_ibn_a', 'resnet50_ibn_a', 'resnet101_ibn_a', 'resnet152_ibn_a',
'resnet18_ibn_b', 'resnet34_ibn_b', 'resnet50_ibn_b', 'resnet101_ibn_b', 'resnet152_ibn_b']
model_ur... | ibnnet/resnet_ibn.py | MIT | 11,223 | 651244079b79b770880ac6b089312882c905b334 | Python | py | |
import torch
from mmedit.models.builder import build_component
def test_search_transformer():
model_cfg = dict(type='SearchTransformer')
model = build_component(model_cfg)
lr_pad_level3 = torch.randn((2, 32, 32, 32))
ref_pad_level3 = torch.randn((2, 32, 32, 32))
ref_level3 = torch.randn((2, 32, ... | tests/test_models/test_transformer/test_search_transformer.py | Apache-2.0 | 758 | 29d802acde43bc2b3f646fe44204cbf576cb67c7 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import os
import torch
from torch.autograd import Variable
from torch.utils.data import ConcatDataset
from pythia.tasks.vqa2.task import VQA2Task
from .dataset import VisualDialogDataset
class VisualDialogTask(VQA2Task):
def __init__(self, dataset_type):
... | pythia/tasks/dialog/original.py | BSD-3-Clause | 5,288 | ff01ab17dfc257d0783bf05da68fa21025bf8385 | Python | py | |
import inspect
import os
import pickle
from collections import OrderedDict
from copy import deepcopy
from functools import partial
from torch import optim
def create_folder(folder):
if not os.path.exists(folder):
os.makedirs(folder)
class Chomp:
def __init__(self, src_dict=None):
self.__dic... | torch_agents/cogment_verse_torch_agents/third_party/hive/utils/utils.py | Apache-2.0 | 5,180 | 7003af89450d6c2717aec9bb6ff569f3e428ecc5 | Python | py | |
import math
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
from collections import OrderedDict
import time
from . import model_utils
import logging
BatchNorm2d = nn.BatchNorm2d
bn_mom = 0.1
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 c... | models/pidnet_small_uniPag_pappm_ddfm_camvid.py | MIT | 14,268 | 7ceda6ba9900b7f52451dbc816eb311f7312447b | Python | py | |
"""Training Module."""
import albumentations as album
import torch
import pytorch_lightning as pl
from albumentations.pytorch.transforms import ToTensorV2
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping, LearningRateMonitor
from tablenet i... | handigit/OCR_tablenet/train.py | MIT | 1,697 | 7c7515d7b738ab5d937501e38c31c1e0325f286c | Python | py | |
import os
import torch
import torch.nn as nn
from models.basic.encoder.resnet import seg_resnet50
from models.basic.utils import MLP
from models.basic.decoder.fcn import MoCoFCN
# from models.basic.decoder.pspnet import PSPHead
# from models.basic.decoder.aspp import ASPPHead
class ResNetEncoder(nn.Module):
def... | models/selfsup/MoCoWD/builder.py | MIT | 7,589 | e98ca9dc338207f17652177f7412e42d693b1da1 | Python | py | |
import dgl
import torch
import torch.nn as nn
import torch.nn.functional as F
from dgllife.model.model_zoo import GCNPredictor
class Predictor(nn.Module):
def __init__(self, in_feats, hidden_feats=[32, 32], batchnorm=[True, True], dropout=[0, 0], predictor_hidden_feats=32, n_tasks=64):
super(Predictor, s... | nn/nn.py | MIT | 1,476 | 29d82653b32e3df8aa002326f85f29da1d5bcaf4 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from onmt.models.transformer_layers import PositionalEncoding
from onmt.modules.pre_post_processing import PrePostProcessing
from onmt.models.transformers import TransformerEncoder, TransformerDecoder, Transformer, TransformerDecodingState
from onmt.mo... | onmt/models/speech_recognizer/relative_transformer.py | MIT | 26,169 | 345663063190310eb99df92962187625e6a87c09 | Python | py | |
# Copyright (c) 2019 NVIDIA Corporation
import logging
from abc import abstractmethod
from typing import Dict, Set, Tuple, Optional, List
import torch as t
import torch.nn as nn
from ...core import NeuralModule, DeviceType, WeightShareTransform
from ...utils.helpers import rgetattr, rsetattr, get_cuda_device
class ... | nemo/nemo/backends/pytorch/nm.py | Apache-2.0 | 11,393 | 24b3a13e95d75f7f9b19743d1a48fd8735ab9291 | Python | py | |
import torch
import torch.nn as nn
from ..builder import NECKS
@NECKS.register_module()
class GlobalAveragePooling(nn.Module):
"""Global Average Pooling neck.
Note that we use `view` to remove extra channel after pooling. We do not
use `squeeze` as it will also remove the batch dimension when the tensor... | mmcls/models/necks/gap.py | Apache-2.0 | 1,039 | e9b7a95fe4e86e16c8ff68e0389f6551affe1963 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
helper class that supports empty tensors on some nn functions.
Ideally, add support directly in PyTorch to empty tensors in
those functions.
This can be removed once https://github.com/pytorch/pytorch/issues/12013
is implemented
"""
import m... | maskrcnn_benchmark/layers/misc.py | MIT | 4,605 | 29d856cd1ee363484b211db150b6c1531085fa03 | Python | py | |
import numpy as np
import torch
import torch.nn.functional as F
import matplotlib
import threading
try:
from matplotlib import pyplot as plt
except ImportError:
print("failed importing pyplot!")
from matplotlib import collections as mc
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation
import t... | neural_layout/network_graph.py | MIT | 23,604 | 5f8f1560068914a431d4cbde66f478e70c045019 | Python | py | |
#!/usr/bin/python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "Licens... | examples/torchexample.py | Apache-2.0 | 3,096 | 1ec084aeed1c948a84c94b90bbc3b1cb290d87c3 | Python | py | |
from __future__ import print_function
import argparse
import torch
import csv
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
import numpy as np
def batch_product(iput, mat2):
result = None
for i in r... | models.py | Apache-2.0 | 17,020 | dfb88b89c69315186a93fc0582088fe3187d9155 | Python | py | |
import argparse
import os
import torch
import torch.nn as nn
from examples.models.cifar10.mobilenet import DEFAULT_STATE_DICT, Mobilenet
from tinynn.converter import TFLiteConverter
from tinynn.graph.quantization.quantizer import PostQuantizer
from tinynn.graph.tracer import model_tracer
from tinynn.util.cifar10 impor... | examples/qat/post.py | MIT | 3,662 | 6502559192be42fd61d0712f9224a79ac31c6a43 | Python | py | |
# AUTOGENERATED! DO NOT EDIT! File to edit: 50-audio-training.ipynb (unless otherwise specified).
__all__ = ['timestamp2index']
# Cell
#modeling imports
from transformers import Wav2Vec2Processor, Wav2Vec2ForSequenceClassification, pipeline, TrainingArguments, Trainer
from datasets import load_metric
import torch
imp... | wise/audio_modeling.py | MIT | 1,714 | 708986aba1570c35a0848dbcd7f6333e4922dd5b | Python | py | |
import numpy as np
import os
from tqdm import tqdm
import argparse
from sklearn.metrics import confusion_matrix
import yaml
# torch imports
import torch
import torch.utils.data
# lightconvpoint imports
import lightconvpoint.utils.data_utils as data_utils
import lightconvpoint.utils.metrics as metrics
from lightconvpo... | examples/npm3d/test.py | Apache-2.0 | 6,906 | 29d89a60b761b3250226575b83c1110a4edbf5b3 | Python | py | |
from networks import VggDepthEstimator
from LKVOLearner import FlipLR
import torch
from torch.autograd import Variable
import os
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import requests
import cv2
import argparse
# get the commandline arguments to obtain model and ip cam address
parser ... | src/real-time_demo.py | BSD-3-Clause | 1,978 | 653c957d0a046ae92bed39ddb9edbe9e46d9e6b5 | Python | py | |
from utils import *
from repre import *
from reason import *
import torchtext
import dill
import json
import traceback
import argparse
import datetime
import time
# torch.set_printoptions(precision=16)
parser = argparse.ArgumentParser()
parser.add_argument("--co_train", type=bool, default = False, help="Whether to add... | 1-HRF-xgb/prepare_embedding.py | MIT | 4,528 | 1ed6eb4e317a18afe5afc38d274f6b47c343dab2 | Python | py | |
# pylint: disable=no-self-use,invalid-name
import pytest
import spacy
import torch
import numpy
import h5py
from allennlp.common.testing import ModelTestCase, AllenNlpTestCase
from allennlp.common.params import Params
from allennlp.data.dataset import Batch
from allennlp.data import Token
from allennlp.data.token_inde... | allennlp/tests/modules/token_embedders/openai_transformer_embedder_test.py | MIT | 8,345 | 7ca52e52a19019ab881e315a6776c1e36edceb38 | Python | py | |
"""model.py - Model and module class for EfficientNet.
They are built to mirror those in the official TensorFlow implementation.
"""
# Author: lukemelas (github username)
# Github repo: https://github.com/lukemelas/EfficientNet-PyTorch
# With adjustments and added comments by workingcoder (github username).
import... | efficientnet_pytorch/model.py | Apache-2.0 | 17,396 | b23de5f97aecfb60aca41df7ed22e51a06994d5a | Python | py | |
import argparse
import collections
import copy
import gc
import os
import shutil
import sys
import time
import warnings
from datetime import datetime
import torch.backends.cudnn as cudnn
from torch import nn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed... | imagenet/train.py | MIT | 20,531 | fcd9ee83ca5621adf51b3991967514b878fa96fd | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
class CrossEntropyLoss(nn.CrossEntropyLoss):
def __init__(self, weight=None, ignore_index=-100, reduction='mean', smooth_eps=None, smooth_dist=None,
from_logits=True):
super(CrossEntropyLoss, self).__init__(weight=weight,
... | maskrcnn_benchmark/layers/cross_entroy_loss.py | MIT | 3,599 | a92a59b960c85cb30a7c3c4a81033e5d2f1c8777 | Python | py | |
import torch
import torchvision
from torch import nn as nn
class GANLoss(nn.Module):
"""Define different GAN objectives.
The GANLoss class abstracts away the need to create the target label tensor
that has the same size as the input.
"""
def __init__(self, gan_mode, target_real_label=1.0, target_... | models/modules/loss.py | BSD-3-Clause | 4,888 | 29d8cf8ce1701807c717966392ac34663b388126 | Python | py | |
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
from modeling.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
webroot = 'http://dl.yf.io/drn/'
model_urls = {
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'drn-c-26': webroot + 'drn_c_26-ddedf421.pt... | modeling/backbone/drn.py | MIT | 15,145 | 52bf3a87593df83e3d687bfefe45aebb89961f4c | Python | py | |
## Created by: Zilin Gao
## Implementation of "Global Second-order Pooling Convolutional Networks", Zilin Gao, Jiangtao Xie, Qilong Wang, Peihua Li. IN CVPR2019.
## Copyright (c) 2019 Zilin Gao, Jiangtao Xie, Qilong Wang and Peihua Li.
##
## This source code is licensed under the MIT-style license found in the
## LICEN... | main.py | MIT | 19,207 | 29d8f033d203798e412bdc536d130955ba4d044d | Python | py | |
import argparse
import math
import logging
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.distributed as dist
from torch.utils.data import DataLoader
from dataset import create_dataset
from model import MODEL_NAMES, create_model
from helper import setup_default_logging
parser = argpars... | code/6.FairFaceClassifier/inference.py | MIT | 6,490 | e62472756f525b69748643125b3d6b5611b1278b | Python | py | |
"""
=====
Distributed by: Notre Dame SCAI Lab (MIT Liscense)
- Associated publication:
url: https://arxiv.org/abs/2010.03957
doi:
github: https://github.com/zabaras/transformer-physx
=====
"""
import numpy as np
import random
import argparse
import os, errno, json
import torch
from typing import List
HOME = os.getcwd... | trphysx/embedding/training/enn_args.py | MIT | 4,476 | 4ba79d32361fc38a7ce543900a4f29af88734b6d | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | run_poker.py | Apache-2.0 | 3,985 | 29d90bdc6fbabfc2fdddc42d1e13ab94b5df7155 | Python | py | |
import torch
import torch.nn as nn
import pdb
"""
A Processing module takes an input from a stream and the independent memory
of that stream and runs a single timestep of a GRU cell, followed by
dropout and finally a linear ELU layer on top of the GRU output.
It returns the output of the fully connected... | egg/zoo/gym-game/models/modules/processing.py | MIT | 2,592 | 29d9202060b50b53c89c0332c4a99c038c9dc22f | Python | py | |
""" DropBlock, DropPath
PyTorch implementations of DropBlock and DropPath (Stochastic Depth) regularization layers.
Papers:
DropBlock: A regularization method for convolutional networks (https://arxiv.org/abs/1810.12890)
Deep Networks with Stochastic Depth (https://arxiv.org/abs/1603.09382)
Code:
DropBlock impl ins... | mmdet/models/backbones/layers/drop.py | Apache-2.0 | 6,873 | 5f2008c0825c1fceff6e04e613a6a66e33a9869a | Python | py | |
# Copyright 2020 Toyota Research Institute. All rights reserved.
import torch
from packnet_sfm.models.SfmModel_fisheye_CamConvs import SfmModel_fisheye_CamConvs
from packnet_sfm.losses.fisheye_multiview_photometric_loss import MultiViewPhotometricLoss
from packnet_sfm.models.model_utils import merge_outputs
class S... | packnet_sfm/models/SelfSupModel_fisheye_CamConvs.py | MIT | 5,376 | 5f7332b5c12b26d2208aabef4adafd1776099a48 | Python | py | |
# Copyright 2020 Google LLC
#
# 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, ... | torchsde/_core/adjoint.py | Apache-2.0 | 15,298 | 29d94d2eed7d28acca4cdb9e1508193adbe31f5b | Python | py | |
import pickle
import pytest
import torch
from torch import nn
from garage.envs import GymEnv
from garage.torch.q_functions import DiscreteCNNQFunction
from tests.fixtures.envs.dummy import DummyBoxEnv
# yapf: disable
@pytest.mark.parametrize('batch_size, hidden_channels, kernel_sizes, '
's... | tests/garage/torch/q_functions/test_discrete_cnn_q_function.py | MIT | 2,853 | 29d9584ac82c2759d16a14397f7215e0eabe142a | Python | py | |
from torch.utils.data.dataset import Dataset
class TowheeDataSet:
"""
TowheeDataSet is a kind of dataset wrapper, where the `self.dataset` is the true dataset.
"""
def __init__(self):
self.framework = None
self.dataset = None
def __len__(self):
raise NotImplementedError
c... | towhee/data/dataset/dataset.py | Apache-2.0 | 662 | 29d96603ed32169fb5516fbc4bab8ef9067f887e | Python | py | |
import logging
from torchtext.utils import download_from_url
from torchtext.data.datasets_utils import (
_RawTextIterableDataset,
_wrap_split_argument,
_add_docstring_header,
_create_dataset_directory,
_read_text_iterator,
)
URL = {
'train': "https://raw.githubusercontent.com/wojzaremba/lstm/ma... | torchtext/datasets/penntreebank.py | BSD-3-Clause | 1,338 | 29d9666af1abc662c90e577805f66e213ce8f303 | Python | py | |
import torch.nn as nn
class SELayer(nn.Module):
def __init__(self, channel, reduction=16):
super(SELayer, self).__init__()
self.global_avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Sequential(
nn.Linear(channel, channel // reduction),
nn.ReLU(inplace=True),
nn.Linear(channel // reduction, channel),
... | lib/nets/modules/se_modules.py | MIT | 2,839 | 29d9684fe7d7adc95e91d7099bb8fb463b9253e7 | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def fused_leaky_relu(input, bias=None, negative_slope=0.2, scale=2 ** 0.5):
if bias is not None:
rest_dim = [1] * (input.ndim - bias.ndim - 1)
return (
F.leaky_relu(
input + bias.view(1, bia... | tortoise/models/random_latent_generator.py | Apache-2.0 | 1,649 | e90ef2130a47ec52160709877972716352e04c9c | Python | py | |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
This file contains components with some default boilerplate logic user may need
in training / testing. They will not work for everyone, but many users may find them useful.
The behavior of functions/classes in this file... | projects/DensePose/densepose/dummy/defaults.py | Apache-2.0 | 25,004 | d7ec9545a14e9ce97b712a6db616cadb3f8f41f8 | Python | py | |
from fastai.vision import *
import torch
from loss_functions.triplet_loss import TripletLoss
import glob
from sklearn.manifold.t_sne import TSNE
class L2_norm(nn.Module):
def __init__(self):
super(L2_norm, self).__init__()
def forward(self, x):
return F.normalize(x, p=2, dim=-1)
if __name__ ... | extract_embeddings.py | Apache-2.0 | 2,355 | f9aa32b4fa0e7e5247f1a36e0e39c25f55ef0cee | 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/plugins/training_type/training_type_plugin.py | Apache-2.0 | 13,457 | 29d9944a3f33da3ea139a11fe1b725992bd7822f | Python | py | |
# train_sum.py
"""
Train and test unsupervised summarization model
Usage:
Train model:
1. python train_sum.py --gpus=0,1,2,3 --batch_size=16 \
--tau=2.0 --bs_dir=tmp
Test model:
2. python train_sum.py --mode=test --gpus=0 --batch_size=4 \
--tau=2.0 --notes=tmp
"""
import os
from collections import defaultdict
from ... | checkpoints/sum/train/hotel_mask_sing_asp/batch_size_12-notes_4gpu/code_snapshot/train_sum.py | Apache-2.0 | 6,538 | 29d99caaae37a46850f806f5f5249f02d59ad08a | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# NEURAL CODES AND EMBEDDING ANALYZER
#
from ungol.common import logger
from ungol.common import embed as uce
from ungol.common.util import ts
import h5py
import attr
import torch
import numpy as np
import pandas as pd
from tqdm import tqdm as _tqdm
import gc
import... | models/ungol/models/analyze.py | MIT | 26,395 | 29d9a424d154587f2acfff8e02ffbcdc647977f8 | Python | py | |
# Copyright (C) 2020 * Ltd. All rights reserved.
# author : Sanghyeon Jo <josanghyeokn@gmail.com>
# modified by Sierkinhane <sierkinhane@163.com>
import os
import sys
import copy
import shutil
import random
import argparse
import numpy as np
import imageio
import torch
import torch.nn as nn
import torch.nn.functiona... | WSSS/inference_CCAM.py | MIT | 8,611 | e906b2154c727855a10276bd2a8626f2e4ad0cc5 | Python | py | |
import argparse
import math
import torch
import numpy as np
from tqdm import tqdm
from sklearn.metrics import classification_report
from fairseq.data import data_utils
from fairseq.models.bart import BARTModel
# https://github.com/pytorch/fairseq/blob/108f7204f6ccddb676e6d52006da219ce96a02dc/fairseq/models/bart/hub_i... | scripts/code_to_code/defect_prediction/evaluator.py | MIT | 4,021 | dfe41e10f904af60351875323fdffb334eff1f68 | Python | py | |
from functools import partial
import numpy as np
from mmcv.cnn import ConvModule, constant_init, kaiming_init
from mmcv.runner import _load_checkpoint, load_checkpoint
from mmcv.utils import _BatchNorm
from torch import nn as nn
from torch.utils import checkpoint as cp
from ...utils import get_root_logger
from ..comm... | mmaction/models/backbones/resnet.py | Apache-2.0 | 26,154 | 29d9df8135a1519a4b96a4bea6c3b0b98fe4309f | Python | py | |
import random
import numpy as np
import torch
from torch_sparse import SparseTensor
from tqdm import tqdm
from rgnn_at_scale.attacks.base_attack import SparseAttack
from rgnn_at_scale.helper import utils
class DICE(SparseAttack):
"""DICE Attack
Parameters
----------
add_ratio : float
ratio ... | rgnn_at_scale/attacks/dice.py | MIT | 6,165 | 45f17596fcd5a13d63dd43ae5d55d27cab397e3d | Python | py | |
'''
PointGroup test.py
Written by Li Jiang
'''
import torch
import time
import numpy as np
import random
import os
from util.config import cfg
cfg.task = 'test'
from util.log import logger
import util.utils as utils
import util.eval as eval
from tensorboardX import SummaryWriter
writer = SummaryWriter(cfg.exp_path)
... | test.py | Apache-2.0 | 10,687 | 29da036ca1c0e616274a811330a676cf2ddb358c | Python | py | |
import argparse
import collections
import torch
import data_loader.data_loaders as module_data
import model.loss as module_loss
import model.metric as module_metric
import model.model as module_arch
from parse_config import ConfigParser
import trainer as trainer_arch
from functools import partial
import time
import log... | output_prediction.py | Apache-2.0 | 6,819 | 107c1b35fa7e49800468bd44320c59af776683d8 | Python | py | |
import torch
import torch.nn as nn
from torch.nn.utils import weight_norm
from TCN.mycelu import *
USE_WEIGHT_NORM = False
USE_WEIGHT_NORM = True
class Chomp1d(nn.Module):
def __init__(self, chomp_size):
super(Chomp1d, self).__init__()
self.chomp_size = chomp_size
def forward(self, x):
... | TCN/tcn.py | MIT | 2,680 | 52a0e62fb05205ec2851369a65a5e79a6a6be780 | Python | py | |
import numpy as np
import random
import torch
# set random seeds for the pytorch, numpy and random
def set_seeds(args, rank=0):
# set seeds for the numpy
np.random.seed(args.seed + rank)
# set seeds for the random.random
random.seed(args.seed + rank)
# set seeds for the pytorch
torch.manual_see... | rl_utils/seeds/seeds.py | MIT | 407 | 29da4b4cffebdc0a1f707dd5b6e3aca626d6f43e | Python | py | |
#=========================================================
# Developer: Vajira Thambawita
# Reference: https://github.com/meetshah1995/pytorch-semseg
#=========================================================
import argparse
from datetime import datetime
import os
import copy
from tqdm import tqdm
import matplotlib.... | 222_REAL_FAKE_UNETPlusPlus_fold_2.py | MIT | 19,167 | 707b3fd7c37ba7e88a2f3f58d9786325d731de8c | Python | py | |
import torch
from . import isoneutral_pytorch
from torchbenchmark.tasks import OTHER
from ...util.model import BenchmarkModel
def _generate_inputs(size):
import math
import numpy as np
np.random.seed(17)
shape = (
math.ceil(2 * size ** (1 / 3)),
math.ceil(2 * size ** (1 / 3)),
... | torchbenchmark/models/pyhpc_isoneutral_mixing/__init__.py | BSD-3-Clause | 3,386 | 704ab26fd773c701c2a9034f117840af8697d517 | Python | py | |
import torch
import deepspeed
###################################
# Setup
###################################
class VerboseLinear(torch.nn.Linear):
def __init__(self, **kwargs):
print(f'Begin VerboseLinear.__init__')
super().__init__(**kwargs)
print(f'End VerboseLinear.__init__')
class... | tests/small_model_debugging/stage3_test.py | MIT | 2,425 | 5eb1e7d6c14c10c3f24c6a990c98f4ee947bd6f1 | Python | py | |
# -*- coding: utf-8 -*
from loguru import logger
import os
import os.path as osp
import torch
from copy import deepcopy
from typing import Dict, Tuple, List
from torch import nn
from torch.utils.data import DataLoader
from videoanalyst.model.module_base import ModuleBase
from videoanalyst.optim.optimizer.optimizer_b... | videoanalyst/engine/trainer/trainer_base.py | MIT | 6,223 | 29da5e7cfe75a1f96edce377e009a53d0bc48677 | Python | py | |
from __future__ import absolute_import, division, print_function
import json
import logging
import math
import os
import random
import warnings
from multiprocessing import cpu_count
import numpy as np
from scipy.stats import pearsonr
from sklearn.metrics import (
confusion_matrix,
label_ranking_average_precis... | simpletransformers/question_answering/question_answering_model.py | Apache-2.0 | 43,747 | b21e3dc3ef47398b622e09cf23a8c1948458bf4b | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 16 14:47:33 2019
@author: Matteo Papini
"""
import torch
import gym
import potion.envs
from potion.actors.continuous_deterministic_policies import ShallowDeterministicPolicy
from potion.actors.hyperpolicies import GaussianHyperpolicy
from potion.com... | script/pgpe_minigolf.py | MIT | 4,353 | 80151cb520ad4dd08374a61df87b1204b3c547c8 | Python | py | |
import torch
import torch.nn.functional as F
from packaging import version
def grid_sample_bilinear(input, grid):
# PyTorch 1.3 introduced an API change (breaking change in version 1.4), therefore we check this explicitly
# to make sure that the behavior is consistent across different versions
if version.... | model/utils.py | MIT | 2,341 | 29da95fdeb2e2719ef1da27c2f9ad18c4166c9b4 | Python | py | |
#!/usr/bin/env python
# coding=utf-8
# Copyright 2017-2020 The THUMT Authors
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import numpy as np
import tensorflow as tf
import torch
def convert_tensor(variables, name, ... | thumt/scripts/convert_checkpoint.py | BSD-3-Clause | 3,860 | ff67d667b10152026759d3908bcfe51fece80223 | Python | py | |
from torch import nn
class Net(nn.Module):
"""
Feed forward network with a four convolution-max-pooling blocks act as a feature extractor
and the dataset tasks specific classifier
"""
def __init__(self):
super().__init__()
self.feature_extractor = nn.Sequential(
nn.Conv... | model/net.py | MIT | 1,044 | a9978b25d2dc416ee2cac0d22f34ef7688314540 | Python | py | |
import torchvision
import torchvision.transforms as transforms
from .torch import TorchDataset
class TorchCIFAR10(TorchDataset):
"""`TorchCIFAR10` class.
Represents a CIFAR10 dataset class for PyTorch.
"""
TORCH_MODULE = torchvision.datasets.CIFAR10
DATASET_SIZE = {"train": 50000, "test": 10000... | privacy_evaluator/datasets/torch/cifar10.py | MIT | 1,748 | 8004970bbe2b23152a0883ba1b01c5cb399031c7 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as data
from torchvision import datasets, transforms
import os
import numpy as np
from PIL import Image
import time
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") # 让torch判断是否使用GPU,建议使用GPU环境,因为会快很多
class ... | SEU-captcha-recognition/jwc_captcha_recog.py | MIT | 2,716 | 343ab542f95813d40925ab641aa96cc0157f6e9f | Python | py | |
import torch
from torch.nn.utils import clip_grad_norm_
from apex import amp
from ignite.engine.engine import Engine, Events
import huepy as hue
import time
import os.path as osp
from .misc import ship_data_to_cuda, lucky_bunny, warmup_lr_scheduler
from .distributed import reduce_dict, is_main_process
from .logger imp... | lib/utils/trainer.py | MIT | 5,852 | 103eca0041bea54b909f8c2c7582879d9e7b6fbb | Python | py | |
from .src.graph_pb2 import GraphDef
from .src.node_def_pb2 import NodeDef
from .src.versions_pb2 import VersionDef
from .src.attr_value_pb2 import AttrValue
from .src.tensor_shape_pb2 import TensorShapeProto
from distutils.version import LooseVersion
import warnings
def parse(graph):
import torch
scope = {}
... | tensorboardX/graph.py | MIT | 4,485 | 28c7d935f8c0f0eb8e139a6755a510e28ca1eab1 | Python | py | |
import torch.nn as nn
from PreActBlock import PreActBlock
def conv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution"""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
# FrontNet
class FrontNet(nn.Module):
def __init__(self, block, layers, isGray=False):
... | PyTorch/FrontNet.py | MIT | 2,133 | f99f7e17c5e879dd111c17f2765a208bc1a8c5ad | Python | py | |
"""
Main script for running the adversarial and OOD detection experiments.
"""
from __future__ import absolute_import, division, print_function
import sys
import argparse
import os
import time
import numpy as np
import torch
from torchvision import datasets, transforms
from nets.mnist import *
from nets.svhn import *
f... | expts/detection_main.py | MIT | 32,941 | 29db123e31682f4d035f3e8b29a5f29ab7bf578f | Python | py | |
import torch
import os.path as osp
from PIL import Image
from torch.utils.data import Dataset
import numpy as np
from torchvision import transforms as T
import glob
import re
from .base import BaseDataset
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
def read_image(img_path):
"""Keep reading ima... | dataset/data.py | MIT | 1,377 | 29db2e1f49ec58ebf547ec8ee951ce880ad78b34 | Python | py | |
import pytest
import torch
from mish import MemoryEfficientMish, Mish, MishImplementation
from torch.testing import assert_allclose
def get_input_params():
devs = ['cpu']
if torch.cuda.is_available() and torch.cuda.device_count() > 0:
devs += ['cuda:0'] # TODO: Allow other devices
dev_types = [(dty... | test_mish.py | MIT | 2,161 | 7063820709fbcbe772ad2dd84883808dfd893504 | Python | py | |
if __name__ == "__main__":
#%%
import sys
import time
from sklearn.model_selection import StratifiedKFold, train_test_split
from tqdm import trange
sys.path.append('..')
import os
import torch
import pandas as pd
import numpy as np
from torch.nn import CrossEntropyLoss, ... | experiments/old/experiment_09_vdem.py | Apache-2.0 | 27,579 | b29e5eec4d7489dacaf71c7e347d1b0c9e378b01 | Python | py | |
import numpy as np
import torch.nn as nn
from . import basicblock as B
import torch
"""
# --------------------------------------------
# FFDNet (15 or 12 conv layers)
# --------------------------------------------
Reference:
@article{zhang2018ffdnet,
title={FFDNet: Toward a fast and flexible solution for CNN-based i... | dphsir/denoisers/models/network_ffdnet.py | MIT | 4,222 | 29db94135b487a84eefe3a71106ce911baa17e96 | 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.
r"""
Gaussian Process Regression models based on GPyTorch models.
.. [Wu2019mf]
J. Wu, S. Toscano-Palmerin, P. I. ... | botorch/models/gp_regression_fidelity.py | MIT | 14,079 | 29dbc680f9b93256119d16bad028ec1b7b85813c | Python | py | |
from typing import List, Iterable, Tuple, Any, Union, Dict, Optional, Callable
import torch
from transformers import LogitsProcessor
class WhiteListLogitsProcessor(LogitsProcessor):
"""
A simple LogitsProcessor constraining the generation to "white list", i.e. a set of allowed tokens.
"""
def __i... | constrained_decoding/word_list_decoding.py | MIT | 1,986 | ffa0ab24627be361e713f884755ce60e45327334 | Python | py | |
# -*- coding: utf-8 -*-
"""
@created on: 4/3/21,
@author: Shreesha N,
@version: v0.0.1
@system name: badgod
Description:
..todo::
"""
import librosa
import librosa.display
import matplotlib.pyplot as plt
import cv2
import json
import random
import time
import numpy as np
import torch
import torch.nn as nn
import to... | covid_19/runners/plain_conv_vae.py | MIT | 22,554 | 12b9f58b0001143bf749440e37fb864dd38886a2 | Python | py | |
import torch
def split_shot_query(data, way, shot, query, ep_per_batch=1):
img_shape = data.shape[1:]
data = data.view(ep_per_batch, way, shot + query, *img_shape)
x_shot, x_query = data.split([shot, query], dim=2)
x_shot = x_shot.contiguous()
x_query = x_query.contiguous().view(ep_per_batch, way ... | utils/few_shot.py | MIT | 1,029 | 29dbe5dce119719422e0fe16e5f4fd3e05afb889 | Python | py | |
## Use Python to run Deep Autoencoder (feature selection)
## path - is a string to desired path location.
import pandas as pd
import numpy as np
import torch
from torchvision import transforms
from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils.data import Dataset,... | example/1. Autoencoder.py | MIT | 5,901 | 29dbf32fa9fef10d029e873599647e44bff6e08b | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import matplotlib
import matplotlib
matplotlib.use("Agg")
from matplotlib import pyplot as plt
from scipy.io import wavfile
import os
import librosa
import text
import hparams as hp
import soundfile
## Vocoders ##
def get_waveglow():... | vocoder.py | MIT | 1,204 | 29dbf7272258553044fe4396569422ed567dbce1 | Python | py | |
import torch
import torch.nn as nn
import threading
from torch._utils import ExceptionWrapper
import logging
def get_a_var(obj):
if isinstance(obj, torch.Tensor):
return obj
if isinstance(obj, list) or isinstance(obj, tuple):
for result in map(get_a_var, obj):
if isinstance(result,... | util.py | MIT | 2,495 | 6b11cd4ea86d93304a882bebda2f5128bec7eb4d | Python | py | |
# Copyright 2020 - 2021 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 wri... | monai/data/nifti_writer.py | Apache-2.0 | 8,061 | 29dc62cdec3a5b9569852a203e8c81c37f7d74d4 | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
class Encoder(nn.Module):
def __init__(self):
super(Encoder, self).__init__()
self.encoder = nn.Sequential(
nn.Linear(3*32 * 32, 1280),
nn.ReLU(),
nn.Linear(1280, 1024)
)
def forward(self, x):
... | net_simple_cifar10_1d.py | MIT | 680 | 29dc74caa5454bc6c9a9950edb7e109162c21aac | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
This file contains primitives for multi-gpu communication.
This is useful when doing distributed training.
"""
import functools
import logging
import numpy as np
import pickle
import torch
import torch.distributed as dist
_LOCAL_PROCESS_GROUP ... | detectron2/utils/comm.py | Apache-2.0 | 7,936 | 347b85c5f363cb31e4e2ce2c4c4a7380f45b5475 | Python | py | |
from pathlib import Path
import torch
from torch.nn import functional as F
from torchaudio import functional as AF, sox_effects
import torchaudio
from src.meldataset import load_wav
torchaudio.set_audio_backend('sox_io')
def apply_sox_effect(tensor, sample_rate, effects):
return sox_effects.apply_... | src/speech_distillation/augmentation/augmentation_methods.py | MIT | 5,696 | cc01aaff3341e30f3bbc2b4535c89ca2a8fed7ac | Python | py | |
# Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
import os
import time
import numbers
import glob
import torch
import torch.multiprocessing as mp
import torch.distributed as dist
import mmcv
from mmcv import get_git_hash
from mmseg import __version__
# from mmseg.apis import train_segme... | mpa/seg/trainer.py | Apache-2.0 | 5,557 | 29dc8e000c561be39c1a8f34622ce2a02f213fa6 | Python | py | |
# File: lstm_v5.py
# Author: Ronil Pancholia
# Date: 4/19/19
# Time: 12:36 AM
from torch import nn
class LSTM_v5(nn.Module):
def __init__(self):
super(LSTM_v5, self).__init__()
self.lstm = nn.LSTM(input_size=12, hidden_size=200, num_layers=4, bias=True, bidirectional=False)
self.fc2 = nn.L... | models/lstm_v5.py | MIT | 628 | 29dc8f60656399700cf3ba8f63d5af53b7977575 | Python | py | |
"""
threedb.controls.blender.background
===================================
Defines a Blender control for solid-color background color modifications.
"""
from typing import Any, Dict
from colorsys import hsv_to_rgb
import torch as ch
from ...try_bpy import bpy
from ..base_control import PostProcessControl
class Bac... | threedb/controls/blender/background.py | MIT | 2,194 | 101f3ab78e21d2c127353b9508c0ee70f51ca9af | Python | py | |
import os
import inspect
from pathlib import Path
timm_model_cfgs = [
('nfnet', 'CLASSIFICATION', 'dm_nfnet_f0'),
('efficientnet', 'CLASSIFICATION', 'mixnet_m'),
('regnet', 'CLASSIFICATION', 'regnety_002'),
('resnest', 'CLASSIFICATION', 'resnest14d'),
('vision_transformer', 'GENERATION', 'vit_small... | torchbenchmark/models/gen_timm_models.py | BSD-3-Clause | 6,289 | 29dca9e38397b41d5c89df655be7f9687112064a | Python | py | |
"""Common functions to marshal data to/from PyTorch
"""
import collections
from typing import Optional, Sequence, Union, Dict, List, Any
import numpy as np
import torch
from torch import nn, Tensor
from .support import pytorch_toolbelt_deprecated
__all__ = [
"count_parameters",
"image_to_tensor",
"logit"... | pytorch_toolbelt/utils/torch_utils.py | MIT | 7,324 | e9398affc9d70c2c08126133954511fea69e2722 | Python | py | |
import torch
import numpy as np
class Subset(torch.utils.data.Dataset):
def __init__(self, dataset, indices, transform):
self.dataset = dataset
self.indices = indices
self.transform = transform
self.targets = np.array(dataset.targets)[self.indices]
def __getitem__(self, idx):
... | datasets/custom_subset.py | MIT | 1,521 | e60e47b58297f1e95ddaf5428bf1bccb18059ea8 | Python | py | |
# proccess
import torch
from torchvision import transforms
from torchvision import datasets
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.optim as optim
batch_size = 64
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,),(0.3081,))
])
... | liuer/9-2.py | Apache-2.0 | 2,298 | fdf16238a81acaad7e1af4aa61c0609812ef7719 | Python | py | |
import json
import torch
from ArticulatoryCombinedTextFrontend import ArticulatoryCombinedTextFrontend
def pretrain_512_dim():
with open("embedding_table_512dim.json", 'r', encoding="utf8") as fp:
datapoints = json.load(fp)
datapoints.pop('̩')
embedding = torch.nn.Sequential(torch.nn.Linear(66,... | Preprocessing/pretrain_articulatory_features_combined.py | Apache-2.0 | 2,781 | 29dce9a92ca1f8a64bbceb6f1f311b10cc81062e | Python | py | |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import os
from scipy.ndimage.filters import gaussian_filter
import sys
import numpy as np
from PIL import Image... | deepcluster-master/visu/gradient_ascent.py | MIT | 4,670 | e92e83cdc156bde86e9690a3e633f0c5f01fc261 | Python | py | |
import torch
import syft
from typing import List, Tuple
from syft.generic.frameworks.hook import hook_args
from syft.generic.frameworks.overload import overloaded
from syft.workers.abstract import AbstractWorker
from syft.generic.abstract.tensor import AbstractTensor
class PrivateTensor(AbstractTensor):
def _... | syft/frameworks/torch/tensors/interpreters/private.py | Apache-2.0 | 6,472 | fdc0f24a569aab29571d319ebded72f06d7e8fa3 | Python | py | |
import torch
from modules.models.Seq2Seq_atn import EncoderCRNN, AttnDecoderRNN
class ModelHandler:
@staticmethod
def save_checkpoint(state, filename):
torch.save(state, filename)
@staticmethod
def get_new_model(input_channels, gru_layers, hidden_size, num_classes=6):
# get a new mode... | modules/models/ModelHandler.py | MIT | 2,729 | 29dd23b9d6416092d950de33154eccfb01bf99cf | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
COCO dataset which returns image_id for evaluation.
Mostly copy-paste from https://github.com/pytorch/vision/blob/13b35ff/references/detection/coco_utils.py
"""
from pathlib import Path
import torch
import torch.utils.data
import torchvision
f... | datasets/coco.py | Apache-2.0 | 5,330 | 455e86e7b7f5eb883aed1c6992cd3c92d3b28fa4 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import repeat, rearrange
from quant_noise import quant_noise
class Xformer(nn.Module):
def __init__(
self,
input_dim,
num_heads,
dropout=0.0,
scalar=2,
max_seq_len=280,
bias... | xformer_pytorch/xformer_pytorch.py | Apache-2.0 | 2,599 | a95d644484c3e266331fc60b3f188e6644c206b0 | Python | py | |
# YOLOv5 experiment logging utils
import warnings
from threading import Thread
import torch
from torch.utils.tensorboard import SummaryWriter
from utils.general import colorstr, emojis
from utils.loggers.wandb.wandb_utils import WandbLogger
from utils.plots import plot_images, plot_results
from utils.torch_utils imp... | utils/loggers/__init__.py | MIT | 5,938 | 29dd4605341b685660b17a89d998ae22ac9c9163 | Python | py | |
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
# Generaly G architecutre was bravely taken from this project with minor changes:
# https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix
class Generator(nn.Module):
def __init__(self, input_nc=3, output_nc=4... | models.py | MIT | 3,812 | 29dd5bca74797b2de08a793adfdb31c85a06afbc | Python | py | |
import argparse
import torch
from torchvision import transforms
import numpy as np
import cv2 as cv
import sys
#python run.py --photo D:\trash\mountain.jpg
import opt
from places2 import Places2
from evaluation import evaluate
from net import PConvUNet
from util.io import load_ckpt
parser = argparse.ArgumentParser()... | run.py | MIT | 3,720 | 29dd5d5eb9230d4cc4bbaf2e24ffbc7016d8b371 | Python | py | |
import datetime
import dgl
import numpy as np
import random
import torch
import torch.nn.functional as F
from dgl import model_zoo
from dgl.data.chem import one_hot_encoding
from dgl.data.utils import split_dataset
from sklearn.metrics import roc_auc_score
def set_random_seed(seed=0):
"""Set random seed.
Par... | examples/pytorch/model_zoo/chem/property_prediction/utils.py | Apache-2.0 | 12,242 | b2a1a697a598cfae87b6cc4998e387705f676eb5 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.