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
# --------- Link Prediction Model with both TAT and GAT contained ----------- import torch.nn as nn import torch from .GAT import GAT from .TAT import TAT class GATA(nn.Module): def __init__(self, emb_dim, hid_dim, out_dim, num_voc, num_heads, num_ent, num_rel, dropout, alpha, **kwargs): super(GA...
Existing paper reading/model/GATA.py
MIT
1,782
105813c869a5edc310f98773b833ce8591293d86
Python
py
import argparse import datetime import random import time from pathlib import Path import torch import torchvision.transforms as standard_transforms import numpy as np from PIL import Image import cv2 from crowd_datasets import build_dataset from engine import * from models import build_model import os import warning...
test_video.py
BSD-3-Clause
5,324
10861da00bfec7ae0a2c81190acfaca8ab56366a
Python
py
# Copyright (c) 2020 Horizon Robotics and ALF Contributors. 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...
alf/algorithms/data_transformer_test.py
Apache-2.0
13,244
3aca8848c79a96835684431a9ec6d7653f72a16b
Python
py
# PyTorch import torch import torchvision.transforms as transforms # Image managing from PIL import Image # Paths import os # Utils from tqdm import tqdm class HistopathologyImageMaker: def __init__(self, model: torch.nn.Module) -> None: """ Constructor for the HistopathologyImageMaker ...
HistImageMaker.py
MIT
6,860
5ea8a5beda7364afb8fcfccce5e4d2b80fe863e9
Python
py
from torch.utils.data import Dataset from torchvision.transforms import transforms from sklearn.model_selection import train_test_split import os import glob import torch import numpy as np from PIL import Image import pdb class LocalDataset(Dataset): def __init__( self, root: str, datase...
src/base/local_dataset.py
MIT
3,356
e9667bd424694f5af16378d0dfcd7bc9fa58a7a6
Python
py
import numpy as np import torch import torch.nn.functional as F import scipy.sparse as sps from scipy.linalg import eigh, inv, det from numpy import zeros import math from .source import Source from utils import roll class Lattice: def __init__(self,L, d, BC='periodic'): self.L = L self.d = d ...
source/ising.py
Apache-2.0
2,517
ff0be3d2fde851cd4b8ac7c3269abc018fb1bd0f
Python
py
import json from typing import NamedTuple import numpy from numpy.testing import assert_array_almost_equal, assert_almost_equal import torch import pytest from flaky import flaky from allennlp.common.checks import ConfigurationError from allennlp.common.testing import AllenNlpTestCase from allennlp.nn import util fro...
allennlp/tests/nn/util_test.py
Apache-2.0
56,551
3acaa78601c7e3136002abe0dfca3c23e2c12c31
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 torch.nn as nn import numpy as np import sys import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = o...
models/loss_helper.py
MIT
42,095
3acab136dea98d6a53ce2191d7ffcabf9d43c35e
Python
py
import os import sys sys.path.append("../../../../monk_v1/"); sys.path.append("../../../monk/"); import psutil from pytorch_prototype import prototype from compare_prototype import compare from common import print_start from common import print_status import torch import numpy as np from pytorch.losses.return_loss im...
monk/system_unit_tests/pytorch/test_layer_transposed_convolution1d.py
Apache-2.0
1,422
10a26b4e1e3fd2d2851622f032540fc2101bd362
Python
py
import torch.nn as nn import torchvision.transforms as transforms class AlexNetOWT_BN(nn.Module): def __init__(self, num_classes=1000): super(AlexNetOWT_BN, self).__init__() self.features = nn.Sequential( nn.Conv2d(3, 128, kernel_size=3, stride=1, padding=1, bias...
models/vgg_cifar10.py
MIT
2,206
1ec23cd157301e4a7712e8f863a4712aa9bcc93d
Python
py
'''Simplified version of DLA in PyTorch. Note this implementation is not identical to the original paper version. But it seems works fine. See dla.py for the original paper version. Reference: Deep Layer Aggregation. https://arxiv.org/abs/1707.06484 ''' import torch import torch.nn as nn import torch.nn.function...
models/dla_simple.py
MIT
4,084
3acaba68014993ed6235f6ce40272a226b32610a
Python
py
import pytest import torch from pytorch_lightning.metrics.functional.classification import dice_score @pytest.mark.parametrize(['pred', 'target', 'expected'], [ pytest.param([[0, 0], [1, 1]], [[0, 0], [1, 1]], 1.), pytest.param([[1, 1], [0, 0]], [[0, 0], [1, 1]], 0.), pytest.param([[1, 1], [1, 1]], [[1, ...
tests/metrics/functional/test_classification.py
Apache-2.0
541
f9f3033427b1bdfc89c70af188aaa8e6c69b802f
Python
py
# Copyright (C) 2020 THL A29 Limited, a Tencent company. # 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 appl...
benchmark/benchmark_helper.py
BSD-3-Clause
6,220
8036164162942a77bc56f45ff438cc2d7af3d881
Python
py
from torch.multiprocessing import Queue import time import tqdm import torch from typing import List from ml_gym.multiprocessing.job import JobType, Job from ml_gym.multiprocessing.worker import WorkerProcessWrapper from ml_gym.util.logger import QueuedLogging from ml_gym.util.logger import LogLevel, QLogger class Po...
src/ml_gym/multiprocessing/pool.py
Apache-2.0
4,374
b2d403fdde7c0ec43b23e0246a2521f141c95fba
Python
py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import copy import math from pathlib import Path import utils from encoder import make_encoder LOG_FREQ = 10000 def gaussian_logprob(noise, log_std): """Compute Gaussian log probability.""" residual = (-0.5 * noise.pow(2) -...
curl_sac.py
MIT
16,835
3acb1b896affae47f4ae6e3e9c040e1f009f0c1a
Python
py
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
tests/callbacks/test_model_summary.py
Apache-2.0
3,479
b2a57b4e192d095e2131a8de29e8b23a2dc8c1bd
Python
py
# Copyright 2020 Kyoto University (Hirofumi Inaguma) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Conformer encoder block.""" import logging import random import torch import torch.nn as nn from neural_sp.models.modules.conformer_convolution import ConformerConvBlock from neural_sp.models.modules.p...
neural_sp/models/seq2seq/encoders/conformer_block.py
Apache-2.0
7,261
7c93b3aa425b899cc7cb8c608bbfab1149d6f715
Python
py
import argparse import torch from torch.nn import Linear import torch.nn.functional as F from torch_geometric.nn import APPNP from citation import get_planetoid_dataset, random_planetoid_splits, run parser = argparse.ArgumentParser() parser.add_argument('--dataset', type=str, required=True) parser.add_argument('--ran...
benchmark/citation/appnp.py
MIT
1,936
038d428692dfe8239e798eb6afb964efec68a6c6
Python
py
#!/usr/bin/env python """ Main training workflow """ from __future__ import division import argparse import glob import os import random import signal import time import torch from transformers import BertTokenizer import distributed from models import data_loader, model_builder from models.data_loader import lo...
temp/src/train_abstractive.py
MIT
12,448
5fb91d65bd5499f69420f9d47c7049720026fc82
Python
py
from functools import partial import pytest import torch from sklearn.metrics import ( accuracy_score as sk_accuracy, jaccard_score as sk_jaccard_score, precision_score as sk_precision, recall_score as sk_recall, f1_score as sk_f1_score, fbeta_score as sk_fbeta_score, roc_curve as sk_roc_cu...
tests/metrics/functional/test_classification.py
Apache-2.0
23,322
12eb8555b10aa1d4831184d449abe3052c7c037a
Python
py
# 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,956
12c47c407301b7133a266cb8030f2b36177b3a3d
Python
py
import csv import numpy as np from sklearn.neighbors import KernelDensity from sklearn.model_selection import GridSearchCV from Utils import cuda_utils import torch global cpu_kde, cpu_kde_conditional cpu_kde = None cpu_kde_conditional = {} def build_cpu_kde(X): # Cross-validation to find best bandwidth param...
Models/Parzen/Parzen.py
MIT
2,500
24c725a4fc41a15a939a7037cd023be80473ed23
Python
py
import copy import torch import torch.nn as nn from . import diffeq_layers __all__ = ["ODEnet", "ODEfunc"] def divergence_approx(f, y, e=None): e_dzdx = torch.autograd.grad(f, y, e, create_graph=True)[0] e_dzdx_e = e_dzdx.mul(e) cnt = 0 while not e_dzdx_e.requires_grad and cnt < 10: ...
module/odefunc.py
MIT
5,953
342563890d4f82aace4c607f76602c7d79fc1686
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict class SegNet(nn.Module): def __init__(self,input_nbr,label_nbr): super(SegNet, self).__init__() batchNorm_momentum = 0.1 self.conv11 = nn.Conv2d(input_nbr, 64, kernel_size=3, padding=1) ...
models/segnet.py
MIT
6,168
80520868e3b6dbdc4500a19ef0e7ca4c2c886c8d
Python
py
""" Modeling Relational Data with Graph Convolutional Networks Paper: https://arxiv.org/abs/1703.06103 Code: https://github.com/tkipf/relational-gcn Difference compared to tkipf/relation-gcn * l2norm applied to all weights * remove nodes that won't be touched """ import argparse, gc import numpy as np import time impor...
examples/pytorch/rgcn/entity_classify_mp.py
Apache-2.0
25,849
3acb758b43c716045ef485d80a4422a185609781
Python
py
"""This model shows an example of using dgl.metapath_reachable_graph on the original heterogeneous graph. Because the original HAN implementation only gives the preprocessed homogeneous graph, this model could not reproduce the result in HAN as they did not provide the preprocessing code, and we constructed another da...
examples/pytorch/han/model_hetero.py
Apache-2.0
3,815
2477b1711dfc61c1d278795f858d56730c4204b2
Python
py
import cv2 import torch from PIL import Image from threading import Thread def get_boxes(frame): global box_data, ACTIVE_THREADS ACTIVE_THREADS += 1 # Get prediction bounding boxes results = model(frame, size=320) box_data = results.xyxy ACTIVE_THREADS -= 1 def draw_boxes(frame, box, line_th...
Computer_Vision/4_trained_yolov5.py
MIT
2,476
3acb977c70bcad0242d61ff92ffa412b75664cc1
Python
py
import os from torchaudio.functional import magphase from functools import partial import torch class OnlinePreprocessor(torch.nn.Module): def __init__(self, sample_rate=16000, win_len=512, hop_len=256, n_freq=257, feat_list=None, **kwargs): super(OnlinePreprocessor, self).__init__() n_fft = (n_fr...
preprocess.py
MIT
5,158
d7f9644de985dd4dbd9deaec9e4f3cf28fa3e916
Python
py
import flask import torch import torchvision from typing import Tuple from pathlib import Path from dotenv import find_dotenv, load_dotenv from urllib.request import urlretrieve import shutil import json from mapillary_image_classification.config import MAPILLARY_TOKEN_v4 from mapillary_image_classification.models.mod...
mapillary_image_classification/models/predict_model.py
MIT
4,464
dfddb373ba1a9fbe856aa7b1f3b5c9329fb5ee2d
Python
py
import os from unittest import TestCase import torch import yaml from spectrainer import ToyNetTrainer from toynet.toynetv1 import ToyNetV1 from utils.utils import cal_parameters, getConfig class TrainerFunctionTest(TestCase): def setUp(self): conf = getConfig('./config/toynetv1.yml') self.traine...
test/test_trainer.py
MIT
890
70489ea23e5284b7b50f80e681b2ecdc0bd0434e
Python
py
# coding=utf-8 # Copyleft 2019 project LXRT. import os import collections import torch import torch.nn as nn from torch.utils.data.dataloader import DataLoader from tqdm import tqdm from param import args from pretrain.qa_answer_table import load_lxmert_qa from tasks.vqa_model import VQAModel from tasks.vqa_data imp...
src/tasks/vqa.py
MIT
7,842
3acbc4cce61d8aa68e67d9996d8a71c79c3ca50a
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class yoloLoss(nn.Module): ''' 定义一个torch.nn中并未实现的网络层,以使得代码更加模块化 torch.nn.Modules相当于是对网络某种层的封装,包括网络结构以及网络参数,和其他有用的操作如输出参数 继承Modules类,需实现__init__()方法,以及forward()方法 ''' def __init__(self,S,B,l_co...
Yolov1_pytorch/utils/yoloLoss.py
MIT
7,117
d7a01ec09803493de95726d413110e03730a31ba
Python
py
"""Federated datasets.""" import enum import os import random as rnd from collections import Counter, defaultdict from dataclasses import dataclass from typing import (Callable, Dict, Generator, Iterable, List, Optional, Set, Tuple, Union) import torch from torch.utils.data import Dataset from torchtext.data.utils im...
src/fl_simulation/utils/data/datasets.py
MIT
21,418
fce4e4acceb9771aa9614ad14dec7002ca2a278d
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from . import modules class UnwarpNet_cmap(nn.Module): def __init__(self, use_simple=False, combine_num=3, train_mod="all"): super(UnwarpNet_cmap, self).__init__() self.combine_num = combine_num self.use_simple = use_simple...
models/misc/model_cmap.py
Apache-2.0
8,135
3acbeda11a3aa0a000785c272b86733b2ea6fc48
Python
py
import math import pdb import torch.nn as nn from torch.nn import functional as F __all__ = ['BahdanauAttention'] class BahdanauAttention(nn.Module): def __init__(self): pass def forward(self): pass
elvis/modeling/models/layers/attention.py
Apache-2.0
228
3acc11b577eeecc66dbe72d1a763e43e2d42317a
Python
py
# coding=utf-8 # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
megatron/model/multiple_choice.py
MIT
5,700
dfe289aad7ae0bc827aeec7981624f5ac0305807
Python
py
from __future__ import absolute_import, division, print_function import os from transformers import BertTokenizer import torch import torch.nn as nn import const bert_tokenizer = BertTokenizer.from_pretrained(const.MODEL_TYPE, do_lower_case=True) def get_bert_data(examples, tag2id, config): bert_data = [] ...
NER_BERT/bert_data_util.py
Apache-2.0
3,368
3acc6766366f5f27858c6ac0cd1edd9d3c12a19b
Python
py
import os import pytest import torch import ignite.distributed as idist from ignite.distributed.utils import has_hvd_support from tests.ignite.distributed.utils import ( _test_distrib_all_gather, _test_distrib_all_reduce, _test_distrib_barrier, _test_distrib_config, _test_distrib_one_rank_only, ...
tests/ignite/distributed/utils/test_horovod.py
BSD-3-Clause
8,086
1ecc4a0c96d8a5ab2067f9b0382d3e253b39ed64
Python
py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
tests/collections/nlp/test_retrieval_module_inference.py
Apache-2.0
26,708
3acc6fdceb8478674c292b3c1f953e37219ee52f
Python
py
import os import os.path as osp import math import sqlite3 from tqdm import tqdm import pandas as pd import numpy as np import torch import magnificat.observation_utils as obs_utils class LSSTCadence: min_mjd = 59580.139555 nside_in = 32 nested = False fov_radius = 1.75 # deg, field of view bp_to...
magnificat/cadence.py
MIT
10,151
7c390999b5719b46ea7483792c682eb00a0ee176
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. import contextlib import copy from enum import Enum, auto import functools import logging from math import inf import time import traceback im...
fairscale/nn/data_parallel/fully_sharded_data_parallel.py
BSD-3-Clause,Apache-2.0,MIT
104,357
f9a75c8d0f1f0963746e685cb64a0de29181af60
Python
py
# Copyright 2020 The HuggingFace Team. 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 applicabl...
src/transformers/commands/env.py
Apache-2.0
3,232
3acc85825d7e6d66e0f1591413a4cb828ea81063
Python
py
import os from collections import defaultdict from PIL import Image from torch.utils.data import Dataset from torchvision import transforms from torchvision.datasets.utils import download_and_extract_archive from src.datasets.specs import Input2dSpec AIRCRAFT_RESOURCES = { 'aircraft': 'http://www.robots.ox.ac.uk...
src/datasets/natural_images/aircraft.py
MIT
4,995
4b49505d80418eaa1e31dc592799072e651db00a
Python
py
""" Useful functions related to the `ava.models` subpackage. """ __date__ = "July - November 2020" from affinewarp import PiecewiseWarping from affinewarp.crossval import paramsearch import h5py import matplotlib.pyplot as plt plt.switch_backend('agg') import numpy as np import os from scipy.interpolate import inter...
ava/models/utils.py
MIT
14,493
dfe3af549a685c1c0434ba01719058c8e012362f
Python
py
# adapted from https://github.com/sthalles/SimCLR/blob/master/models/resnet_simclr.py import torch.nn as nn import torchvision.models as models class Resnet(nn.Module): def __init__(self, out_dim=128): super(Resnet, self).__init__() self.resnet = models.resnet18(pretrained=False, num_classes=out_...
model.py
Unlicense
594
a91b8c943a55d35cbd3b3c4fe1c7dec50055b46c
Python
py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import List, Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F from pytext.config import ConfigBase from pytext.models.module import Module from pytext.utils import cuda from pyte...
pytext/models/representations/ordered_neuron_lstm.py
BSD-3-Clause
7,014
3accd73402e2a6eeabd55b33aa622b3423f05212
Python
py
import sys import os from transformers import AutoModel from typing import List from tfkit.utility.predictor import Predictor dir_path = os.path.dirname(os.path.realpath(__file__)) sys.path.append(os.path.abspath(os.path.join(dir_path, os.pardir))) import torch from torch import nn from tfkit.model.seq2seq.dataload...
tfkit/model/seq2seq/model.py
Apache-2.0
10,765
fd6f9fc79ae45ce7f2f9bc870a2382ed25158ed3
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/networks/nets/resnet.py
Apache-2.0
16,338
1086a21e46f37095d6583dbc71eac4e4e4607697
Python
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import datetime import json import logging import random import s...
torch/distributed/elastic/rendezvous/etcd_rendezvous.py
Intel
49,569
3accfc3b43b5fb95f6a10451b52f3a6c82b8e2da
Python
py
import os import torch from ucca.convert import to_text, xml2passage from .instance import Instance from .dataset import TensorDataSet class Corpus(object): def __init__(self, dic_name=None): self.dic_name = dic_name self.passages = self.read_passages(dic_name) self.instances = [Instanc...
parser/utils/corpus.py
MIT
3,769
b256e8955294fab061c05ad4e29a8623547fb0c3
Python
py
# -*- coding: utf-8 -*- # @Author : William # @Project : TextGAN-william # @FileName : maligan_instructor.py # @Time : Created at 2019/11/29 # @Blog : http://zhiweil.ml/ # @Description : # Copyrights (C) 2018. All Rights Reserved. import torch import torch.optim as optim import confi...
instructor/real_data/maligan_instructor.py
MIT
6,228
e65f0d7e75baa9b1aed9550a310d1de29adf621d
Python
py
#!/usr/bin/env python3 # Copyright 2020 Christian Henning # # 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...
ex02/tests/public/test_main.py
MIT
2,934
fccb72920c92c5034ffa3f579151d9b4a9115ac1
Python
py
# OpenPCDet PyTorch Dataloader and Evaluation Tools for Waymo Open Dataset # Reference https://github.com/open-mmlab/OpenPCDet # Written by Shaoshuai Shi, Chaoxu Guo # All Rights Reserved 2019-2020. import os import pickle import copy import cv2 from cv2 import cvtColor import numpy as np import torch import multiproc...
pcdet/datasets/waymo/waymo_dataset.py
MIT
25,987
dffe2d3890938ebd7c42429d58f0707cdb5381a0
Python
py
import torch as T import neuralnet_pytorch.ext as ext __all__ = ['earth_mover_distance'] class EarthMoverDistanceFunction(T.autograd.Function): @staticmethod def forward(ctx, xyz1, xyz2): xyz1 = xyz1.contiguous() xyz2 = xyz2.contiguous() assert xyz1.is_cuda and xyz2.is_cuda, "Only sup...
neuralnet_pytorch/extensions/dist_emd.py
MIT
1,012
3acd87ec7f8276a911f71b457483ac4a20bc33b6
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import glob import importlib import logging import os import sys import warnings import torch from mmf.common.reg...
mmf/utils/checkpoint.py
BSD-3-Clause
17,750
ff0d7df8571aec99c8dc3fae2f314cc4b1225229
Python
py
""" file: models/ada_lista.py author: Xiaohan Chen last modified: 2021.08.10 Implementation Ada-LISTA. """ import math import torch import numpy as np import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from .utils import shrink, shrink_ss class AdaLIS...
models/ada_lista.py
MIT
6,545
e9c746d248e5f8e7499a780bc9b7cdd51441b5d2
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...
torchmetrics/classification/roc.py
Apache-2.0
7,237
3acda6e64ff970636c03546a71d13fcfa44e4e1f
Python
py
"""Transducer decoder interface module.""" from espnet.nets.beam_search_transducer import Hypothesis from typing import Any from typing import Dict from typing import List from typing import Tuple from typing import Union import torch class TransducerDecoderInterface: """Decoder interface for transducer models...
espnet/nets/transducer_decoder_interface.py
Apache-2.0
3,398
3acdaef51012a2a5e5b330599a45a7c89eac2f3b
Python
py
import os from glob import glob import numpy as np import torch from args import args if args.dtype == 'float32': default_dtype = np.float32 default_dtype_torch = torch.float32 elif args.dtype == 'float64': default_dtype = np.float64 default_dtype_torch = torch.float64 else: raise ValueError('Unk...
src_hop_sk/utils.py
MIT
3,616
3406c95e24ebf99752835c8704b3ca6d2d4d10f9
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 matplotlib.pyplot as plt from mpl_toolkits.mplot3d.art3d import Poly3DCollection import PIL import imageio from easydict import EasyDict as edict ...
util_vis.py
MIT
10,655
3acdd7f5aaff2a2ae51192c16f0eb184d92dccf2
Python
py
import numpy as np import torch from .misc import process_outputs_gaussian from .estimators import ( EnsembleGaussianCategoricals, ) def compute_token_gaussian_uncertainties(args, outputs, extra): """ Function which computes token-level measures of uncertainty for Gaussian Categorical model. :param a...
examples/self_distribution_distillation/self_distribution_distillation_src/uncertainty/gaussian.py
MIT
2,838
3acded7e220980ae26bc4ee9ee1a4bd546cb5a2d
Python
py
import yaml import torch.optim as op from torch.nn import modules import goodDataML.learning.horizontal.torch_model.process_data as processes from typing import Callable def convert_loss_name_to_func(loss): # type: (str) -> modules.module return getattr(modules.loss, loss) def convert_optimizer_to_func(opt...
goodDataML/learning/utils/pytorch_utils.py
Apache-2.0
2,044
45474782da857d00c0a0a450b401d97c471803e7
Python
py
# encoding: utf-8 """ A script for running the following experiments: * dataset: Overnight * model: BART encoder + vanilla Transformer decoder for LF * training: normal (CE on teacher forced target) """ import json import random import string from copy import deepcopy from functools import partial from typing import C...
parseq/scripts_multling/geoquery_base_bert.py
MIT
18,386
5f7b7482e18483988e3c6ca7f157d277232e4e5f
Python
py
""" Copyright (c) 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 wri...
torchreid/apis/export.py
MIT
3,873
3ace0397813b0fccbe77c7961603b07923fc7a09
Python
py
r"""RNN language model with residual connection.""" from typing import ClassVar, Dict, List, Optional import torch import torch.nn as nn from lmp.model._rnn import RNNModel from lmp.tknzr._base import BaseTknzr class ResRNNBlock(nn.Module): r"""Residual connected RNN blocks. Each output of RNN will be add...
lmp/model/_res_rnn.py
Beerware
12,483
e91876fc13dc0fbb83c53fd0b0d5b81efd687abb
Python
py
import collections import json import logging import os from argparse import Namespace from typing import (Dict, List, Optional) import torch from .tag_encoder import NERTagsEncoder, SCHEMES from .tokenization import ( Token, TokenizerWithAlignment, reconstruct_text_from_tokens, ) from pytorch_transforme...
portuguese_bert/preprocessing.py
MIT
19,549
4b4faf3ce8c7375f30c3c442502042bb3bee6623
Python
py
# -*- coding: utf-8 -*- """CIFAR_training.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1XcUVE2Bt2CVgmD9uHwATsBJ40MC9w0PC """ datasetName = "CIFAR-100" # datasetName = "CIFAR-10" if (datasetName == "CIFAR-100"): tc = 100 if (datasetName == ...
cifar_training.py
MIT
9,209
5f46c92f937a03792024b72f2a4723ecbb9f968b
Python
py
import torch.nn as nn import torch import torch.nn.functional as F from ltr.models.layers.blocks import conv_block from .conv_gru import ConvGRUCell #import msvcrt from visdom import Visdom vis=Visdom(env="rnn") class ResponsePredictor(nn.Module): def __init__(self, state_dim=8, representation_predictor_dims=(64,...
ltr/models/kys/response_predictor_stark.py
MIT
10,194
428f15369b0425521c8df806357a9d3f4fd8e46f
Python
py
import numpy as np import torch import time from hydroDL.model import rnn, crit from hydroDL.data import transform def subsetRandom(dataLst, batchSize, sizeLst, opt='Random', matB=None): """get a random subset of training data Arguments: dataLst {list} -- see trainModel [x,xc,y,yc] batchSize ...
hydroDL/model/trainBasin.py
MIT
8,560
3ace3a30b9a2888d46edb6892dd79465c12de3e7
Python
py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import math from itertools import groupby import torch import torch.nn.functional as F from fairseq im...
examples/audio_visual_se_sr/criterions/RNNT_loss.py
MIT
7,261
3ace69484cf3bd5c1695b37bbb9bf0d13cb3e6df
Python
py
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import os import json import logging from tqdm import tqdm import random import torch from torch.utils.data import DataLoader, SequentialSampler, Dataset from torch.utils.data.distributed import DistributedSampler from transformers import Rober...
utils_nlp/models/transformers/abstractive_summarization_seq2seq.py
MIT
45,326
3ace6da3c92fee90f84bc7810c2db49e121ea69f
Python
py
import torch import torch.utils.data import torch.backends.cudnn as cudnn import torch.nn.functional as F from torchvision.transforms.functional import rgb_to_grayscale from utils import AttnLabelConverter from model import Model from dataset import NormalizePAD from PIL import Image,ImageDraw,ImageFont import math i...
demo-opencv.py
Apache-2.0
6,692
3ace6f94bf35292c12959d70337879f936b5da67
Python
py
import torch from torch import Tensor import torch.nn as nn from typing import Type, Any, Callable, Union, List, Optional def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d: """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, k...
system/flcore/trainmodel/resnet.py
MIT
6,372
5f80c293570422d15642b5972182158e9b935b0f
Python
py
# -*- coding: utf-8 -*- import argparse import os.path as osp from copy import deepcopy import yaml from loguru import logger import torch from main.test import build_sat_tester, build_siamfcpp_tester from videoanalyst.config.config import cfg as root_cfg from videoanalyst.config.config import specify_task from vid...
main/hpo.py
MIT
2,412
f93bfe6caaf65e9584ae0340edebb61c514ff726
Python
py
import warnings import torch.nn as nn from mmcv.cnn import constant_init, kaiming_init from qd3dt.ops import DeformConvPack, ModulatedDeformConvPack from .conv_ws import ConvWS2d from .norm import build_norm_layer conv_cfg = { 'Conv': nn.Conv2d, 'ConvWS': ConvWS2d, 'DCN': DeformConvPack, 'DCNv2': Mod...
qd3dt/models/utils/new_conv_module.py
BSD-3-Clause
5,869
3acec4920a162be6827deea90c049de164c513b7
Python
py
# Copyright (c) 2019 Graphcore Ltd. All rights reserved. import numpy as np import popart import torch import pytest from op_tester import op_tester # `import test_util` requires adding to sys.path import sys from pathlib import Path sys.path.append(Path(__file__).resolve().parent.parent) import test_util as tu def ...
tests/integration/operators_test/matmul_test_broadcasting_base.py
MIT
4,671
52a5294e14ee3836ad4277dd2c30343a02104ff4
Python
py
import glob import math import os import random import cv2 import numpy as np import torch # from torch.utils.data import Dataset from utils.utils import xyxy2xywh class LoadImages: # for inference def __init__(self, path, img_size=416): if os.path.isdir(path): image_format = ['.jpg', '.jpe...
utils/datasets.py
MIT
12,227
7caf2df186cfa6a8e7ccf3d991e0a11708980339
Python
py
import argparse import numpy as np import os import Loader as Loader import sys import math import torch import matplotlib.pyplot as plt import torch.nn.functional as F from utils import CropImage, linear_schedule from torch import nn, optim from torch.nn import functional as F from torch.autograd import Variable from ...
vae/plotshitsogram.py
MIT
1,877
3acf22f037ca8afc573af7bf58c7f58ff848431c
Python
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 29 14:57:05 2019 @author: esat """ import os import sys import numpy as np import math import cv2 import scipy.io as sio import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import to...
MLP/VideoSpatialPrediction3D_bert_embedding.py
MIT
10,430
fccc13df9466234a086f18b04091953192733c6a
Python
py
from utils.utils import AUCMeter from tqdm import tqdm from models.resnet import resnet18, resnet50 import numpy as np from utils.Logger import Logger from optimizer.optimizer_helper import get_optim_and_scheduler, FocalLoss from models import model_factory from data.data_helper import available_datasets from data impo...
Domain_Generalization/train.py
BSD-2-Clause
19,249
10e5c6dc0a8c0488dfc376c38e13b45482be814b
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from mmcv.runner import ModuleList, force_fp32 from mmdet.core import (build_anchor_generator, build_assigner, build_bbox_coder, build_sampler, multi_apply) from ..builder import HEADS from ..losses import smooth_l1_loss from .a...
mmdet/models/dense_heads/ssd_head.py
MIT
11,064
1e2151afd32849c1e7cd13ab38351ef6a6d670b6
Python
py
import torch import torchvision import cv2 import random import numpy as np from PIL import Image from torchvision import transforms from sourcecode.configs.make_cfg import Struct """ - type: RandomRotation prob: 0.3 angle: [-10, 10] - type: RandomRotation prob: 0.3 angle: [90, 90] - typ...
sourcecode/dataset/transform.py
MIT
5,061
3acf98942959c5f175e5b0d17233c7614d77a66a
Python
py
""" A collection of utility functions for working with files, such as reading metadata from demonstration datasets, loading model checkpoints, or downloading dataset files. """ import os import h5py import json import time import urllib.request import numpy as np from collections import OrderedDict from tqdm import tqd...
robomimic/utils/file_utils.py
MIT
13,479
7079b02d59ecd4d033002a386ae68031feef426c
Python
py
# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and # Technical University of Darmstadt. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source ...
Pyrado/pyrado/policies/base.py
DOC,Zlib,BSD-3-Clause
9,665
129318ead4f2ed99d020a298dacd1191b3c2cb50
Python
py
#!/usr/bin/env python import argparse from mmcls.apis import init_model import torch from list_dataset import ImageFilelist import numpy as np import pickle from tqdm import tqdm import mmcv from os.path import dirname import torchvision as tv def parse_args(): parser = argparse.ArgumentParser(description='Say hel...
extract_feature_vit.py
Apache-2.0
2,525
3acfc1d1c4310e0d49095eaabb347a96e498b64d
Python
py
import torch from torch import nn, optim from torch.nn import functional as F class FaderAE(nn.Module): def __init__(self, num_attributes, num_channels=1): super().__init__() self.input_size = 256 self.latent_space = 50 self.num_channels = num_channels self.num...
models/FaderAE.py
MIT
2,925
104ca01ad391b9267ee561803224167acef0b60d
Python
py
""" Copyright (c) 2019-2020 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in w...
tests/torch/test_backward_compat.py
Apache-2.0
7,890
3acfc52d4e803dbb9c4bd37ab6708087e88ce30a
Python
py
"""Tests for graph construction tools.""" import numpy as np import pytest import torch from matplotlib import pyplot as plt from tiatoolbox.tools.graph import ( SlideGraphConstructor, affinity_to_edge_index, delaunay_adjacency, edge_index_to_triangles, triangle_signed_area, ) def test_delaunay_...
tests/test_graph.py
BSD-3-Clause
10,494
10a6eb7f8c8a8f0a3005f8c270ac47acb04c72c5
Python
py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a cop...
examples/research_projects/distillation/run_squad_w_distillation.py
Apache-2.0
36,220
3acfd468640626f052fa66a9560d04ac46db03a3
Python
py
#!/usr/bin/env python # Copyright 2020-2021 OpenDR European Project # # 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 a...
projects/opendr_ws/src/perception/scripts/object_detection_2d_detr.py
Apache-2.0
4,316
52f7d31aa2123715a7816e8be06078e9915ddac0
Python
py
# Import from third library import torch import torch.nn as nn from up.utils.model.initializer import initialize_from_cfg from up.utils.general.registry_factory import MODULE_ZOO_REGISTRY from up.tasks.det.plugins.yolov5.models.components import ConvBnAct, Focus, SPP from up.tasks.det.plugins.yolov5.models.components ...
up/tasks/det/plugins/yolox/models/backbone/cspdarknet.py
Apache-2.0
11,355
3ad01767b66d7c5201ea80cec7cc2dfb2f55d078
Python
py
import torch from torch import nn from torch import optim from torch.utils import data from torch.backends import cudnn from .trainer import Trainer from ..utils import StepClass from ..models.ExprAutoEncoders import ClassDiscriminator class SAAETrainer(Trainer): '''see readme''' def __init__(self, parameter...
src/biopy/training/saae_trainer.py
MIT
7,150
dfe220f5159146fc3c030509fd11b4ce06b67d0f
Python
py
import torch import torch.nn as nn import torch.nn.functional as F class LSTM_model(torch.nn.Module): def __init__(self, embedding_dim, hidden_dim, target_size, batchsize, isTraining=True, use_dropout=False, gpu=0, lstm_layers=1, att_dim=0): super(LSTM_model,self).__init__() self.e...
networks.py
MIT
2,323
10c3113148eeac98aeb4b4de969e6229194e6ce1
Python
py
""" File Name: UnoPytorch/drug_qed_dataset.py Author: Xiaotian Duan (xduan7) Email: xduan7@uchicago.edu Date: 9/4/18 Python Version: 3.6.6 File Description: """ import logging import numpy as np import pandas as pd import torch import torch.ut...
Pilot1/UnoMT/utils/datasets/drug_qed_dataset.py
MIT
4,797
12e9de28fd1f35863e09ab306c564fb46f825d47
Python
py
import pickle import random import os import numpy as np import torch from torch.utils.data import TensorDataset from options import opt class FoldedDataset: def __init__(self, baseclass, kfold, *args): self.__class__ = type(self.__class__.__name__, (baseclass, object), di...
code/data_prep/folded_dataset.py
MIT
2,596
3ad0b186d88a538bb7d8781c2091079bdb2de8b2
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. # pylint: disable=missing-module-docstring # pylint: disable=missing-class-docstring # pylint: disable=missing-function-d...
tests/nn/data_parallel/test_fsdp_regnet.py
MIT,Apache-2.0,BSD-3-Clause
13,553
10e6d351d6f039a918741da8ac24a326698d4d73
Python
py
import argparse import datetime import numpy as np import time import torch import torch.backends.cudnn as cudnn import json from pathlib import Path from timm.data import Mixup from timm.models import create_model from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy from timm.scheduler import cre...
search.py
MIT
18,800
29f246c6fd7a541e9b72127b2cae7c9c9b2d68f1
Python
py
import torch from .autograd_impl import Autograd, AutogradFloat32 from torchaudio_unittest import common_utils @common_utils.skipIfNoCuda class TestAutogradLfilterCUDA(Autograd, common_utils.PytorchTestCase): dtype = torch.float64 device = torch.device('cuda') @common_utils.skipIfNoCuda class TestAutogradRN...
test/torchaudio_unittest/functional/autograd_cuda_test.py
BSD-2-Clause
435
341c575d87aadc0f6cdc59c9daed3eb5d94e84c4
Python
py
from __future__ import print_function import argparse import json import logging import os import sys import horovod.torch as hvd import torch.nn.functional as F import torch.optim as optim import torch.utils.data.distributed from model_def import Net from torchvision import datasets, transforms logger = logging.get...
sagemaker-python-sdk/pytorch_horovod_mnist/code/mnist.py
Apache-2.0
7,337
d7d3f474ced32a368607501f37f1446a7fdc8096
Python
py
# Copyright (c) OpenMMLab. All rights reserved. import pytest import torch from mmcv.ops import gather_points @pytest.mark.skipif( not torch.cuda.is_available(), reason='requires CUDA support') def test_gather_points(): features = torch.tensor([[[ -1.6095, -0.1029, -0.8876, -1.2447, -2.4031, 0.3708, ...
tests/test_ops/test_gather_points.py
Apache-2.0
2,188
a93df692a58425140fc1fd73f5cefe9c07cf0d6b
Python
py