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 (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import os
import torch
from maskrcnn_benchmark.utils.model_serialization import load_state_dict
from maskrcnn_benchmark.utils.c2_model_loading import load_c2_format
from maskrcnn_benchmark.utils.imports import import_file
from mask... | maskrcnn_benchmark/utils/checkpoint.py | MIT | 4,810 | d7a279c2d05db1c90c60e233b9e34456452de0ea | Python | py | |
r"""General purpose tensor functionals"""
import torch
import torch.fft as fft
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from typing import List, Tuple, Union
def channel_conv(
x: Tensor,
kernel: Tensor,
padding: int = 0, # Union[int, Tuple[int, ...]]
) -> Tensor:
... | piqa/utils/functional.py | MIT | 10,286 | 3aaf968de51d3a1d1d0cd74c836007cc9a54ac06 | Python | py | |
"""
Source code originally from SE(3)-Transformer (https://github.com/FabianFuchsML/se3-transformer-public/)
"""
import dgl
import numpy as np
import torch
from torch.utils.data import Dataset
DTYPE = np.float32
DTYPE_INT = np.int32
class QM9DGLDataset(Dataset):
"""QM9 dataset."""
num_bonds = 4
num_atom... | project/datasets/QM9/qm9_dgl_dataset.py | Apache-2.0 | 5,233 | 3aafb9b140fa287f97ae1bca849b8e5257018d92 | Python | py | |
# Copyright 2019 Toyota Research Institute. All rights reserved.
"""General-purpose class for rigid-body transformations.
"""
import cv2
import numpy as np
import torch
from pyquaternion import Quaternion
from dgp.proto import geometry_pb2
class BoundingBox3D:
"""3D bounding box (cuboid) that is centered at `po... | dgp/utils/geometry.py | MIT | 11,461 | e612cfb3322cf576e0fd6bc88b035d8b0fbde9fe | Python | py | |
import cv2
import torch
import tqdm
import os
import numpy as np
import h5py
import copy
from imageio import imread
import sys
from OurNet import HeatNet1
from OurNet import HeatNet2
from OurNet import ImNet1
from OurNet import ImNet2
from OurNet import BothNet1
from OurNet import BothNet2
from Trainer import Trainer... | classify.py | BSD-3-Clause | 13,958 | 343f97fe15d48e9f4efcb6cb52cfde8ccf3fd849 | Python | py | |
import logging
from typing import Dict, Any, Optional, Union
import torch
from allennlp.training.callbacks.log_writer import LogWriterCallback
logger = logging.getLogger(__name__)
class MetricsLoggerCallback(LogWriterCallback):
"""
Callback for logging metrics while training model.
"""
def _to_param... | common/callbacks.py | MIT | 1,036 | 3aafe803a7740c7c7ae179da978b0171b6db9cfa | Python | py | |
""" Utilities to build models.
Including -
- basic building blocks, e.g., conv3x3, conv1x1, etc.
"""
import functools
import os
import numpy as np
import torch
import torch.nn as nn
from thop import profile
from gumi.ops import GroupConv2d, MaskConv2d, MMPointwiseConv2d, SparseGroupConv2d
__all__ = ["conv3x3", "... | gumi/model_utils.py | MIT | 6,456 | 700342af92065259a495cc0f5cfdba715193fa2a | Python | py | |
import pytest
import torch
from torch.autograd import gradcheck
import kornia
import kornia.testing as utils # test utils
from kornia.testing import assert_close
class TestZCA:
@pytest.mark.parametrize("unbiased", [True, False])
def test_zca_unbiased(self, unbiased, device, dtype):
data = torch.ten... | test/enhance/test_zca.py | ECL-2.0,Apache-2.0 | 5,312 | 3ab014a3cc9a4eb8719deeedac6c345318617289 | 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... | run_lm_finetuning.py | Apache-2.0 | 32,974 | 3ab04388f901e954a1047f2a107e0b23bae4a3cc | Python | py | |
from model import common
from model import unet
import torch.nn as nn
import torch
def make_model(args, parent=False):
return A_net(args)
class A_net(nn.Module):
def __init__(self, args):
super(A_net, self).__init__()
self.args = args
m_unet = [unet.make_model(1, 1, ngf = args.n_feat... | code/model/A_net.py | MIT | 1,812 | a908b3c0665152878e351ab4df6c237fc0799354 | Python | py | |
from __future__ import print_function
import torch.utils.data as data
from PIL import Image
import os
import sys
import pickle
import numpy as np
import lmdb
import torch
from src.config import file_keys_pkl
class RecipeLoader(data.Dataset):
def __init__(self, data_path=None):
if data_path == Non... | solutions/im2recipe/src/data_loader.py | Apache-2.0 | 1,415 | fcef24908913dfee8f759d2b4af7fa6be8a825a2 | Python | py | |
import os
import copy
import time
import glob
import torch
import logging
from torch.utils.data import DataLoader
# define project dependency
import _init_paths
# project dependence
from common_pytorch.dataset.all_dataset import *
from common_pytorch.config_pytorch import update_config_from_file, update_config_from_... | infer.py | MIT | 3,443 | 4221606f975bd9199b9f86098a7a72f5816db28b | Python | py | |
import errno
import os
import numpy as np
import pandas as pd
from skimage import io, transform
import torch
from torch.utils.data import Dataset
class UserProfileModeDataset(Dataset):
def __init__(self, csv_file, transform=None):
items_padded = True
# Data sources
if not os.path.isfile(... | datasets/user_profile_mode.py | MIT | 1,910 | 3ab0689615e17e9c7855a0ce7f865027f67d8735 | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@file : bert_ontonotes_ner_dataset.py
@author: xiaoya li
@contact : xiaoya_li@shannonai.com
@date : 2021/01/20 16:40
@version: 1.0
@desc :
"""
import os
import torch
from torch.utils.data import Dataset
from tokenizers import BertWordPieceTokenizer
class BertOnto... | datasets/bert_ontonotes_ner_dataset.py | MIT | 4,347 | b2a018f4aa1518e6ffcc0a07434d48a11dab208e | Python | py | |
import torchvision
import random
import numpy as np
from PIL import Image, ImageStat, ImageOps, ImageFile
import pdb
from onconet.transformers.factory import RegisterImageTransformer
from onconet.transformers.abstract import Abstract_transformer
from onconet.utils.region_annotation import flip_region_coords_left_right,... | onconet/transformers/image.py | MIT | 13,232 | 1eb1149f0907f61097ec3eb44ada12e701aa0432 | Python | py | |
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
setup(
name='bpd_cuda',
ext_modules=[
CUDAExtension('bpd_cuda', [
'bpd_cuda.cpp',
'bpd_cuda_kernel.cu',
]),
],
cmdclass={
'build_ext': BuildExtens... | post_process/setup.py | Apache-2.0 | 331 | 3ab0dcfb38e66b5d483c824be668284285e4f4fc | Python | py | |
from models.base import ImplicitSurface, NeRF, RadianceNet
from utils import io_util, train_util, rend_util
from utils.logger import Logger
import copy
import functools
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
from collections import OrderedDict
import torch
import torch.nn as nn
impor... | models/frameworks/volsdf.py | MIT | 32,492 | 3ab115cbb62054114c89de688e8548aacfeeb06d | Python | py | |
import torch.nn as nn
from ..builder import CLASSIFIERS, build_backbone, build_head, build_neck
from .base import BaseClassifier
@CLASSIFIERS.register_module()
class ImageClassifier(BaseClassifier):
def __init__(self, backbone, neck=None, head=None, pretrained=None, frozen_backbone=True):
super(ImageCla... | mmcls/models/classifiers/image.py | Apache-2.0 | 2,100 | 3ab1389c298a5ed70105eec7168268a0a3b91d48 | Python | py | |
from __future__ import division
import os
import sys
import argparse
import json
import torch
import torch.nn as nn
from torch import cuda
import table
import table.Models
import table.ModelConstructor
import table.modules
from table.Utils import set_seed
import opts
# from tensorboard_logger import Logger
from path ... | wikisql/train.py | MIT | 6,239 | 3ab13aaf697c8f33e5ba37f35df3367846e8c935 | Python | py | |
# Authors: Zhaoshuo Li, Xingtong Liu, Francis X. Creighton, Russell H. Taylor, and Mathias Unberath
#
# Copyright (c) 2020. Johns Hopkins University - All rights reserved.
import os
import numpy as np
import torch.utils.data as data
from PIL import Image
from albumentations import Compose, OneOf
from natsort import... | dataset/scene_flow.py | Apache-2.0 | 9,679 | e6376817392040cd12c4cb53370561cfefdf17f5 | 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 torch... | tools/test_net.py | BSD-2-Clause | 3,580 | fddc42f74e3ba48c8e3f26ab675d5e0426764eb2 | Python | py | |
# coding=utf-8
# Copyright 2018 The OpenAI Team Authors and 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 copy of the License... | src/transformers/modeling_gpt2.py | Apache-2.0 | 41,022 | 3ab1660ae4fe542aebec1c4ab62673eab34934f0 | Python | py | |
import sys
import os
import time
import math
import copy
import importlib
import torch
import numpy as np
from matplotlib import pyplot as plt
def eval_acc(model, bx, by, bt):
model.eval()
accs = np.zeros(model.n_tasks, dtype=np.float32)
with torch.no_grad():
for task in np.unique(bt.data.cpu().n... | utils/plot1D.py | MIT | 8,307 | 104f1ce43812c6b45e38cbe7a499e879808cc745 | Python | py | |
import torch
import torch.nn as nn
import torchvision
import numpy as np
#from . import resnet, resnext, mobilenet, dpn, drn
from lib.nn import SynchronizedBatchNorm2d
import math
from collections import OrderedDict
'''
I have already implemented the classes SegmentationModuleBase,
SegmentationModule, and ModelBuilder... | models/models.py | BSD-3-Clause | 8,788 | 3ab182e3933b6dee7fd7f41bd9efb47a907c3c03 | Python | py | |
import torch
import numpy as np
from torch.autograd import Variable
import torch.optim as optim
import argparse
import random
import os
import models
import torchvision.utils as vutils
import utils
import dataLoader
import torch.nn as nn
from torch.utils.data import DataLoader
import math
import cv2
import torch.nn.fun... | PointCloud/outputMesh.py | MIT | 18,669 | 3ab19652bb939a6ffcf8dcf354c5eb40e9ea0555 | Python | py | |
import os
import pickle
import gym
import numpy as np
import torch
import torch.nn.functional as F
from gym.spaces.box import Box
from gym.wrappers.clip_action import ClipAction
from stable_baselines3.common.atari_wrappers import (ClipRewardEnv,
EpisodicLifeEnv,
... | il_offline_rl/envs.py | MIT | 13,693 | 3ab1a6aad4284398984af9823e4bd63950ae3ec6 | Python | py | |
import os
import re
import inflect
import torch
from tokenizers import Tokenizer
# Regular expression matching whitespace:
from unidecode import unidecode
_whitespace_re = re.compile(r'\s+')
# List of (regular expression, replacement) pairs for abbreviations:
_abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IG... | tortoise/utils/tokenizer.py | Apache-2.0 | 5,185 | 3ab1c31223c990e79a4e01fb1b7bb0996d0f66af | Python | py | |
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or ... | docs/source/conf.py | Apache-2.0 | 13,805 | dfd10440221460552eaaf2c18a007a5eb8be6f47 | Python | py | |
import torch
from catalyst_rl.utils import metrics
def test_iou():
size = 4
half_size = size // 2
shape = (1, 1, size, size)
# check 0: one empty
empty = torch.zeros(shape)
full = torch.ones(shape)
assert metrics.iou(empty, full, activation="none").item() == 0
# check 0: no overlap
... | catalyst_rl/utils/tests/test_iou.py | Apache-2.0 | 1,256 | 4b689b149836c73760b96967e54b9f5d91d93f7d | Python | py | |
"""
# This Conv64F network was designed following the practice of the following papers:
Revisiting Local Descriptor based Image-to-Class Measure for Few-shot Learning.
Wenbin Li, Lei Wang, Jinglin Xu, Jing Huo, Yang Gao and Jiebo Luo. In CVPR 2019.
https://github.com/WenbinLee/DN4/blob/master/models/network.py
"""
imp... | network/Embeddings/Conv64F.py | MIT | 2,573 | 3ab2189346bb1ac56c05ebc1535d84992935c5ad | Python | py | |
'''
Performs detection using models created with FAIRs Detectron2 Framework.
https://github.com/facebookresearch/detectron2
'''
import os
import torch
from detectron2.utils.logger import setup_logger
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
setup_logger()
with open(os.get... | detectors/detectron2.py | MIT | 2,938 | 3ab234b788bd21501d1f8e85f41c9f343cc5027d | Python | py | |
import torch
from collections import defaultdict, OrderedDict
from typing import Callable, Any, Dict, Tuple, Set, Optional, List
from torch.ao.quantization import QConfig
from torch.ao.quantization.qconfig import add_module_to_qconfig_obs_ctr, QConfigAny, qconfig_equals
from torch.ao.quantization.quantize import (
... | torch/ao/quantization/fx/qconfig_utils.py | Intel | 14,923 | ff874d47f68b89a4fb3255841adcfea2e33b40dd | Python | py | |
import os
import numpy as np
import torch
from torch.utils.data import Dataset
from torchvision.transforms import transforms
import collections
from PIL import Image
import csv
import random
import pandas as pd
import re
import random
class MiniImagenet(Dataset):
"""
put mini-imagenet files as :
root :
... | MiniImagenet_val.py | MIT | 9,786 | d737911957a90369bcb5be21ae4bb7644f5eb6d1 | Python | py | |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', type=int, default=32, help='input batch size')
parser.add_argument('--image_size', type=int, default=32, help='input image size')
parser.add_argument('--nz', type=int, default=100, help='size of the noise')
parser.add_argument('--n... | neural_nets/givemeagan/run.py | MIT | 5,816 | 10b1c3bbe1f912f6c43a06e0619b40f0ab6bb4a3 | Python | py | |
import os
import pdb
import random
import torch
from torch.utils.data import Dataset
import torchvision.transforms as transforms
import numpy as np
from PIL import Image, ImageDraw
from encoder import DataEncoder
#coco_label = ['person', 'bicycle', 'car', 'motorbike', 'aeroplane', 'bus', 'train', 'truck', 'boat', '... | datasets.py | Artistic-1.0-cl8 | 6,169 | 0392659b91d7418ee85ad4750cc3436028f2d610 | Python | py | |
# coding=utf-8
# @Time : 2020/12/3 11:53
# @Auto : zzf-jeff
import torch
import torch.optim as optim
import math
import numpy as np
from .builder import LR_SCHEDULER
from torch.optim.lr_scheduler import _LRScheduler
# class WarmUpLR(_LRScheduler):
# """warmup_training learning rate schedul... | torchocr/lr_schedulers/learning_rate.py | Apache-2.0 | 3,959 | d737d4c2c228ac3b703022a899f8fd204bd91088 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from dgl.nn.pytorch import GraphConv, HeteroGraphConv
from .GeneralGNNLayer import homo_layer_dict
class HeteroGeneralLayer(nn.Module):
"""
General wrapper for layers
"""
def __init__(self, name, rel_names, dim_in, dim_out, dropout, a... | openhgnn/layers/GeneralHGNNLayer.py | Apache-2.0 | 2,711 | 3ab2a9672f0c735a0a5fe269f3757d0871647a69 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.model_selection import GridSearchCV, StratifiedKFold
###############################################
# Mutual info Loss; adapted from https://github.com/fanyun-sun/InfoGraph
#############################################... | utils/losses.py | MIT | 7,908 | 3ab2ba1a0211f0585a0ba624349521e88ec965c9 | Python | py | |
import os
import torch
import torch.nn as nn
from dataset import Dataset
from architectures.architecture_pggan import PGGAN_D, PGGAN_G
from trainers.trainer import Trainer
from utils import save, load
dir_name = 'data/celeba'
basic_types = None
lr_D, lr_G = 0.001, 0.001
sz, nc, nz = 128, 3, 256
use_sigmoid = False
d... | train.py | MIT | 2,815 | 805448e7d9e0666782e73407c710ce6938966ba5 | Python | py | |
import torch
from torch import nn
from src import config
from src.utils import init_weights
class GeneratorModel(nn.Module):
def __init__(self):
super().__init__()
self.process = nn.Sequential(
nn.Linear(config.data.z_size, 512, bias=False),
nn.BatchNorm1d(512),
... | src/gan/wgan_hl/models/generator_model.py | MIT | 742 | 3ab2c0aa85cb71c4a1621a991236c074a0dde7bd | Python | py | |
import torch
import tqdm
def loss_fn(outputs, targets):
return torch.nn.BCEWithLogitsLoss()(outputs, targets)
def train(epoch, model, training_loader, device, optimizer, scheduler):
model.train()
for _,data in tqdm(enumerate(training_loader, 0), total=len(training_loader)):
ids_1 = data['ids_abstr... | roberta-dual-input/engine.py | MIT | 1,790 | 3ab321f31873792978641ca1348a76dd0a066e85 | Python | py | |
import torch, torchvision
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models.resnet import Bottleneck, conv1x1, conv3x3
import numpy as np
from functools import partial
from itertools import product, chain
from math import sqrt
from typing import List, Tuple, Optional
from torch import Tensor... | yolact_edge/yolact.py | MIT | 79,625 | 3ab323eb40d5752d2f94b176471368554a7d29e9 | Python | py | |
import torch
conf_mask = torch.FloatTensor([10.0, 1.0, 0.0, 1.0, 1.0])
conf_data = torch.FloatTensor([0.1, 0.9, 0.0, 0.2, 0.2])
loss_fn = torch.nn.MSELoss() # reduce=False, size_average=False)
x= loss_fn(conf_mask, conf_mask).item()
print(x) | shangtang/iou_test.py | MIT | 246 | 3afead80f992f44f6b29419aefd604226dba9c8b | Python | py | |
import os
import cv2
import torch
from PIL import Image
import numpy as np
import pickle
from torch.utils.data import Dataset
class IndoorDataset(Dataset):
def __init__(self, data_dir, dataset='', transform=None, zero_shot=False):
self.pics = sorted(os.listdir(data_dir))
self.data_dir = data_dir
... | lib/datasets.py | MIT | 2,008 | 3ab329b0d8960e5ec9daedfc093400d8db44c027 | Python | py | |
from typing import Optional
import numpy as np
import torch
def psd_numpy(
X: np.array,
mask: Optional[np.array],
multi_mask: bool = False,
normalize: bool = True,
eps: float = 1e-15
) -> np.array:
X_conj = np.conj(X)
psd_X = np.einsum("...cft,...eft->...ftce", X, X_co... | test/torchaudio_unittest/common_utils/psd_utils.py | BSD-2-Clause | 652 | 3ab3354672f336381ff3796a70da653b2a9d920e | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: Aruni RC
"""
import os
import sys
import copy
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def knn(x, k):
inner = -2*torch.matmul(x.transpose(2, 1), x)
xx = torch.sum(x**2, dim=1, keepdim=True)
... | models/dgcnn_seg2.py | MIT | 6,270 | fcce7e01484ca40f6d30bc6d9105cce0aab425a6 | Python | py | |
import os.path
import random
import torchvision.transforms as transforms
import torch
from data.base_dataset import BaseDataset
import glob
import numpy as np
from collections import namedtuple
server_ports = range(5550, 5558, 2)
from data.server import client
def make_dataset(data_path):
file_list = glob.glob(... | data/video_data.py | BSD-3-Clause | 1,789 | 5e7dd5b28e334ee047c1dd2b4fd3ab7ed812757b | Python | py | |
# pylint: disable=not-callable, no-member, invalid-name, line-too-long, unexpected-keyword-arg, too-many-lines, import-outside-toplevel
"""
Some functions related to SO3 and his usual representations
Using ZYZ Euler angles parametrisation
"""
import gc
import math
import os
from functools import lru_cache
import lie_... | e3nn/o3.py | MIT | 13,538 | 3ab359688c4ad6aad99f98380e7df92e78c7b36e | Python | py | |
'''
Author: jianzhnie
Date: 2022-01-04 15:59:42
LastEditTime: 2022-01-05 11:52:18
LastEditors: jianzhnie
Description:
'''
import sys
import torch
from torch import nn, optim
from torch.nn import functional as F
from torch.utils.data import DataLoader, Dataset
from tqdm.auto import tqdm
from nlptoolkit.data.utils.uti... | examples/sentence_polarity/mlp_sent_polarity.py | Apache-2.0 | 3,384 | 3ab369c6217cfb29c3d9586c9031ca9692fd59ea | Python | py | |
import numpy as np
from scipy.io.wavfile import read
import torch
def get_mask_from_lengths(lengths):
max_len = torch.max(lengths).item()
ids = torch.arange(0, max_len, out=torch.cuda.LongTensor(max_len))
mask = (ids < lengths.unsqueeze(1)).bool()
return mask
def load_wav_to_torch(full_path):
sa... | tts/utils.py | MIT | 1,026 | 3ab37b1056b5509136d7c80482dff5ca46b58a3d | Python | py | |
import math
import random
import mmcv
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmgen.models.architectures import PixelNorm
from mmgen.models.architectures.common import get_module_device
from mmgen.models.architectures.pggan import (EqualizedLRConvDownModule,
... | mmgen/models/architectures/stylegan/generator_discriminator_v1.py | Apache-2.0 | 19,197 | 3ab37c4605538b1e7d2f0b992e0e4c4226d909af | Python | py | |
import argparse
import base64
import json
import os
import random
import shutil
import time
import torch
import typing
from gym_fuzz1ng.coverage import Coverage
from torch.utils.data import Dataset
from utils.config import Config
from utils.log import Log
from utils.runner import Runner
class Pool:
def __init_... | utils/runs_db.py | MIT | 8,611 | 10235b0a8472c83d7bf46a9afbb8ad46286f3c66 | Python | py | |
import copy
import warnings
from collections import OrderedDict
from typing import List, Union
import numpy as np
import torch
__all__ = [
"normalize_image",
"channels_first",
"scale_intrinsics",
"pointquaternion_to_homogeneous",
"poses_to_transforms",
"create_label_image",
]
def normalize_i... | gradslam/datasets/datautils.py | MIT | 9,271 | 5e2f3f25ccb57970493f89ad40c9f26be18fa90a | Python | py | |
import os
from shutil import copyfile
from tqdm import tqdm
from argparse import ArgumentParser
from pprint import pformat
import random
import yaml
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch_transformers import GPT2LMHeadModel, GPT2Tokenizer
from models import GPT... | sampling_batch.py | Apache-2.0 | 10,162 | 3ab3d6e4cfa16bba3dc216d1e51b6fe9643af3ee | Python | py | |
# flake8: noqa
from torch.nn.modules import *
from .common import Flatten, GaussianNoise, Lambda, Normalize
from .lama import LamaPooling, TemporalAttentionPooling, TemporalConcatPooling
from .pooling import (
GlobalAttnPool2d,
GlobalAvgAttnPool2d,
GlobalAvgPool2d,
GlobalConcatAttnPool2d,
GlobalCon... | catalyst/contrib/nn/modules/__init__.py | Apache-2.0 | 457 | 3ab3e2941b6f403af41700077d7767ce4d038166 | Python | py | |
# Copyright 2022 Cisco Systems, 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 l... | lib/python/flame/examples/dist_mnist/trainer/pytorch/main.py | Apache-2.0 | 4,820 | 3ab3e52b68c51bbb7e5816c795b4be911db98d4b | Python | py | |
"""
Adapted from https://github.com/PyTorchLightning/pytorch-lightning/blob/master/tests/conftest.py.
See https://github.com/PyTorchLightning/pytorch-lightning/pull/661.
"""
from functools import wraps
import pytest
import torch.multiprocessing as mp
def pytest_configure(config):
config.addinivalue_line(
... | allennlp/tests/training/conftest.py | Apache-2.0 | 757 | e93bec8d50e21ad50e662cdf87a79d4c87fe0f2b | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
import torchvision as tv
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = nn.Conv2d(3, 32, 5)
#96-5+1=92
self.pool1 = nn.MaxPool2d(2,2)
#92/2=46
self.conv2 ... | model.py | MIT | 6,603 | 3ab403290c715be904957aa29e22fff8b078c888 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import importlib
import importlib.util
import logging
import numpy as np
import os
import random
import sys
from datetime import datetime
import torch
__all__ = ["seed_all_rng"]
TORCH_VERSION = tuple(int(x) for x in torch.__version_... | detectron2/utils/env.py | Apache-2.0 | 3,920 | 7035b13f47e157294400170b5e9678cc1845c9dd | Python | py | |
import argparse
import pickle
import os
import pandas as pd
import numpy as np
import itertools
import torch
from DEwNF.flows import inverted_conditional_planar_flow_factory
from DEwNF.utils import searchlog_day_split, get_split_idx_on_day, searchlog_semisup_day_split
from DEwNF.regularizers import NoiseRegularizer, r... | semisup_no_semi_searchlog_script_planar.py | MIT | 14,930 | 7c73c1c6360780de0dc15e9df068fc8fe8020f0e | Python | py | |
r"""
.. todo::
doc
"""
__all__ = [
"initial_parameter",
"summary"
]
from functools import reduce
import torch
import torch.nn as nn
import torch.nn.init as init
def initial_parameter(net, initial_method=None):
r"""A method used to initialize the weights of PyTorch models.
:param net: a PyTorch... | fastNLP/modules/utils.py | Apache-2.0 | 4,109 | 3ab4247e1790de6c132f3ef1ed6650b8b709aee0 | Python | py | |
import imageio
import logging
import os
from timeit import default_timer
from collections import defaultdict
from tqdm import trange
import torch
from torch.nn import functional as F
import sys
sys.path.append('/export/u1/homes/weichao/Workspace/disentangling-vae/')
from disvae.utils.modelIO import save_model
TRAI... | exp_var/training_var.py | MIT | 5,223 | 3ab42b263eb35c646ab4b179a9ef179d84c84203 | Python | py | |
# author: Jintao Huang
# date: 2020-5-14
# pred_image for train.py
import json
from models.efficientnet import efficientnet_b0, config_dict
import torch
from utils.display import resize_pad
from utils.utils import processing
import cv2 as cv
def pred_transform(image, target):
"""
:param image: ndarray[H, W,... | pred_image.py | Apache-2.0 | 1,556 | 8011fd549d16548d222c2781c9136e7aad3b6cdb | Python | py | |
import torch
#
torch.multiprocessing.set_sharing_strategy('file_system')
import pandas as pd
import numpy as np
import sys
import os
import pickle
import argparse
# local imports
import train_model
import experiment_routines as experiments
from subsetting_exp import subset_experiment
from dataset_chunking_fxns import... | code/scripts/cv_hyperparameter_search.py | BSD-3-Clause | 11,343 | 654b9cbaa87333af272f9303d1ac0110300211cf | Python | py | |
import config
import torch
class BERTDataset:
def __init__(self, review, target):
self.review = review
self.target = target
self.tokenizer = config.TOKENIZER
self.max_len = config.MAX_LEN
def __len__(self):
return len(self.review)
def __getitem__(self, item):
... | dataset.py | MIT | 1,022 | e90a0b0f74781ec50b175a0f52ddac223df7f850 | Python | py | |
import torch
import torch.nn as nn
from ..registry import LOSSES
from .utils import weighted_loss
@weighted_loss
def smooth_l1_loss(pred, target, beta=1.0, ts=1.0):
assert beta > 0
assert pred.size() == target.size() and target.numel() > 0
diff = torch.abs(pred - target) / ts
loss = torch.where(diff ... | mmdet/models/losses/smooth_l1_loss.py | Apache-2.0 | 1,353 | 52a7ee73e83f50255d61688949bb25a9cc4555a4 | Python | py | |
import gym
import torch
import torch.nn as nn
# from itertools import count
from torch.distributions import Bernoulli
import numpy as np
import torch.nn.functional as F
# from tensorboardX import SummaryWriter
from collections import deque
import random
device = torch.device("cuda:0" if torch.cuda.is_available() else ... | Actor-Critic/A2C.py | MIT | 4,412 | 3ab489232d3894d5f4ec2c86a24ff15322a3a324 | Python | py | |
from collections import OrderedDict
import numpy as np
import torch
import torch.nn as nn
class ConvBnRelu(nn.Module):
def __init__(self, in_planes, out_planes, ksize, stride, pad, dilation=1,
groups=1, has_bn=True, norm_layer=nn.BatchNorm2d, bn_eps=1e-5,
has_relu=True, inplace=... | seg/seg_block.py | MIT | 7,215 | fcd5684c4bd72503b6d5cba76e2b90c4be3337c2 | Python | py | |
from pathlib import Path
from typing import Optional
import torch
import yaml
from torch import Tensor, nn
from yukarin_sa.config import Config
from yukarin_sa.network.predictor import Predictor, create_predictor
from vv_core_inference.utility import remove_weight_norm, to_tensor
class WrapperUniGRU(nn.Module):
... | vv_core_inference/make_yukarin_sa_forwarder.py | MIT | 4,682 | 5e130bfbdef922a4d94e22d869b42e7ef7edbbe1 | Python | py | |
import os
import tqdm
import torch
import numpy as np
import matplotlib.pyplot as plt
from transformers import pipeline
from argparse import ArgumentParser
def get_device_int(device):
if device == 'cpu':
return -1
else:
return 0
def get_activation(model, source_sents, target_sents, device):... | paper/appendix/check_quantiles/check_quantiles.py | MIT | 4,154 | 3ab4979fd26abb5165ea3cac993dccc4a7f1a88d | Python | py | |
# Basic training configuration file
from pathlib import Path
from torch.optim import Adam
from torch.optim.lr_scheduler import ReduceLROnPlateau, MultiStepLR
from torchvision.transforms import RandomHorizontalFlip
from torchvision.transforms import RandomResizedCrop
from torchvision.transforms import ColorJitter, ToTen... | classification/imaterialist_challenge_furniture_2018/configs/train_squeezenet_350_bl_adam_resized_crop.py | MIT | 2,369 | 3ab4b5ec824956ef7b8e1572db42416bd1816e85 | Python | py | |
import numpy as np
import torch
class ResidualCoder(object):
def __init__(self, code_size=7, nusc=False, norm_velo=False, **kwargs):
super().__init__()
self.nusc = nusc
if self.nusc:
code_size = 9
self.code_size = code_size
self.norm_velo = norm_velo
@stati... | pcdet/utils/box_coder_utils.py | Apache-2.0 | 9,592 | 3ab4bc0f751a4e1da44aaf17a712c0f398477cc0 | Python | py | |
# Copyright 2019 Ross Wightman
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | built-in/PyTorch/Official/cv/image_classification/Gluon_ResNet50_v1c_for_PyTorch/timm/models/layers/separable_conv.py | Apache-2.0 | 3,147 | 1ebb85a567eb9d1755550e9ab65d2f1374d6cfd2 | Python | py | |
import argparse
import json
import os
import time
import ray
import requests
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from filelock import FileLock
from ray import serve, tune
from ray.util.ml_utils.node import force_on_current_node
from ray.util.sgd.torch import TorchTrainer, Tra... | release/golden_notebook_tests/workloads/torch_tune_serve_test.py | Apache-2.0 | 7,373 | 3ab4c4765e1f56005dccfbbf62342b31099942d1 | Python | py | |
#!/usr/bin/env python3
# This file is covered by the LICENSE file in the root of this project.
import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
import imp
import yaml
import time
from PIL import Image
import __init__ as boog... | src/tasks/semantic/modules/demo_user.py | BSD-2-Clause | 5,718 | 7ce732fc86e7590d284859aacd6c71be98822297 | Python | py | |
"""
visualize results for test image
"""
# https://github.com/WuJie1010/Facial-Expression-Recognition.Pytorch/blob/054107ce6ba9394ad5c4bed30dfa235df124c5a0/visualize.py
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import torch
import torch.nn as nn
import torch.nn.functional as F
i... | visualize_cpu.py | MIT | 3,349 | 3ab4d7d5a4e47a9c1d4fa623d3017ea40109d38f | Python | py | |
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable... | test/test_npu/test_network_ops/test_true_divide.py | BSD-3-Clause | 5,192 | 24f06fe4b555d5b73cfdff84cb3ac1890354a18e | Python | py | |
import torch.nn as nn
class BidirectionalLSTM(nn.Module):
def __init__(self, nIn, nHidden, nOut):
super(BidirectionalLSTM, self).__init__()
self.rnn = nn.LSTM(nIn, nHidden, bidirectional=True)
self.embedding = nn.Linear(nHidden * 2, nOut)
def forward(self, input):
recurrent,... | models/basic_crnn.py | MIT | 2,553 | d7903cbf54b535feaa914d5076f9dd159c4ac26f | Python | py | |
import torch
import torch.nn as nn
from torchvision.models.utils import load_state_dict_from_url
import ipdb
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
'wide_resnet50_2', 'wide_resnet101_2']
model_urls = {
'resn... | PA_DPC/backbone/resnet_2d.py | MIT | 14,204 | 3ab504c35e217f922d1ec400cad9c56c1269ebb3 | Python | py | |
# Copyright 2020 The MACE 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 la... | tools/python/transform/pytorch_converter.py | Apache-2.0 | 40,928 | 5ed65c30b7c0c96252c28096153b9c3fb226d950 | Python | py | |
"""
Description:
Author: Jiaqi Gu (jqgu@utexas.edu)
Date: 2021-06-06 23:37:55
LastEditors: Jiaqi Gu (jqgu@utexas.edu)
LastEditTime: 2021-06-06 23:37:55
"""
from typing import Any, Dict, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from pyutils.compute import gen_gaussian_nois... | torchonn/layers/mzi_conv2d.py | MIT | 40,641 | 4560ae8ac9f711e06445fe5bed453cfd09e3f10e | Python | py | |
# flake8: noqa
import os
import sys
import torch
from torch.utils.data import DataLoader, TensorDataset
from catalyst import dl
if os.getenv("USE_APEX", "0") != "0" or os.getenv("USE_DDP", "0") != "0":
sys.exit()
# sample data
num_samples, num_features, num_classes = int(1e4), int(1e1), 4
X = torch.rand(num_sa... | tests/_tests_scripts/dl_z_mvp_classification2.py | Apache-2.0 | 1,106 | 52cd7de4629bde61e3ce3b52f44ef875df7604b7 | Python | py | |
import torch
import torch as F
import torchvision
import numpy as np
import matplotlib.pyplot as plt
import os
import random
import cv2
def batch_transform(batch, transform):
"""Applies a transform to a batch of samples.
Keyword arguments:
- batch (): a batch os samples
- transform (callable): A funct... | utils.py | MIT | 5,173 | 3ab54551deef8ddbb48fbca9af0ebba22198739f | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
import torch.nn.functional as F
from mmdet.core import multi_apply
from torch import nn
from mmocr.models.builder import LOSSES
@LOSSES.register_module()
class BSLoss_tb(nn.Module):
"""The class for implementing FCENet loss.
FCE... | mmocr/models/textdet/losses/bs_loss_tb copy.py | Apache-2.0 | 6,032 | 4bae1ae2278748ba6d93ec2d9d0e1a055ca14ec5 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import List, Tuple
import hydra
import pytest
import torch
from hydra.experimental import compose, initialize
from mtrl.experiment import experiment
from mtrl.utils.types import EnvMetaDataType
from tests.agent.utils import get_metawo... | tests/agent/metaworld_test.py | MIT | 4,979 | 3ab56c869fd106486cdff1be6325e7b0ab659b0f | Python | py | |
"""
The `Information eXtraction from Images (IXI)`_
dataset contains "nearly 600 MR images from normal, healthy subjects",
including "T1, T2 and PD-weighted images,
MRA images and Diffusion-weighted images (15 directions)".
.. note ::
This data is made available under the
Creative Commons CC BY-SA 3.0 license... | torchio/datasets/ixi.py | MIT | 8,840 | 3ab5723a4043270ca211d601b30fa7d6ab435eba | Python | py | |
"""Utilities and tools for tracking runs with Weights & Biases."""
import json
import sys
from pathlib import Path
import torch
import yaml
from tqdm import tqdm
sys.path.append(str(Path(__file__).parent.parent.parent)) # add utils/ to path
from utils.datasets import LoadImagesAndLabels
from utils.datasets import im... | PyTorch/yolov3/utils/wandb_logging/wandb_utils.py | MIT | 16,894 | 12bd320cc30ae17917de9cf332c0f303ff8b4338 | Python | py | |
from SemiSupervisedLearning import visualisations
import matplotlib.pyplot as plt
import numpy as np
import torch
import pathlib
def to_cuda(elements):
"""
Transfers every object in elements to GPU VRAM if available.
elements can be a object or list/tuple of objects
"""
if torch.cuda.is_availabl... | GenerativeModelling/utils.py | MIT | 5,873 | 3ab58615e5fff1c0d0844da0b8e404941d0e0d0d | Python | py | |
import unittest
import numpy as np
import torch
from fastNLP import DataSetIter, TorchLoaderIter
from fastNLP import DataSet
from fastNLP import Instance
from fastNLP import SequentialSampler, ConstantTokenNumSampler
from fastNLP import ConcatCollateFn
def generate_fake_dataset(num_samples=1000):
"""
产生的Dat... | tests/core/test_batch.py | Apache-2.0 | 19,862 | 1e2188009563c793072c7a409ab89103e235f9c7 | Python | py | |
import os
import time
import torch
import numpy as np
import inspect
from contextlib import contextmanager
import subprocess
def int_tuple(s):
return tuple(int(i) for i in s.split(','))
def find_nan(variable, var_name):
variable_n = variable.data.cpu().numpy()
if np.isnan(variable_n).any():
exit... | Attention-based/AGTransformer/utils.py | MIT | 2,533 | 3ab59277c50f30604ecb2616d02eed6214654d3e | Python | py | |
import torch
from torch import nn
import torch.nn.functional as F
class AIRLDiscrim(nn.Module):
def __init__(self, image_shape, state_shape, gamma):
super().__init__()
state_shape = state_shape[0]
h, w, c = image_shape
self.g_cnn = nn.Sequential(
nn.Conv2d(in_channel... | python/utils/networks/discriminator.py | MIT | 4,417 | 708a558a1bba472f14bba5ceea7b84a793bf61ec | Python | py | |
import json
import logging
import math
import os
import re
import socket
from collections import defaultdict, Counter
from datetime import datetime
from os import mkdir, makedirs, getpid
from time import perf_counter
import h5py
import torch
from numbers import Number
from os.path import join, exists, dirname
from typ... | gpv2/train/trainer.py | Apache-2.0 | 39,551 | 456af96a2dbb3a70efccc521ba8b65dccf8c4fc8 | Python | py | |
""" Classifier head and layer factory
Hacked together by / Copyright 2020 Ross Wightman
"""
from torch import nn as nn
from torch.nn import functional as F
from .adaptive_avgmax_pool import SelectAdaptivePool2d
def create_classifier(num_features, num_classes, pool_type='avg', use_conv=False):
flatten = not use_... | timm/models/layers/classifier.py | Apache-2.0 | 1,616 | e9194f054e4f1fa4b5d552d201b98cb724d49227 | Python | py | |
# Copyright 2020 Ross Wightman
# Various utility functions
import torch
import torch.nn as nn
from functools import partial
import math
import warnings
import torch.nn.functional as F
from timesformer.models.helpers import load_pretrained
from .build import MODEL_REGISTRY
from itertools import repeat
# from torch._si... | timesformer/models/vit_utils.py | Apache-2.0 | 6,528 | 340b81559cc8b2f50db42bece9ad34a1f46f6b6f | Python | py | |
# reference: https://github.com/Sanbongawa/binary_swarm_intelligence
import math
import torch
import tqdm
@torch.no_grad()
def bba(func, x0=None, n=200, maxiter=2000, topk=100, is_min=True, fmin=0, fmax=2, loud_A=0.25, r0=0.4, alpha=0.999, gamma=10., progress=False):
"""
Binary Bat Algorithm
input:{ fun... | fluid_coarse/bba.py | MIT | 3,255 | fd9f22bcc36f63605e7f2a174089ce88bb2dda89 | Python | py | |
import os
import torch
from torchtext.data import Field
from onmt.inputters.datareader_base import DataReaderBase
try:
import numpy as np
except ImportError:
np = None
class VecDataReader(DataReaderBase):
"""Read feature vector data from disk.
Raises:
onmt.inputters.datareader_base.MissingD... | onmt/inputters/vec_dataset.py | MIT | 5,465 | 3ab6454fc5a124fa1301df1261587553dfe8a1c7 | 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/training/network_training/nnUNet_variants/architectural_variants/nnUNetTrainerV2_LReLU_slope_2en1.py | Apache-2.0 | 2,221 | 5ec0d2296f7dfa6ad7d1ffd517a020f3d5b9c65d | Python | py | |
import torch
from mmdet.core import bbox2result, bbox_mapping_back, multiclass_nms
from ..builder import DETECTORS
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class GFL(SingleStageDetector):
def __init__(self,
backbone,
neck,
bbox... | mmdet/models/detectors/gfl.py | Apache-2.0 | 3,407 | f9a47049a765a704adca576ae27c606837fdb1e9 | Python | py | |
import torch
import torch.nn as nn
class LayerNorm(nn.Module):
"""
Layer Normalization
(https://arxiv.org/abs/1607.06450)
"""
def __init__(self, normalized_shape, eps=1e-5):
super(LayerNorm, self).__init__()
self.gamma = nn.Parameter(torch.ones(normalized_shape))
self.beta... | models/claf/modules/layer/normalization.py | MIT | 565 | 3ab6b2939e007363727b1549da58e3124582cda8 | Python | py | |
import numpy as np
import torch
from dataclasses import dataclass
from typing import List
from jiant.tasks.core import (
BaseExample,
BaseTokenizedExample,
BaseDataRow,
BatchMixin,
Task,
TaskTypes,
)
from jiant.tasks.lib.templates.shared import (
construct_double_input_tokens_and_segment_id... | jiant/jiant/tasks/lib/stsb.py | MIT | 3,148 | 653046f911e285e9cf81b79981cbc8bcf07bc553 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.