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 os import os.path as osp import numpy as np import torch from sklearn.preprocessing import StandardScaler from sklearn.model_selection import GridSearchCV from skorch import NeuralNetRegressor from torch.optim.lr_scheduler import StepLR from skorch.callbacks.lr_scheduler import LRScheduler from classicalgsg...
examples/mmff94/train_models.py
MIT
3,471
fdf133d84931286806f6504e1dc9c352218d12e1
Python
py
# encoding:utf-8 ''' @Author: catnlp @Email: wk_nlp@163.com @Time: 2018/5/21 18:23 ''' from NER.utils.config import Config from NER.utils.helpers import * import sys import argparse import random import torch import numpy as np seed_num = 100 random.seed(seed_num) torch.manual_seed(seed_num) np.random.seed(seed_num) ...
NER/Tests/group/cc/train_joint-cc.py
MIT
4,442
a94fe4509e4a67bda35b2e2e1c86590fa2535014
Python
py
import traceback import sys import logging import os import time import subprocess import socket import json import torch from contextlib import closing from carla08.tcp import TCPConnectionError from carla08.driving_benchmark import run_driving_benchmark from drive import CoILAgent from logger import coil_logger...
coil_core/run_drive.py
MIT
12,130
650a11832b2703bdabe15a872a03e20d25dffb3e
Python
py
# Author: Yan Zhang # Email: zhangyan.cse (@) gmail.com import sys import numpy as np import matplotlib.pyplot as plt import pickle import os import gzip import model from torch.utils import data import torch import torch.optim as optim from torch.autograd import Variable from time import gmtime, strftime import sys...
src/testConvNet.py
MIT
3,639
8b45b86b3b0b09671417b191eb953207d6048dab
Python
py
import math import torch.nn as nn import torch.nn.functional as F import torch from timm.models.layers import variance_scaling_ def make_cross_attention_mask(query_mask, kv_mask): batch_size, query_len = query_mask.shape _, key_len = kv_mask.shape mask = torch.einsum("bi,bj->bij", (query_mask, kv_mask))...
perceiver_io/transformer_primitives.py
Apache-2.0
16,840
fcd93b3e87d8ab9c82d977776fc09c3ef4271491
Python
py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from model.base_module import BaseModule from model.paragraph_module import ParagraphModule from model.image_module import ImageModule import math class CrossModalModule(BaseModule): def __init__(self, config, encoder):...
model/cross_modal_module.py
MIT
5,178
e62d0f597db2912823b80142c0b43368fed7f49d
Python
py
""" Meta-learning Omniglot and mini-imagenet experiments with iMAML-GD (see [1] for more details). The code is quite simple and easy to read thanks to the following two libraries which need both to be installed. - higher: https://github.com/facebookresearch/higher (used to get stateless version of torch nn.Module-s) -...
examples/iMAML.py
MIT
11,822
8b45e71146436ec4eea05332d3b3a0c54f90d3c2
Python
py
# Copyright 2020 MONAI Consortium # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, s...
monai/networks/blocks/segresnet_block.py
Apache-2.0
4,322
4b6fd132037b53556b403588b1ebe0040a52f179
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. """ Create a FAISS Index with a series of dense embeddings. """ import os import random import torch from typing import L...
parlai/agents/rag/scripts/index_dense_embeddings.py
MIT
4,832
10b32be640f4a4e965fd6f5de2f749f58a73558c
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math import torch import torch.nn.functional as F from fairseq import utils from fairseq.criterions import FairseqCriterion,...
fairseq/examples/rxf/rxf_src/sentence_prediction_r3f.py
MIT
6,685
801ee2dfd2c1c4bfae07c5fecc651ae41a8fb36e
Python
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from model.utils.config import cfg from model.faster_rcnn.faster_rcnn_MEAA import _fasterRCNN import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import mat...
lib/model/faster_rcnn/resnet_MEAA.py
MIT
31,362
4ba4cf229d44a302d4a1a1dbeedd1383a4e76909
Python
py
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author: Donny You(youansheng@gmail.com) from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch.nn as nn from models.backbones.densenet.densenet_models import DenseNetModels class NormalDensenetBackbone...
models/backbones/densenet/densenet_backbone.py
Apache-2.0
6,487
8b463593cc096189d2c276e8d3aef2d8264ca23c
Python
py
import math import multiprocessing as mp import matplotlib.pyplot as plt import torch import torch.nn.functional as F import torch.optim as optim from trainer.start import * from data.nih14 import * from data.vin import * from data.voc import * from model.baseline import * from model.fpn import * from pylon import * ...
utils/exp_base.py
Apache-2.0
13,086
fcbe4a2399d419ed7cc5ab1a93d049f8e7851eee
Python
py
import re from copy import deepcopy import torch from torch import nn as nn from .conv2d_helpers import * # Default args for PyTorch BN impl _BN_MOMENTUM_PT_DEFAULT = 0.1 _BN_EPS_PT_DEFAULT = 1e-5 BN_ARGS_PT = dict(momentum=_BN_MOMENTUM_PT_DEFAULT, eps=_BN_EPS_PT_DEFAULT) def round_channels(channels, depth_multipli...
gen_efficientnet/efficientnet_builder.py
Apache-2.0
19,184
8b464d2ca755b028f700a993df57c0a8096c6438
Python
py
# ------------------------------------------------------------------------------ # Portions of this code are from # CornerNet (https://github.com/princeton-vl/CornerNet) # Copyright (c) 2018, University of Michigan # Licensed under the BSD 3-Clause License # -------------------------------------------------------------...
src/lib/models/losses.py
MIT
8,108
12a8548a6ef29c9273b43d5f96679900bddb3386
Python
py
""" This script is ported from https://github.com/MadryLab/robustness branch: master commit: 54f3375e428ad9a9ba4501dbbb3030f141e2ff78 """ import torch import torch.nn as nn import torch.nn.functional as F __all__ = ['resnet50'] # https://github.com/MadryLab/robustness only provide pre-trained models for resnet50 c...
policy_driven_attack/models/victim/cifar/madry_resnet.py
Apache-2.0
4,745
45d34af65e44ec061b31ecef48f06df419ae3436
Python
py
#!/usr/bin/env python # encoding: utf-8 """ @Author: yangwenhao @Contact: 874681044@qq.com @Software: PyCharm @File: test_accuracy.py @Time: 19-8-6 下午1:29 @Overview: Train the resnet 10 with asoftmax. """ from __future__ import print_function import argparse import os import sys import time # Version conflict import ...
TrainAndTest/test_egs_multi.py
MIT
29,231
5f78b17a1b6fea8a12cb38edb3c35a4299c983bb
Python
py
from typing import Optional, Any from warnings import warn import torch import torch.autograd as autograd import torch.distributed as distributed from torch.autograd.function import once_differentiable from . import backend def _activation_from_name(activation): if activation == "leaky_relu": return bac...
modules/functions.py
BSD-3-Clause
10,911
4b5564b3bd01ebce17f89d0d7d54aacb31f7a7da
Python
py
import torch import torch.nn as nn from collections import defaultdict from copy import deepcopy from math import log2 from ..utils import ConvModule, build_module from .registry import BRICKS FUSION_METHODS = ('concat', 'add') @BRICKS.register_module class JunctionBlock(nn.Module): """JunctionBlock A basic...
vedaseg/models/decoders/bricks.py
Apache-2.0
7,125
5fb2ce38b0ccea34cf0784b2cb3e64923c14b5ae
Python
py
import argparse from model_vc import Generator import matplotlib.pyplot as plt import torch from torch_utils import device from data_loader_circular import get_loader def show_melsp(tensor, title): fig = plt.figure(title) plt.imshow(tensor.detach().cpu().reshape((128,80)).numpy().T, cmap='viridis') if __name_...
visualizer.py
MIT
2,229
8b46fe47108113c123c0001e48d32de4d09b0eac
Python
py
"""Create model.""" # coding=utf-8 # # /************************************************************************************ # *** # *** Copyright 2020-2022 Dell(18588220928@163.com), All Rights Reserved. # *** # *** File Author: Dell, 2020年 09月 09日 星期三 23:56:45 CST # *** # ***************************************...
project/image_clean/clean.py
MIT
5,442
8b472e4fb51b5d3f78bbd61bf7177bb2778be9b3
Python
py
import numpy as np import os from PIL import Image from torch.utils.data import Dataset class Dataloader(Dataset): def __init__(self, image_dir, mask_dir, transform=None): self.image_dir = image_dir self.mask_dir = mask_dir self.transform = transform self.images = os.listdir(image_...
cv_segmentation/u-net_architecture/dataset.py
MIT
949
b216a76c9538ec40915e33cf847d6049ef3c67e8
Python
py
import torch from torch import nn from smoke.modeling.smoke_coder import SMOKECoder from smoke.layers.utils import ( nms_hm, select_topk, select_point_of_interest, ) class PostProcessor(nn.Module): def __init__(self, smoker_coder, reg_head, det_thres...
smoke/modeling/heads/smoke_head/inference.py
MIT
3,953
b25e2b9e0c9032d7e8d3b168e8135ae234c2cd15
Python
py
import copy import os from PIL import Image import tqdm import torch import torch.utils.data import torchvision from pycocotools import mask as coco_mask from pycocotools.coco import COCO import baseline.transforms as T class FilterAndRemapCocoCategories(object): def __init__(self, categories, remap=True): ...
object-detection/baseline/coco_utils.py
BSD-3-Clause
9,420
ff3acac4e77c9756789566b1db54230305c8eb9f
Python
py
import logging import math from typing import Any, Dict, List, Tuple import torch import torch.nn.functional as F from overrides import overrides from allennlp.data import TextFieldTensors, Vocabulary from allennlp.models.model import Model from allennlp.modules.token_embedders import Embedding from allennlp.modules ...
allennlp/allennlp/models/coreference_resolution/coref.py
MIT
31,342
d7295bcf571cb3bac4a8d5b2e546d66428684675
Python
py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from botorch import fit_gpytorch_model from botorch.models.contextual import LCEAGP, SACGP from botorch...
test/models/test_contextual.py
MIT
3,970
7c9c40b482e4086573284552cff1b3f5f5b62547
Python
py
import argparse import glob import json import logging import os import random import math import onnx import onnx.numpy_helper import numpy as np import torch # from torch.functional import norm import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader, RandomSampler, SequentialS...
inference/nni_onnx_map.py
MIT
7,839
8b47ab53f9efca0a3ace2d0cd2ca1ea7a501c41f
Python
py
import logging from typing import Dict, List, Tuple from overrides import overrides import torch from allennlp.data.fields.production_rule_field import ProductionRuleArray from allennlp.data.vocabulary import Vocabulary from allennlp.models.model import Model from allennlp.modules import TextFieldEmbedder, Seq2SeqEn...
allennlp/models/semantic_parsing/nlvr/nlvr_semantic_parser.py
Apache-2.0
12,119
704ef6994d40655b418bcce9448c4a5d9bcda8d1
Python
py
import random import os import numpy as np from PIL import Image from collections import defaultdict import torch from torch.utils.data.dataloader import default_collate import torchvision.transforms as transforms import torch.utils.data as data from input_pipelines import colmap_utils def _collate_fn(batch): _...
input_pipelines/llff/nerf_dataset.py
MIT
10,341
dfc7929eefba3cf5007cc04a552e0d1e9ea0158b
Python
py
import argparse import os import sys import mmcv from mmcv import DictAction from torchvision import utils # yapf: disable sys.path.append(os.path.abspath(os.path.join(__file__, '../..'))) # isort:skip # noqa from mmgen.apis import init_model, sample_uncoditional_model # isort:skip # noqa # yapf: enable def pa...
demo/unconditional_demo.py
Apache-2.0
2,349
34107c1f70ac3725755340e450cfbd9787a64682
Python
py
""" This file handles the details of the loss function during training. This includes: LossComputeBase and the standard NMTLossCompute, and sharded loss compute stuff. """ from __future__ import division import torch import torch.nn as nn from torch.autograd import Variable import onmt import onmt.io ...
onmt/Loss.py
MIT
10,819
8b47d9542d53beb880aac49d2470abdc6b16caf1
Python
py
import os import sys sys.path.append(os.path.dirname(sys.path[0])) import torch.nn as nn import torch.nn.functional as F from torch_geometric.nn import RGCNConv, FastRGCNConv '''Model skeleton for creating custom scene graph learning models''' class CustomGraphModel(nn.Module): def __init__(self, config): ...
roadscene2vec/learning/model/graph_model_skeleton.py
MIT
2,262
8b47f1684875f895dc68f6161cf9a27ad19a4dcd
Python
py
try: import binutil # required to import from dreamcoder modules except ModuleNotFoundError: import bin.binutil # alt import if called as module from json.decoder import JSONDecodeError from syntax_robustfill import SyntaxCheckingRobustFill from image_robustfill import Image_RobustFill import time from dream...
bin/rbBaseline.py
Unlicense
19,602
8b480e93f11ea0a7a71921fb5265968d8ab0c998
Python
py
# python frozen.py --model_path scratch/frozen_bert --train --dump_path scratch/dump_bert --verbose --num_runs 100 --num_workers 4 --gpu 4 # python frozen.py --model_path scratch/frozen_glove --train --dump_path scratch/dump_word_embeddings_glove --verbose --num_runs 100 --num_workers 4 --gpu 5 import argparse import ...
frozen.py
MIT
6,277
f9669848cca6cb98e0f87d3d366b058878169815
Python
py
import logging import time import os import sys from argparse import ArgumentParser import baseline from torch.nn.parallel import DistributedDataParallel from torch.utils.data import DataLoader from eight_mile.utils import str2bool, write_json, Average, Timer, get_num_gpus_multiworker from baseline.pytorch.embeddings i...
mead/api_examples/pretrain_paired_pytorch.py
Apache-2.0
19,620
e95bca66d49813d57a72ac5e43b4a485cdf5f572
Python
py
import math import torch import logging import numpy as np from tqdm import tqdm import torch.nn as nn import multiprocessing from os.path import join from datetime import datetime from torch.utils.data.dataloader import DataLoader torch.backends.cudnn.benchmark= True # Provides a speedup import util import test imp...
train.py
MIT
7,512
5ed656a407d12bab933f1d7fe2a78a419894ebd0
Python
py
import torch import torch.nn as nn from abc import ABC from abc import abstractmethod from pathlib import Path class Model(nn.Module, ABC): # Must be implemented. @abstractmethod def get_args(self): return [] def save(self, path, word_index): path = Path(path) path.parent.mkdir(exist_ok=True, par...
autowordbug/base_models/model.py
MIT
856
5eba97655b7b3b596427ef4642e37e8bd02fe837
Python
py
import torch from rlpyt.algos.pg.base import PolicyGradientAlgo, OptInfo from rlpyt.agents.base import AgentInputs, AgentInputsRnn from rlpyt.utils.tensor import valid_mean from rlpyt.utils.quick_args import save__init__args from rlpyt.utils.buffer import buffer_to, buffer_method from rlpyt.utils.collections import n...
rlpyt/algos/pg/ppo.py
MIT
5,397
8b487f7ab5b757eafe62794c8ad877820c42758c
Python
py
# Based on https://github.com/huggingface/transformers/blob/master/src/transformers/models/bert/modeling_bert.py """PyTorch Temporal BERT model""" import math import torch import torch.utils.checkpoint import utils from models.tempobert.configuration_tempobert import TempoBertConfig from packaging import version fro...
models/tempobert/modeling_tempobert.py
MIT
56,530
1046babb8c3850ca50fce8ccaa1c7e1ffc6e6c1c
Python
py
import os import logging import numpy as np from PIL import Image from scipy.ndimage import convolve1d from torch.utils import data import torchvision.transforms as transforms from utils import get_lds_kernel_window print = logging.info class AgeDB(data.Dataset): def __init__(self, df, data_dir, img_size, split...
agedb-dir/datasets.py
MIT
3,488
b24f4ac2466cb12bc4acda42ddd17dae6d7e02d0
Python
py
from __future__ import print_function import sys import time import torch from torchvision import datasets, transforms import os import dataset import random import math import numpy as np from utils import get_all_boxes, multi_bbox_ious, nms, read_data_cfg, logging from cfg import parse_cfg from darknet import Darknet...
eval.py
MIT
4,606
8b489b37aaa277370c9580008d1ba31e49036df4
Python
py
from pathlib import Path from collections import OrderedDict # import gpustat import torch from torch import autograd import torch.nn.init as init from torchvision import transforms, datasets from torch.autograd import grad from models.wgan import * def mkdir_path(path): path.mkdir(parents=True, exist_ok=True) ...
training_utils.py
MIT
3,402
e98ca720e97924134867cffd5f86b6551274dec9
Python
py
import torch from torch_sparse import coalesce from torch_geometric.read import parse_txt_array from torch_geometric.utils import one_hot from torch_geometric.data import Data elems = {'H': 0, 'C': 1, 'N': 2, 'O': 3, 'F': 4} def parse_sdf(src): src = src.split('\n')[3:] num_atoms, num_bonds = [int(item) for ...
torch_geometric/read/sdf.py
MIT
1,213
8b48f745a07611f2b082571dd651fe315703a368
Python
py
import numpy as np import torch import torch.nn as nn from mmcv.cnn import ConvModule, bias_init_with_prob, normal_init from mmdet.core import (build_anchor_generator, build_assigner, build_bbox_coder, build_sampler, force_fp32, images_to_levels, multi_apply, multiclass_...
mmdet/models/dense_heads/sabl_retina_head.py
Apache-2.0
27,068
ff1471f7f2c1247733415622fa17f05decf34359
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Backbone modules. """ from collections import OrderedDict import os import torch import torch.nn.functional as F import torchvision from torch import nn from torchvision.models._utils import IntermediateLayerGetter from typing import Dict, List...
models/backbone.py
Apache-2.0
9,547
f9a84236d09bb8b64cea330c2a38530fdf6003c0
Python
py
import unittest import os from torchvision.datasets import ImageFolder from torch._utils_internal import get_file_path_2 def mock_transform(return_value, arg_list): def mock(arg): arg_list.append(arg) return return_value return mock class Tester(unittest.TestCase): root = os.path.normp...
test/test_folder.py
BSD-3-Clause
3,467
8b49518b419036c7456ce1ca76c0d638993b6db9
Python
py
import warnings import matplotlib.pyplot as plt import mmcv import numpy as np import torch from mmcv.parallel import collate, scatter from mmcv.runner import load_checkpoint from mmcls.datasets.pipelines import Compose from mmcls.models import build_classifier def init_model(config, checkpoint=None, device='cuda:0'...
mmcls/apis/inference.py
Apache-2.0
5,678
4584ffc4df24d7f6427b34beeeff8824cd86f93d
Python
py
# Owner(s): ["module: tests"] import torch import numpy as np import math from typing import Dict, List, Sequence import random from functools import partial from itertools import product, combinations, permutations import warnings from torch._six import inf, nan from torch.testing import make_tensor from torch.test...
test/test_reductions.py
Intel
160,475
52c0a8a1d25785e9b65c830364bfec888e660fac
Python
py
import copy import logging import numpy as np import torch from torch.utils.data import DataLoader from utils.toolkit import tensor2numpy from scipy.spatial.distance import cdist EPSILON = 1e-8 batch_size = 64 class BaseLearner(object): def __init__(self): self._cur_task = -1 self._known_classes ...
LLLClassify-part/models/base.py
MIT
10,414
3402ea3bb5b383f0a695ad4c7ec4541bbf6e15bf
Python
py
import numpy as np import os,sys,time import torch import torch.nn.functional as torch_F import torchvision import torchvision.transforms.functional as torchvision_F import tqdm from easydict import EasyDict as edict import matplotlib.pyplot as plt import lpips import util_vis import camera """ nerf.py의 novel_pose pl...
visualization_novel_view.py
MIT
6,064
8b4976e20464e6fd063d31cf2420f55d531cc247
Python
py
from __future__ import print_function import os import argparse import torch import torch.backends.cudnn as cudnn import numpy as np from data import cfg_mnet, cfg_slim, cfg_rfb from layers.functions.prior_box import PriorBox from utils.nms.py_cpu_nms import py_cpu_nms import cv2 from models.retinaface import RetinaFac...
convert_to_onnx.py
MIT
3,875
8b49775f49506eb66a1fe11f6702ffa8cc3d85bf
Python
py
from torchvision import transforms from src.datasets.cifar10 import CIFAR10 from src.datasets.imagenet import ImageNet from src.datasets.wikipedia import WIKIPEDIA, WIKIPEDIATwoViews from src.datasets.wikipedia_val import WIKIPEDIAVAL from src.datasets.newsgroup import NEWSGROUP from src.datasets.slice import WIKIPEDIA...
src/datasets/datasets.py
MIT
1,687
8b49862079a15a3a7bf7115f08d401a51ca3a8cb
Python
py
# coding=utf-8 import math import torch from torch.nn.modules import Module from torch.nn.modules.utils import _single, _pair, _triple from torch.nn import init from torch.nn import Parameter class ConvNd(Module): __constants__ = ['stride', 'padding', 'dilation', 'groups', 'bias', 'padding_m...
fourier_conv.py
Apache-2.0
7,505
4b97e1c84ea350382227f7a1c7fbe217dd6312a2
Python
py
from flask import Flask, render_template, request,Response import requests from werkzeug import secure_filename app = Flask(__name__,template_folder='templates/') DIST = ["Hotdog", "Not hotdog"] from torchvision import transforms import io,base64 from PIL import Image import torch,json transform = transforms.Compose([...
BLOX/Examples/NotHotdog/server.py
Apache-2.0
1,526
101e3d88953e0fc727a39f387e3e1d5b9b080203
Python
py
import torch.nn as nn class AgentConvBlock(nn.Module): def __init__(self, nin, nout, ksize=3): super(AgentConvBlock, self).__init__() self.conv1 = nn.Conv2d(nin, nout, ksize, padding=1) self.lrelu1 = nn.LeakyReLU(0.2) self.conv2 = nn.Conv2d(nout, nout, ksize, padding=1) sel...
dsketch/models/sketch_net.py
BSD-3-Clause
2,014
6b3b641d931985add5f1bd74bedab6b117b10345
Python
py
#!/usr/local/bin/env python import torch from torch.autograd import Variable import torch.nn.functional as F from tqdm import tqdm from scipy.stats import linregress import numpy as np from sklearn import metrics class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, sel...
ODO/discriminator/model.py
MIT
2,753
dfb65475b0557a808904ecda154d7aea4182df59
Python
py
""" Calculates PSNR for JPG with respect to a dataset. Note: Currently hard-coded for Cifar10 """ import sys import os sys.path.append(os.path.abspath('..')) import argparse import numpy as np import torch import cv2 from collections import namedtuple from PIL import Image from tqdm import tqdm from utils import util_...
scripts/calculate_jpg_psnr.py
MIT
3,144
f992d724a49b68a640fbc669989450a0840a851e
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import math import numpy as np from typing import List import torch from fvcore.nn import sigmoid_focal_loss_jit, smooth_l1_loss from torch import nn from torch.nn import functional as F from detectron2.data.detection_utils import convert_image_to_...
detectron2/modeling/meta_arch/retinanet.py
Apache-2.0
19,618
e6638a89e847935cd25cdbae497c2cfb55e39430
Python
py
import os import re import json import sys import csv import math import shutil import argparse import torch import random import subprocess from utility_functions import taskManager import pandas as pd import scipy.io as sio from PIL import Image as PILImage import matplotlib.pyplot as plt import matplotlib.cm as cmx ...
taskCreator.py
RSA-MD
72,472
b25d12b1b4b57921e6039f7c915099fcc7101c4d
Python
py
import torch.nn as nn import numpy as np import torch.nn.utils.spectral_norm as spectral_norm import torch.nn.functional as F from .base_network import BaseNetwork from .sync_batchnorm import SynchronizedBatchNorm2d from .normalization import get_nonspade_norm_layer from ...util import util import torch from torch.util...
projects/data_generation/synthetic_multi_view_facial_image_generation/algorithm/Rotate_and_Render/models/networks/discriminator.py
Apache-2.0
12,171
28dbb5baa7e034df6b26c8277f53924f987469b6
Python
py
import argparse import math import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import random import scipy.io as sio import sys import time import torch from numpy import dot from scipy.stats import levy_stable from tqdm import tqdm import torch.nn as nn import copy import torch.nn.funct...
geometry_analysis/levy_geometry.py
MIT
7,893
24b39ebc24862b244cfd9b8d128fd1e32afd3e6a
Python
py
import math import torch import torch.nn as nn from torch import Tensor class PositionalEncoding(nn.Module): """ Encodes positional information into word embeddings. Reference: https://naokishibuya.medium.com/positional-encoding-286800cce437 """ def __init__(self, max_positions: int, dim_embed: int, ...
simple_transformer/modules/pos_encoding.py
MIT
1,909
704e4efb8047c934fc7cd93191480ce924891663
Python
py
import torch from torch import nn class Model(nn.Module): def __init__(self, column_units): super(Model, self).__init__() self.cnn = nn.Sequential( nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(16), nn.ReLU(inplace=True), nn.Max...
models/clstm.py
Apache-2.0,MIT
1,051
8b4a570d1354d61bb220892113d100ca24735c28
Python
py
# -*- coding: utf-8 -*- import gc import numpy as np import torch import torch.distributed as dist from pcode.create_dataset import define_dataset, load_data_batch from pcode.utils.checkpoint import save_to_checkpoint from pcode.utils.logging import ( display_training_stat, display_test_stat, dispaly_best...
distributed_code/pcode/distributed_running_cv.py
Apache-2.0
5,979
a90aac476a86e990715f81be7e077a020be65a46
Python
py
from typing import Dict, Optional, Tuple, Union from allennlp.common.checks import ConfigurationError from allennlp.nn.util import tiny_value_of_dtype import torch _emb_dim = -1 def get_unit_normalized_vector(vec: Optional[torch.FloatTensor], ) -> Optional[torch.FloatTensor]: """...
interlens/nn/util.py
MIT
4,609
8b4a5e6a3a3c7a0fe858f6690f83c5626d23dd1d
Python
py
# -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import contextlib import io import numpy as np import os import unittest from collections import defaultdict import torch import tqdm from cvpods.utils import benchmark from pycocotools.coco import COCO from tabulate import ...
tests/layers/test_mask_ops.py
Apache-2.0
6,993
8b4a60984663c43aac15739d18328c09a2f76405
Python
py
import torch import torch.nn as nn from torch.autograd import Variable import pdb ''' NOTES - steps are how many times you recurse over the data! (eg the length of the trajectory) - effective_steps is a list of which step outputs you want to save - the format of the data as-is is [batch size, input channels, h, w, d] ...
convolution_lstm.py
MIT
10,196
8b4aa1ec412e1720eb36920fc5d5c00b07f7f147
Python
py
import os import torch import argparse import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import numpy as np from core import models from core.utils import flow as flo from core.utils.disp import labelcolormap from core.utils.config import Config from core.utils.bbox import gen_bbox, label...
davis_test.py
BSD-2-Clause
23,238
6b19790e87087adfa53efd5bfa5079c481cb9d04
Python
py
import numpy as np import pandas as pd from sklearn.model_selection import StratifiedKFold from torch.utils.data import DataLoader from paww.augmentation import get_transforms from paww.dataloader import PawwDataset def get_dataloader(cfg): train = pd.read_csv("data/petfinder-pawpularity-score/train.csv") ...
tests/utils.py
MIT
1,366
f93a04769d098144b1ac03c1d0753b64878c178c
Python
py
import torch import torch.nn.functional as F import numpy as np from rlpyt.models.mlp import MlpModel class VaeHeadModel(torch.nn.Module): def __init__(self, latent_size, action_size, hidden_sizes): super().__init__() self.head = MlpModel( input_size=latent_size + action_size, ...
rlpyt/ul/models/ul/vae_models.py
MIT
3,435
45fe5b4269d41395edea4e25ea2ffdcc88e02abb
Python
py
# Copyright (c) 2020 fortiss GmbH # # Authors: Patrick Hart, Julian Bernhard, Klemens Esterle, # Tobias Kessler and Mansoor Nasir # # This software is released under the MIT License. # https://opensource.org/licenses/MIT # The code is adapted from opensource implementation - https://github.com/ku2482/fqf-iqn-qrdqn.pyt...
bark_ml/library_wrappers/lib_fqf_iqn_qrdqn/agent/iqn_agent.py
MIT
13,603
4bc0f073a6631e869456dbd9bfc78995b4b0f74d
Python
py
import math import argparse import uuid import torch from torch.utils.data import DataLoader from torch.utils.data.dataloader import default_collate from torchvision import transforms import torchvision import matplotlib.pyplot as plt from PIL import Image import wandb from som import SomLayer from autoencoder impor...
som-diffusion/train_som.py
MIT
7,187
2481a0d81e3db4fe179a9fdf8992d2d0065e34e2
Python
py
import math import random import time import os import sys import copy from datetime import datetime from os.path import join, exists from os import mkdir import collections from collections import namedtuple from collections import deque from itertools import count import torch import torch.nn as nn import torch.op...
pyvs/LatentARTraining (copy).py
Apache-2.0
46,962
8b4ac290a8170d2194e0f1d0cfbe54b49fc86312
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 torch import numpy as np from typing import List, Dict, Tuple, Union from fairdiplomacy.agents.base_agent import BaseAgent from fairdi...
fairdiplomacy/agents/base_search_agent.py
MIT
4,800
5ec989f9285bdbfdd270f375e9f94fdc0472e8d6
Python
py
""" Optimizers class """ import torch import torch.optim as optim from torch.nn.utils import clip_grad_norm_ from onmt.utils import use_gpu def build_optim(model, opt, checkpoint): """ Build optimizer """ saved_optimizer_state_dict = None if opt.train_from and opt.reset_optim != 'all': optim = c...
onmt/utils/optimizers.py
MIT
10,448
f97b01637dd04c7aaa7ff902fd2b4e467d69cadb
Python
py
""" Quick n simple image folder dataset Copyright 2020 Ross Wightman """ import torch.utils.data as data import os import re import torch from PIL import Image IMG_EXTENSIONS = ['.png', '.jpg', '.jpeg'] def natural_key(string_): """See http://www.codinghorror.com/blog/archives/001018.html""" return [int(s...
pruning/pruning-model-zoo/ImageNet/data/dataset.py
MIT
3,000
8b4b07f0eb57dbe517714e170796647db8d7a6ed
Python
py
##################################################### # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2021.03 # ############################################################# # Borrow the idea of https://github.com/arogozhnikov/einops # ############################################################# import torch import torch....
xautodl/xlayers/super_rearrange.py
MIT
7,584
ff9ff35f6b64e2e65d7f7e7f7a8d5be602b1e059
Python
py
from abc import ABC from torch.optim import SGD class VROptimizer(ABC): def __init__(self, name, model, train_set, batch_size, lr, device, num_workers, weight_decay): self.name = name self.model = model self.train_set = train_set self.batch_size = batch_size self.optimiser ...
vr_optimizers/optims/base_class.py
Apache-2.0
508
8b4b67faf96424a6dc540685c6db6cdab76b0f37
Python
py
import time import logging import numpy as np import emcee import torch import torch.nn as nn import torch.optim as optim from scipy import optimize from pybnn.base_model import BaseModel from pybnn.util.normalization import zero_mean_unit_var_normalization, zero_mean_unit_var_denormalization from pybnn.bayesian_lin...
pybnn/dngo.py
BSD-3-Clause
14,202
8b4b7f761f6fbcf65100ecd48c6ae08cd41a93c6
Python
py
"""Dataset utils for different data settings for GLUE.""" import os import copy import logging import torch import numpy as np import time from filelock import FileLock import json import itertools import random import transformers from transformers.data.processors.utils import InputFeatures from transformers import D...
src/processors.py
MIT
38,901
10fcfce05c403c97e1aca25795c4d038a47ca92d
Python
py
#encoding:utf-8 import torch import warnings from torch.utils.data import DataLoader from pybert.io.dataset import CreateDataset from pybert.io.data_transformer import DataTransformer from pybert.utils.logginger import init_logger from pybert.utils.utils import seed_everything from pybert.config.basic_config import con...
Code/HypoBertClas/inference.py
MIT
3,598
5eb717f1b60abe45f76b88215a9b63d217bcdaf6
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. import itertools import json import numpy as np import os import torch from pycocotools.cocoeval import COCOeval, maskUtils from detectron2.structures import BoxMode, RotatedBoxes, pairwise_iou_rotated from detectron2.utils.file_io import PathManager from .coco_evalu...
detectron2/evaluation/rotated_coco_evaluation.py
Apache-2.0
7,556
8b4bab3cad5f4b1951e5dddd5b4caa90e9a19394
Python
py
from typing import Callable import torch from torch import Tensor from torch.nn import functional as F from torch import distributed as dist class SimpleContrastiveLoss: def __init__(self, n_hard_negatives: int = 0): self.target_per_qry = n_hard_negatives + 1 def __call__(self, x: Tensor, y: Tensor,...
src/grad_cache/loss.py
Apache-2.0
2,282
10c858f4dcf53ec27d5ad6222c2ba0c6a2babe12
Python
py
# Owner(s): ["oncall: quantization"] import torch import math from typing import Tuple from torch.ao.quantization import ( FakeQuantize, MovingAverageMinMaxObserver, default_observer, default_affine_fixed_qparams_fake_quant, ) from torch.ao.quantization._learnable_fake_quantize import _LearnableFakeQu...
test/quantization/core/test_workflow_ops.py
Intel
58,794
8b4baf10d45d1f2d4794b8860924703c27d54cea
Python
py
from random import randint, shuffle from random import random as rand import numpy as np import torch import torch.nn as nn import argparse from tensorboardX import SummaryWriter import os import tokenization import models from tqdm import tqdm import optim import train from torch.utils.data import Dataset, DataLoader...
data.py
Apache-2.0
8,259
459f1bc446f3a8d70c430cd3906905d6419e1cb4
Python
py
from baseline_data import IMDB_Dataset import torch from torch.utils.data import DataLoader from torch import nn from baseline_model import Baseline_Bert, Baseline_LSTM from baseline_tools import logging from baseline_config import Baseline_Config, dataset_config, model_path from tqdm import tqdm evaluate_device = tor...
baseline/baseline_evaluate.py
Apache-2.0
3,512
8b4bbeb73a3498ffc2ab639b20ad3d49cf44ad11
Python
py
import torchxrayvision as xrv import torchvision as tv import os from os.path import join as pjoin import vis_utils import matplotlib.pyplot as plt import torch from arch.lightning.xray import XRayLightningModel from arch.lightning.base_imagenet import ImageNetLightningModel import pandas as pd import json from arch.li...
cal_calibration.py
Apache-2.0
3,074
343f66ead42c356b2b526f4620edaa6044dbb441
Python
py
import torch as tc from drl.agents.preprocessing import Preprocessing def one_hot(ys: tc.Tensor, depth: int) -> tc.Tensor: """ Applies one-hot encoding to a batch of vectors. Args: ys (torch.Tensor): Torch tensor with shape batch_shape, and dtype int64. depth (int): The number of possibl...
drl/agents/preprocessing/tabular.py
MIT
1,065
5f135b149d139fff32fb1bb3880ab0f46fef20b4
Python
py
#!/usr/bin/python # -*- coding: utf-8 -*- import torch import numpy import random import pdb import os import cv2 import math from scipy.io import wavfile def loadWAV(filename, max_frames, start_frame=0, evalmode=False, num_eval=10): # Maximum audio length max_audio = max_frames*160+240 # self.nMaxFrames = 40 的情况...
dataLoader.py
MIT
1,871
e9dd23723cf1c990ba298643f0325366631878c3
Python
py
from torch import nn from torch.optim import Optimizer, RMSprop from typing import Callable, Dict, Optional, Tuple from .envs import ClassicalControl, DummyParallelEnv, EnvExt, EnvGen, ParallelEnv from .net import actor_critic, value from .lib.explore import DummyCooler, Cooler, LinearCooler, Explorer, EpsGreedy from ....
rainy/config.py
Apache-2.0
6,002
29899921f8a5326f4d574610badf2a9fdf07cbca
Python
py
import torch import torch.nn as nn import torch.nn.functional as F class SoftIoULoss(nn.Module): def __init__(self, n_classes): super(SoftIoULoss, self).__init__() self.n_classes = n_classes @staticmethod def to_one_hot(tensor, n_classes): n, h, w = tensor.size() one_hot =...
src/losses/multi/softiou_loss.py
MIT
1,145
2989a9f2aad9ddfb2d332dbf055cae4c772d6f39
Python
py
import torch from torch_geometric.nn import GravNetConv def test_gravnet_conv(): x1 = torch.randn(8, 16) x2 = torch.randn(4, 16) batch1 = torch.tensor([0, 0, 0, 0, 1, 1, 1, 1]) batch2 = torch.tensor([0, 0, 1, 1]) conv = GravNetConv(16, 32, space_dimensions=4, propagate_dimensions=8, k=2) asse...
test/nn/conv/test_gravnet_conv.py
MIT
1,044
2989d6264a4ea5dc8fe9440a17c8a4b1177c48f4
Python
py
import argparse from itertools import product import torch from torch_geometric import seed_everything from torch_geometric.loader import DataLoader from torch_geometric.profile import profileit, timeit, get_stats_summary from datasets import get_dataset from train_eval import train, eval_acc from gcn import GCN fr...
benchmark/kernel/main_performance.py
MIT
2,622
d77254f62e3719585c29c6d14aa1d5c7497d172f
Python
py
# -*- coding: utf-8 -*- from os import walk import torch import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt import os from PIL import Image import cv2 from torchsummary import summary from torch.utils.data import Dataset, DataLoader, random_split import pandas as pd import nu...
src/data/make_dataset.py
FTL
4,234
7c38cdb27c7d945b0e8934aba6c770f455685545
Python
py
import os import copy import numpy as np from os.path import isfile import torch #import binvox_rw import torch.nn.functional as F EPS = 1e-6 use_cuda = torch.cuda.is_available() DEVICE = torch.device("cuda" if use_cuda else "cpu") def assert_same_shape(t1, t2): for (x, y) in zip(list(t1.shape), list(t2.shape)): ...
net_utils/basic.py
MIT
14,495
298a130500b258ab2eae35451b04138e3cc3fa71
Python
py
""" Copyright (c) 2020-2021 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...
nncf/torch/model_creation.py
Apache-2.0
11,396
803369dff77c9e1b7cb8853af230baf77eaca465
Python
py
# -*- coding: utf-8 -*- import torch import torch.nn as nn import torchvision torch.manual_seed(0) torch.cuda.manual_seed(0) torch.cuda.manual_seed_all(0) class ResNet18(nn.Module): """ 18: ([2, 2, 2, 2], basicblock), 34: ([3, 4, 6, 3], basicblock), 50: ([3, 4, 6, 3], bottleneck), 101: ([3, 4, ...
bird/resnet.py
Apache-2.0
5,024
298a1867c71f62d17a2dbf24dc8471d2108a5b24
Python
py
from typing import Any, Dict, List import torch from allennlp.common import Registrable from allennlp.common.util import pad_sequence_to_length from allennlp.data.tokenizers.token import Token from allennlp.data.vocabulary import Vocabulary # An indexed token list represents the arguments that will be passed to a To...
allennlp/data/token_indexers/token_indexer.py
Apache-2.0
5,714
d782d3392b14607b950119bb7882cdf756b702db
Python
py
from PIL import Image import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import cv2 from scipy.interpolate import interp1d from misc_functions import get_vide_example_params, save_class_activation_videos class CamExtractor(): """ Extracts cam features from the model "...
src/unet3d_scorecam2.py
MIT
5,857
298a5c0210628bcb66e032378aef62a6574bc2c3
Python
py
import torch from torch import nn import pdb from models import c3d_BN def generate_model(opt): assert opt.model in ['c3d'] if opt.model == 'c3d': assert opt.model_depth in [10] from models.c3d_BN import get_fine_tuning_parameters if opt.model_depth == 10: model = c3d...
model.py
MIT
3,352
24d96955948ce5c3bf7a12e7034e17a6005e89b4
Python
py