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
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.2.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %reload_ext autoreload # %aut...
notebook/GCN-LSTM-dataset.py
Apache-2.0
6,050
45d29443860492df6500428f8b3fc824f6ef69f9
Python
py
import os import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class LossComputer: def __init__(self, criterion, is_robust, dataset, alpha=None, gamma=0.1, adj=None, min_var_weight=0, step_size=0.01, normalize_loss=False, btl=False, sp=0.0, mode='', ratio=0.0): self.criteri...
Figure_4_and_table_3/loss.py
MIT
9,836
5fc71d46f7a3238d2864420ad9bd18048817dd9f
Python
py
import argparse import gc import os import shutil import numpy as np import scipy.io as io import torch import torch.optim as optim from tqdm import tqdm import losses import networks import utils from input_prepocessing import input_preparation, resize_images from sensor import Sensor from show_results import show f...
main.py
BSD-4-Clause-UC
12,496
12f3cf62c764408592d3538195b8feaf3220129e
Python
py
import numpy as np import os import pytest import random import utils __author__ = "Christopher Potts" __version__ = "CS224u, Stanford, Spring 2022" utils.fix_random_seeds() @pytest.mark.parametrize("arg, expected", [ [ np.array([0.0, 0.25, 0.75]), np.array([0.22721977, 0.29175596, 0.48102426])...
test/test_utils.py
Apache-2.0
3,497
e631f57b359f8a211f0c6d2f49450e509956ce32
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/core/test_data.py
Apache-2.0
1,729
12d163a50be7c544b20cbaefa07d380ad8885ffb
Python
py
from pathlib import Path import numpy as np import torch from torch_geometric.data import InMemoryDataset, Data from torch_geometric.utils import dense_to_sparse from Utils import compute_KNN_graph class ConnectivityData(InMemoryDataset): """ Dataset for the connectivity data.""" def __init__(self, ...
Dataset.py
MIT
1,479
298a9e1385053c3565a6b5c8065568e5b212ab7f
Python
py
from typing import Tuple import torch from allennlp.common import Registrable class Retriever(Registrable): def _post_process_scores(self, scores: torch.Tensor): raise NotImplementedError def __call__(self, scores: torch.Tensor) -> Tuple[torch.LongTensor, torch.LongTensor]: """ Parame...
examples_allennlp/utils/retrieval/retrievers/retriever.py
Apache-2.0
553
f9cf83dbc1544849a72e2777c25209a26403e558
Python
py
import torch from torch import nn from torch import Tensor from torch.nn import functional as F from torch.nn.utils.weight_norm import weight_norm from torch.nn.utils.spectral_norm import spectral_norm from typing import Callable, Any LayerFunc = Callable[[nn.Module], None] def sigmoid_range(x, low, high): "Si...
mmedit/models/colorizers/blocks.py
Apache-2.0
6,933
298ae27788750084080197acf6d4c4bb1c9d91f6
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from torch_geometric.nn.inits import glorot from torch_geometric.nn import MessagePassing from torch_geometric.utils import add_self_loops, softmax, degree import random """Reproducibility""" seed = 0 torch.manual_seed(seed) torch.cuda.manual_seed(seed...
partial_algorithm/GNN.py
MIT
10,759
347ed91aaf5044281d018202fb7ae56b86f674f4
Python
py
import math import os import sys import time import os.path import torch import torch.nn.functional as F import torch.optim as optim from envs import create_atari_env from model import ActorCritic, load_model from torch.autograd import Variable from test import test import pdb def setup(args): # logging log_...
train.py
MIT
7,991
298b0d4f9287573c24f17228af57ef42d79af567
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. from torch import nn from torch.autograd import Function from torch.autograd.function import once_differentiable from torch.nn.modules.utils import _pair from .. import _C class _ROIAlign(Function): @staticmethod def forward...
fcos/core/layers/roi_align.py
BSD-3-Clause
2,208
298b1ac043b949d8a322ea61de9d54b13f6deb8b
Python
py
import glob import os import random import numpy as np from torch.utils.data import Dataset import torchvision.transforms as transforms from PIL import Image class ImageDataset(Dataset): def __init__(self, root, transforms_=None, mode="train"): self.transform = transforms.Compose(transforms_) s...
GAN/Pix2Pix/dataset.py
MIT
861
298b1d66f1f88fb39a764ea41166e17a474564bf
Python
py
# Helper functions of for now unspecified class import NeuralNet import torch import torch.optim as optim from torch.optim import Adam, SGD class Helper(): def __init__(): pass #Loads a pytorch NN given a path (String) Returns a Neural Net torch object def load(path): model = ConNet() model.load_state_dic...
modules/helper.py
MIT
957
298b2660a3f6b7af72e0daaee8f71e2cb0bea916
Python
py
import click import json import pandas as pd import numpy as np from scipy import stats import torch from dataset import Triage from torch.utils.data import DataLoader from models import load_tokenizer MAX_LEN = 512 VALID_BATCH_SIZE = 16 def predict(model, data_loader, device): model.eval() id_list = [] ...
predict.py
MIT
2,971
298b374802f02134c5094db65e3ebe7a141e7bf9
Python
py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # Acknowledgement: Part of the codes are adapted from Zuxuan Wu import os import numpy as np import...
models/audioPreview_model.py
CC-BY-4.0
11,338
298b3d5273bc0c4cb95053e95aa522457f8fe7d6
Python
py
""" # Code borrowded from: # https://github.com/zijundeng/pytorch-semantic-segmentation/blob/master/utils/transforms.py # # # MIT License # # Copyright (c) 2017 ZijunDeng # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software...
transforms/transforms.py
BSD-3-Clause
12,026
e638fe550acbcf618662ee27fa3b7f0c056d49db
Python
py
# -*- coding: future_fstrings -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import json import random import numpy as np from pathlib import Path from . import io from . import misc from . import logging PARAM_FNAME = "params.json" logger...
utils/train.py
MIT
3,648
298b4670d23674950920f1b3f5b9c83c9151eaa3
Python
py
from typing import Dict, List import numpy as np import sklearn.metrics as skmetrics import torch from sklearn.neighbors import KNeighborsClassifier from src import utils def evaluate_knn_on_pretrained_model( model: torch.nn.Module, device: torch.device, loaders: Dict[str, torch.utils.data.DataLoader], ...
src/training/knn.py
MIT
1,468
298b4ac630940fed76534469f0bd83779c951aa4
Python
py
########################## # Utility functions # # THIS FILE IS OBSOLETE # ########################## import torch import time, sys from transformers import RobertaTokenizer, BertTokenizer tokenizer = RobertaTokenizer.from_pretrained('roberta-base') tokenizer_bert = BertTokenizer.from_pretrained('bert-base-case...
scripts/roberta/utils.py
Apache-2.0
4,505
7c2a506691a9520d4abfdd10d2b8bdf2d34fe4c7
Python
py
#!/usr/bin/env python3 # Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang, # Wei Kang) # # See ../../../../LICENSE for clarification regarding multiple authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file e...
egs/librispeech/ASR/conformer_ctc/train.py
Apache-2.0
23,336
298b74112420a34797f6b4ab01fa8942b0e85a23
Python
py
import torch # region new attention class Attention(torch.nn.Module): """ New attention base""" def __init__(self, **kw): super(Attention, self).__init__(**kw) def normalize(self, attention_scores, ctx_mask=None): raise NotImplemented("use subclass") def compute_scores(self, qry, ct...
qelos_core/att.py
MIT
4,765
298b765ef8d3eb82f3126aaa84d449df77a56475
Python
py
import copy import cv2 import os import torch.utils.data as data import scipy.io as io import numpy as np from PIL import Image from util.config import config as cfg from skimage.draw import polygon as drawpoly from util.misc import find_bottom, find_long_edges, split_edge_seqence, \ norm2, vector_cos, vector_sin ...
dataset/dataload.py
MIT
7,195
298b9b3dac44eba82d50356e8206fb07e14c6b11
Python
py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
nemo/collections/asr/data/audio_to_text_dataset.py
Apache-2.0
14,670
4239355530f234f951d10985b7838db952524eed
Python
py
import torch import torch.nn as nn from torchsummary import summary from config import device, im_size import migrate_model class conv2DBatchNormRelu(nn.Module): def __init__( self, in_channels, n_filters, k_size, stride, padding, ...
models_v16_3.py
MIT
8,541
45b75f2fc075afe87277716c10265e4f3b3b2315
Python
py
import torch import torch.distributed as dist from torch.nn import Parameter from torch.nn import Module from apex.parallel import DistributedDataParallel as DDP import argparse import os parser = argparse.ArgumentParser(description='allreduce hook example') parser.add_argument("--local_rank", default=0, type=int) ar...
furnace/apex/tests/distributed/ddp_race_condition_test.py
MIT
2,326
298baeb0571f7381ae880761d03b7573af7fb69a
Python
py
import argparse import logging import time from argparse import ArgumentParser from pathlib import Path import tensorrt as trt import torch from mmdet2trt.models.builder import build_wraper from mmdet2trt.models.detectors import TwoStageDetectorWraper from mmdet.apis import init_detector from mmdet.apis.inference impo...
mmdet2trt/mmdet2trt.py
Apache-2.0
11,826
298bbec70564219b4cf834f8aad22c172fcbb370
Python
py
"""Compute depth maps for images in the input folder. """ import os import glob import torch import cv2 import argparse import matplotlib.pyplot as plt import util.io from torchvision.transforms import Compose from dpt.models import DPTDepthModel from dpt.midas_net import MidasNet_large from dpt.transforms import Re...
run_monodepth.py
MIT
8,295
d74fe2932a15fd844b3096b4bb2f89f128a817d5
Python
py
# Copyright (c) 2019, 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 applic...
kaolin/models/PointNet2.py
ECL-2.0,Apache-2.0
39,025
4256c667775f5c171e18f7bc99cb14f2b5001c2c
Python
py
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
src/transformers/pipelines.py
Apache-2.0
60,848
fd7d7b0886f5acf0ab0918ce73eb8645e7701823
Python
py
# -*- coding: utf-8 -*- """ @author:XuMing(xuming624@qq.com) @description: """ import torch import torch.nn as nn import torch.nn.functional as F class Attention(nn.Module): def __init__(self, input_size, hidden_size, num_classes, device='cuda'): super(Attention, self).__init__() self.attention_...
ocr/layers/attn.py
Apache-2.0
4,125
298be3d18a52deb60a481afa58945d1fa2cba866
Python
py
import torch import torch.nn as nn class JointsOHKMMSELoss(nn.Module): def __init__(self, use_target_weight, topk=8): super(JointsOHKMMSELoss, self).__init__() self.criterion = nn.MSELoss(reduction='none') self.use_target_weight = use_target_weight self.topk = topk de...
mmskeleton/models/loss/JointsOHKMMSELoss.py
Apache-2.0
1,732
5e635e7d085eaccbe46b29102fadc414d84ed3d4
Python
py
import copy import mmcv import torch from mmcv.parallel import DataContainer as DC from mmcv.runner import force_fp32 from os import path as osp from torch import nn as nn from torch.nn import functional as F from mmdet3d.core import (Box3DMode, bbox3d2result, merge_aug_bboxes_3d, show_result...
mmdet3d/models/detectors/mvx_two_stage.py
Apache-2.0
21,871
298c1d5b6a5d135dac106187da42c43b2a956cac
Python
py
import logging import os.path as osp import torch from torch import nn from tensorboardX import SummaryWriter from lib.test import test from lib.utils import checkpoint, precision_at_one, \ Timer, AverageMeter, get_prediction, get_torch_device from lib.solvers import initialize_optimizer, initialize_scheduler f...
lib/train.py
MIT
6,322
6b28b71cfbc31707fcfd48e309b3faef3d23e3c5
Python
py
"""mobilenetv2 in pytorch [1] Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen MobileNetV2: Inverted Residuals and Linear Bottlenecks https://arxiv.org/abs/1801.04381 """ import torch import torch.nn as nn import torch.nn.functional as F class LinearBottleNeck(nn.Module): ...
models/mobilenetv2.py
MIT
2,845
298c290eca334967d5a30d0b40b040a93a515bbb
Python
py
import gpytorch import torch from . import priors class ExactGP_RBF(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood, prior): super(ExactGP_RBF, self).__init__(train_x, train_y, likelihood) # prior if prior == "Lineal": #self.mean_module = priors.Lineal...
excursion/models/__init__.py
Apache-2.0
1,978
7c806bf6328b5483226748d12a6d3eec359d3f88
Python
py
import argparse import logging import random import os import torch import pickle import yaml import json from tqdm import tqdm import numpy as np from tensorboardX import SummaryWriter import torch.optim as optim from data import SQuADDataset from model import RNet from math import log2 from metrics import * def eva...
source/train.py
MIT
8,652
d71527df84a9b48ecc053109343de63565163ed0
Python
py
import os import argparse import logging import time import numpy as np import numpy.random as npr import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F parser = argparse.ArgumentParser() parser.add_argume...
latent_ode_tinfocnf_randtheta_augparam.py
MIT
21,022
298c67b3fe637590e699f7c1fdd4099f61f6f39a
Python
py
from typing import Optional from overrides import overrides import torch from allennlp.training.metrics.metric import Metric @Metric.register("boolean_accuracy") class BooleanAccuracy(Metric): """ Just checks batch-equality of two tensors and computes an accuracy metric based on that. That is, if your p...
allennlp/training/metrics/boolean_accuracy.py
Apache-2.0
4,318
298c70ff80ea61c46fe4f8959d92a478a8c5379c
Python
py
import torch import torch.nn as nn import torchvision # VGG architecter, used for the perceptual loss using a pretrained VGG network class VGG19(torch.nn.Module): def __init__(self, requires_grad=False): super().__init__() vgg_pretrained_features = torchvision.models.vgg19(pretrained=True).features...
model/vgg.py
MIT
2,423
298c77fc7e13d265039568822588b239d45d87d2
Python
py
import torch.nn as nn from hierarchical_clustering.relaxed.models.model import HypHCModel, index_to_one_hot class HypHCLinear(HypHCModel): """ Hyperbolic linear model for hierarchical clustering. """ def __init__(self, rank=2, temperature=0.05, init_size=1e-3, max_scale=1. - 1e-3, alphabet_size=4, ...
hierarchical_clustering/relaxed/models/linear.py
MIT
898
1e54d8d46c526d26fd4897c84d68f03449ff8bd5
Python
py
import torch import torch.nn as nn from omegaconf import OmegaConf import sys sys.path.append("..") # sys.path.append("../image_synthesis") from image_synthesis.utils.misc import instantiate_from_config from image_synthesis.taming.models.vqgan import GumbelVQ, VQModel from image_synthesis.taming.models.cond_transformer...
image_synthesis/modeling/codecs/image_codec/taming_gumbel_vqvae.py
MIT
10,011
fda46eb941b0f28589834e0a6a79c5c609d13ef3
Python
py
# coding=utf-8 # Copyright 2020-present, the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
examples/movement-pruning/emmental/modules/masked_nn.py
Apache-2.0
4,532
298c7e5e51de02b3538ff62f2580d2b9b4836bf6
Python
py
#!/usr/bin/env python 3 # -*- coding: utf-8 -*- # # Copyright (c) 2020 PanXu, Inc. All Rights Reserved # """ acsa model outputs Authors: PanXu Date: 2020/07/18 16:00:00 """ import torch from easytext.model import ModelOutputs class ACSAModelOutputs(ModelOutputs): """ ACSA Model Outputs """ def...
acsa/models/acsa_model_outputs.py
MIT
403
298c93adbad7fdc9939dc1c6e1517dadcff66399
Python
py
import torch.nn as nn import torch.nn.functional as F from im2mesh.layers import ( ResnetBlockFC, CResnetBlockConv1d, CBatchNorm1d, CBatchNorm1d_legacy, ResnetBlockConv1d ) class Decoder(nn.Module): ''' Decoder class. It does not perform any form of normalization. Args: dim (int): i...
im2mesh/onet_m/models/decoder.py
MIT
9,393
5e28f0c1eef729cf4485b43508a7463e2125596e
Python
py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from torch.autograd import Variable import math import copy from load_data import EXTRA_CHARS class OneHotEmbedding(nn.Module): def __init__(self, alphabet_size): super().__init__() self.alphabet_size = alphabet_...
transformer.py
MIT
10,910
7cbeb0bf1522df09678022958807c43dce703d71
Python
py
""" The system trains BERT (or any other transformer model like RoBERTa, DistilBERT etc.) on the SNLI + MultiNLI (AllNLI) dataset with softmax loss function. At every 1000 training steps, the model is evaluated on the STS benchmark dataset Usage: python training_nli.py OR python training_nli.py pretrained_transformer_m...
examples/evaluate_STSb_datasets/sbert_embbeding/training_NLI.py
Apache-2.0
4,865
b2742fcba1361e2cac8cb98bb83e6effa96053d7
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. """ RoBERTa: A Robustly Optimized BERT Pretraining Approach. """ import logging import torch import torch.nn as nn import torch.nn.functional...
fairseq/models/roberta/model.py
MIT
26,608
d7ced9190ca60a922e289958b9f636875f41b125
Python
py
# import torch import torch.nn as nn import torch.nn.functional as F # from torch.autograd import Variable # from functools import partial __all__ = [ 'C2D' ] class C2D(nn.Module): def __init__(self, sample_size, sample_duration, num_classes=400): s...
models/c2d.py
MIT
3,342
fda389e57d50d82c5a313bdfb4298a9e52d5cb86
Python
py
import torch import copy from tqdm import tqdm import torch.nn.functional as F from ogb.nodeproppred import PygNodePropPredDataset, Evaluator from typing import Optional, List, Union from torch_geometric.typing import OptPairTensor, Adj, Size, OptTensor from torch.utils.checkpoint import checkpoint from torch import Te...
src/ogbn-proteins/utils.py
Apache-2.0
13,312
1076d0ee82a8abf22151bea90e5a107bad7d64cc
Python
py
import time from itertools import product from loggers import CSVLogger, PrintLogger, FileLogger, multi_logger import torch from torch.optim import Adam import os import networkx as nx import pickle import numpy as np import logging from model_runner import ModelRunner,execute_runners import cProfile Data...
GCN_II/GCN_temporal_communities_main.py
MIT
7,714
0398ed48c9dce16fb5c8e3fab54247ea60dcc07f
Python
py
import copy from PIL import Image from PIL import ImageEnhance from torch.utils.data import DataLoader, Dataset import torch import numpy as np import glob import torchvision import matplotlib.pyplot as plt import random import cv2 np.seterr(divide='ignore', invalid='ignore') class heatmap_dataset(Dataset): def _...
hourglass_four/dataloader/dataset_four.py
Apache-2.0
18,573
298d0dd919439dded9ae57dfdb84da76f675fa75
Python
py
import os import sys import gym import numpy as np import torch from gym.spaces.box import Box from baselines import bench from baselines.common.atari_wrappers import make_atari, wrap_deepmind from baselines.common.vec_env.vec_env import \ VecEnvWrapper, VecEnv, CloudpickleWrapper, clear_mpi_env_vars from baselin...
a2c_ppo_acktr/envs.py
BSD-3-Clause
11,462
298d0fd8893196bcaf20f272be5a4953c979529d
Python
py
from transformers import GPT2Tokenizer,GPT2LMHeadModel from pytorch_pretrained_bert import OpenAIGPTTokenizer, OpenAIGPTModel, OpenAIGPTLMHeadModel import torch import numpy as np import math tokenizer = GPT2Tokenizer.from_pretrained('gpt2') model = GPT2LMHeadModel.from_pretrained('gpt2') model.to('cuda') model.eval()...
metric/lm_score.py
MIT
1,277
298d52651d28ccf235caf7c4a53d3a59a396ed33
Python
py
import torch import torch.nn as nn from .py_utils import TopPool, BottomPool, LeftPool, RightPool from .py_utils.utils import convolution, residual, corner_pool from .py_utils.losses import CornerNet_Loss from .py_utils.modules import hg_module, hg, hg_net def make_pool_layer(dim): return nn.Sequential() def ma...
6_cornernet_lite/lib/core/models/CornerNet.py
Apache-2.0
2,786
298d7372f740aac217ff41c1871e6e373fa8e9b3
Python
py
# MIT License # # Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021 # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation the # r...
art/preprocessing/standardisation_mean_std/utils.py
MIT
2,403
b2a5d64931a3b87af644c652ed1e21b59359013f
Python
py
import random import math import torch from torch import nn import torchvision from torchvision.ops import misc as misc_nn_ops from .image_list import ImageList from .roi_heads import paste_masks_in_image class GeneralizedRCNNTransform(nn.Module): """ Performs input / target transformation before feeding the...
torchvision/models/detection/transform.py
BSD-3-Clause
7,369
45fe037a86eb64d33c1ebe762a3a0736cd0a42ce
Python
py
import numpy as np import torch import torch.nn.functional as F from dnnv.nn import Operation, OperationVisitor, operations def convert(operations): converter = PytorchConverter() for op in operations: _ = converter.visit(op) return PytorchModel(converter.operations, converter.inputs, operations)...
dnnf/pytorch.py
MIT
14,374
ff4351cb2c42f2961e274a3bf4f3df71a4de1feb
Python
py
import torch import torchvision.models as models import torch.nn as nn import torch.nn.functional as F from torchsummary import summary def encoder(base_model): model,n_out=None,None if base_model == "resnet18": model = models.resnet18(pretrained=True) n_out = 512 elif base_model == "res...
modules.py
MIT
3,342
298d94d2d882d48e825d13aa2c0a4e335e9e7966
Python
py
# -*- coding: utf-8 -*- # @Time : 20-6-3 下午5:14 # @Author : zhuying # @Company : Minivision # @File : MultiFTNet.py # @Software : PyCharm from torch import nn import torch.nn.functional as F from src.model_lib.MiniFASNet import MiniFASNetV1,MiniFASNetV2,MiniFASNetV1SE,MiniFASNetV2SE class FTGenerator(nn.Module): ...
anti_spoofing/model_lib/MultiFTNet.py
Apache-2.0
2,773
f934df4d2575a8a9193401f122b383aef21e358f
Python
py
# Copyright 2021 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/accelerate/launchers.py
Apache-2.0
7,641
298db439b048c3da62f89c192c3d26aafdf0e48d
Python
py
# -*- coding: utf-8 -*- # @Time : 2019/8/23 21:52 # @Author : zhoujun from torch.utils.data import DataLoader from torchvision import transforms import random import pathlib from . import dataset def get_datalist(train_data_path, val_data_path, validation_split=0.1): """ 获取训练和验证的数据list :param train_d...
data_loader/__init__.py
MIT
5,145
4b59eda6bbbf174eedce46c30244f7a2bb06694f
Python
py
import os from abc import abstractmethod, ABC from typing import Union, Tuple import h5py import numpy as np import scipy.io as scio import scipy.sparse from scipy.sparse import load_npz from sklearn.datasets import load_svmlight_file from .benchmark_utils import Dataset __all__ = ( "get_load_fn", "get_cv_fn", ...
falkon/benchmarks/common/datasets.py
MIT
37,537
03a18daaa37d4c4745b46c69c9232fbbc6d30d8a
Python
py
import torch import numpy as np torch.manual_seed(120) from tqdm import tqdm from pytorch3d.loss import chamfer_distance from torch_nurbs_eval.surf_eval import SurfEval import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import offset_eval as off import sys sys.path.insert(...
examples/surface_offsetting.py
BSD-3-Clause
10,184
298dd3525444e199b19a147a9520939607b4a9ba
Python
py
import os.path as osp import numpy as np import math import torch import json import copy import transforms3d import scipy.sparse import cv2 from pycocotools.coco import COCO from core.config import cfg from graph_utils import build_coarse_graphs from noise_utils import synthesize_pose from smpl import SMPL from coo...
data/Human36M/dataset.py
MIT
29,938
6b16b61dfe2e9e6dde41895f94ad2216048d7363
Python
py
#!/usr/bin/env # -*- coding: utf-8 -*- """ main.py: """ import sys sys.path.append("..") import argparse import logging import importlib from dl import logger, args from dl.train import Trainer from dl.info import * import shutil from dl.dataloader import Dataset, MLPDataset, collate_fn from torch.utils.data import ...
dl/main.py
MIT
4,984
1062621fcb47460dc5be602d93ff022492ef2d6e
Python
py
import os import logging import torch import torch.nn.functional as F from utils import metrics logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) logger = logging.getLogger(__name__) def train(model, optimizer, train_dataloader, valid_dataloader, args): be...
trainer.py
MIT
2,170
dfe064bcbd0f084c2a27d3eeb9eccd02a6906842
Python
py
# ------------------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # -------------------------------------------------------------------...
InnerEye/ML/models/losses/ece.py
MIT
2,163
298e0d247b8760eb3a885c992b48181f9951d5db
Python
py
import functools import importlib import logging import pkgutil import sys from collections import OrderedDict from inspect import isfunction, getmembers import torch import torchvision import models.discriminator_vgg_arch as SRGAN_arch import models.feature_arch as feature_arch import models.fixup_resnet.Discriminat...
codes/trainer/networks.py
Apache-2.0
9,475
422d6f913ce3bff3b2acef4f9562d13b37699147
Python
py
import backproppers import calculators import fp_selectors import loggers import selectors import time import torch import torch.nn as nn import trainer as trainer start_time_seconds = time.time() class SelectiveBackpropper: def __init__(self, model, optimizer, ...
lib/SelectiveBackpropper.py
MIT
9,438
298e175a8fb9c89a23e53cb69c5f60247293527a
Python
py
from numbers import Number import torch from torch.distributions import constraints from torch.distributions.distribution import Distribution from torch.distributions.utils import broadcast_all class Uniform(Distribution): r""" Generates uniformly distributed random samples from the half-open interval ``...
torch/distributions/uniform.py
Intel,X11
3,066
b212c52695c24c52766d9cf317ee2ce52271cc52
Python
py
import torch import numpy as np import RLPython.RLHelper.libRLHelper as lib # Replay Buffer do: # store (state, action, reward, done) information (append) # cap path (path_finish) # get state, action list (get_tensor) # calculate returns (get_returns) # calculate gae function (get_gae) class ReplayBuffer(): def _...
RLPython/replaybuffer.py
MIT
2,331
cc189ef777a44259e714adbc7d2a84b9cdccbfa7
Python
py
# # Lightnet related postprocessing # These are functions to transform the output of the network to brambox detection dataframes # Copyright EAVISE # import logging import numpy as np import torch from .util import BaseTransform from distutils.version import LooseVersion try: import pandas as pd except Modu...
lightnet/data/transform/_postprocess.py
MIT
14,269
298e21c8f3229dc04c8465c62bf4e5019201129d
Python
py
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import numpy as np import torch im...
fairseq/data/language_tuple_noise_dataset.py
MIT
11,900
b2358956eb7f7558dd0fbbc4e0bd1795e49a0581
Python
py
import os import torch.utils.data as data import numpy as np from torchvision import transforms as T from data_objects.transforms import Normalize, generate_test_sequence import pandas as pd from pathlib import Path def get_eval_paths(): data_dir = Path("/media/mdt/WD/zalo/speech/data/Train-Test-Data/feature/publ...
data_objects/VoxcelebTestset.py
MIT
4,026
105b983988b085e027c06fd8547b32f91b76438d
Python
py
import numpy as np import os,json,sys from typing import Dict, Sequence, Type, Callable, List, Optional import torch from torch import nn sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from modules.transformers import BertModel,BertConfig,BertTokenizer from modules.MLP import MLP from lo...
nlp_basictasks/heads/attack_for_cls.py
MIT
5,397
298e3a5263896b495aff4452be821c2a5b0777bc
Python
py
# Copyright (C) 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 applicable ...
nemo/collections/asr/parts/jasper.py
Apache-2.0
17,345
f98ababb562ac5bd0708770184f93c172dae1d59
Python
py
import torch from dp_layer import DPLayer def make_data(): a_range=torch.arange(1,3,dtype=torch.float,requires_grad=True).view((1,-1)) a_range=torch.cat([a_range,a_range+2],dim=0).unsqueeze(0) a_range=a_range ** 2 return a_range def test_dp_forward(): image=make_data() layer=DPLayer('diff_sq...
dp_layer/tests/test_dp_layer_forward.py
MIT
731
298e61f2a6f5552427fe2dfcecd278ae775962bf
Python
py
import cv2 import glob import imageio import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import os import shutil import torch import torchvision.datasets as dset from torchvision import transforms def make_folder(path): if not os.path.exists(path): os.makedirs(path...
utils.py
MIT
11,368
70a66d1b1b1dafc08485d5032c5b19afb20e379f
Python
py
# Copyright (c) Chris Choy (chrischoy@ai.stanford.edu). # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, ...
MinkowskiEngine/MinkowskiChannelwiseConvolution.py
MIT
8,259
4bbf04f89703158ff47b211910563b37e5159b2e
Python
py
import logging from abc import ABCMeta, abstractmethod import mmcv import numpy as np import pycocotools.mask as maskUtils import torch import torch.nn as nn from mmdet.core import auto_fp16, get_classes, tensor2imgs class BaseDetector(nn.Module): """Base class for detectors""" __metaclass__ = ABCMeta ...
mmdet/models/detectors/base.py
Apache-2.0
4,894
6b260aa839e367691156486ebec8cf12a205695f
Python
py
'''Train CIFAR10 with PyTorch.''' import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as cudnn import torchvision import torchvision.transforms as transforms import os import argparse from models import * from utils import progress_bar parser =...
main.py
MIT
4,713
10fbc1fec615b6f5322b64380e4cf1c3107948f9
Python
py
import argparse import os import numpy as np import math import itertools import torchvision.transforms as transforms from torchvision.utils import save_image from torch.utils.data import DataLoader from torchvision import datasets from torch.autograd import Variable from mnistm import MNISTM import torch.nn as nn ...
.history/implementations/pixelda/pixelda_try_20190106200721.py
MIT
18,474
5e23606bda0a34f467a341faa242c224e16f2041
Python
py
from typing import Dict, Tuple import torch import torch.distributed.rpc as rpc import torch.testing._internal.dist_utils as dist_utils from torch import Tensor from torch.testing._internal.dist_utils import ( dist_init, get_timeout_error_regex, worker_name, wait_until_pending_futures_and_users_flushed...
torch/testing/_internal/distributed/rpc/jit/rpc_test_faulty.py
Intel,X11
8,445
347580a9c317c48273f60634865758bd3c82b9c6
Python
py
import torch class get_dataset(torch.utils.data.Dataset): def __init__(self, dataset, feature_len=1): super(get_dataset, self) self.dataset= dataset self.feature_len= feature_len def __len__(self): return len(self.dataset) def __getitem__(self, idx): data= self.dataset[idx] features= ...
EyeBlinkDetection/modules/data.py
MIT
808
298ef737ad27dd8de1d7eed84aeaeae02607024e
Python
py
import torch import torch.nn as nn class Discriminator(nn.Module): def __init__(self, n_h): super(Discriminator, self).__init__() self.f_k = nn.Bilinear(n_h, n_h, 1) for m in self.modules(): self.weights_init(m) def weights_init(self, m): if isinstance(m, nn.Bilin...
layers/discriminator.py
MIT
891
298f12e51e02b25700f830cd045a6fd97a29b87d
Python
py
import mmcv import numpy as np import random import torch from PIL import Image from pathlib import Path from torch.utils import data as data from basicsr.data.transforms import augment, paired_random_crop, totensor from basicsr.utils import FileClient, get_root_logger class Vimeo90KDataset(data.Dataset)...
basicsr/data/vimeo90k_dataset-40.py
MIT
5,782
298f14517728bd67ae6767569e5e60cfc3d6ebc1
Python
py
""" File that involves dataloaders for the Visual Genome dataset. """ import json import os import h5py import numpy as np import torch from PIL import Image from torch.utils.data import Dataset from torchvision.transforms import Resize, Compose, ToTensor, Normalize from dataloaders.blob import Blob from lib.fpn.box_...
dataloaders/visual_genome.py
MIT
14,181
a9186854447ba83a6ef2335a119ecdb7e59c518a
Python
py
import torch import torchvision from omegaconf import DictConfig class Model(torchvision.models.ResNet): def __init__(self, config: DictConfig): block_name = config.model.backbone.resnet_block if block_name == 'basic': block = torchvision.models.resnet.BasicBlock elif block_nam...
ptgaze/models/mpiifacegaze/backbones/resnet_simple.py
MIT
1,748
a937e97a3dcef845d275de91dbec90e9fc11ff46
Python
py
from tqdm import tqdm from transformers import GPT2LMHeadModel, GPT2TokenizerFast import argparse import os import torch import logging logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s', datefmt='%d-%m-%Y:%H:%M:%S') logging.getLogger().s...
DPLM-Transformer/eval_ppl_by_gpt2.py
Apache-2.0
2,863
298f61846954751e944acc229390b05ad0f4b107
Python
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import time import random import copy import gym import cv2 import os from PIL import Image from gym import spaces from gym.utils import seeding import numpy as np import torch from torch.autograd import grad from .capac_controller import CapacController # from...
utils/gym_wrapper_e2e_thro.py
MIT
24,438
7cde5a1d6287cd65c85f14a9cdeacd2406a7abc6
Python
py
""" @author: Yifei Ji @contact: jiyf990330@163.com """ from typing import Tuple, Optional, List, Dict import os import torch import torch.nn as nn import numpy as np import torch.nn.functional as F import tqdm from .lwf import Classifier as ClassifierBase __all__ = ['Classifier', 'CoTuningLoss', 'Relationship'] clas...
talib/finetune/co_tuning.py
MIT
6,067
4208c503464170dca8319c1584cb43e0b1c6b7d6
Python
py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.weight_norm import weight_norm from torch.autograd import Variable from utils.config import * from model.modules import * class Generator(nn.Module): def __init__(self, d_model, vocab, W=None): supe...
model/generators.py
MIT
2,698
52b335f0b27b55092edf0def72453f0aa56c3b0f
Python
py
# # Copyright (c) 2020, NVIDIA 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 ...
nvtabular/torch_dataloader.py
Apache-2.0
9,026
34738a7f807376461206ab60cbae9d4284769f7b
Python
py
# encoding: utf-8 import copy import itertools import numpy as np import torch import torch.nn.functional as F import torch.utils.model_zoo as model_zoo import random from scipy.spatial.distance import cdist from sklearn.preprocessing import normalize from torch import nn, optim from torch.utils.data import dataloader...
models/bdb_with_one_branch.py
MIT
9,078
24ab78e7c6cc53007ad4431e50997c1cdd4486c4
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from operations import * from torch.autograd import Variable from genotypes import PRIMITIVES from genotypes import Genotype class MixedOp(nn.Module): def __init__(self, C, stride): super(MixedOp, self).__init__() self._ops = nn.ModuleList(...
Analysis/darts/cnn/model_search_cost.py
MIT
12,185
298fbe086d95ed84b25aad3b5cada33676ed2a5e
Python
py
from abc import abstractmethod import torchvision.transforms as transforms class TransformsConfig(object): def __init__(self, opts): self.opts = opts @abstractmethod def get_transforms(self): pass class AgingTransforms(TransformsConfig): def __init__(self, opts): super(AgingTransforms, self).__init__(o...
configs/transforms_config.py
Apache-2.0,BSD-2-Clause,MIT
2,634
298fc72a190d8eef7a75cec58501a872f0782516
Python
py
import os import torch import numpy as np from tqdm import tqdm #import imageio import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt # io utils from pytorch3d.io import load_obj # datastructures from pytorch3d.structures import Meshes, join_meshes_as_batch, join_meshes_as_scene, Point...
projects/sonar_mapping/fit_real_mesh_from_sss_optimize_loop.py
BSD-3-Clause
14,664
5f0f7ee08b57abf33832b3d467d4cf0593441b8a
Python
py
import torch.optim as optim from torch.optim.lr_scheduler import LambdaLR from core.algorithms.onpolicy_sync.losses import PPO from core.algorithms.onpolicy_sync.losses.ppo import PPOConfig from projects.objectnav_baselines.experiments.objectnav_base import ObjectNavBaseConfig from utils.experiment_utils import Builde...
projects/objectnav_baselines/experiments/objectnav_mixin_ddppo.py
MIT
1,592
f94eb6295e44975ab44fce8bf2427026bd899fa5
Python
py
# coding:utf-8 import torch import numpy as np import json import opennre from opennre import encoder, model, framework import sys import os import argparse import logging print(torch.cuda.is_available()) parser = argparse.ArgumentParser() parser.add_argument('--ckpt', default='', help='Checkpoint...
train_supervised_cnn.py
MIT
4,728
1e532d36b255f80944965f9f0248d490df5db171
Python
py
import torch as th import contextlib from .cg_controller import DeepCoordinationGraphMAC from modules.agents import REGISTRY as agent_REGISTRY import itertools import numpy as np class DCGnoshareMAC (DeepCoordinationGraphMAC): """ Implements DCG without any parameter sharing between agents (Boehmer et al., 2020)....
src/controllers/dcg_noshare_controller.py
Apache-2.0
6,580
b27c2944976e39bdd16d5138081db91b43d3f42b
Python
py