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 |
|---|---|---|---|---|---|---|---|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension
import numpy
############# If showing struct declaration conflict... | setup.py | MIT | 3,271 | feba15dbeefed859c173eacaeb8d58b938acbc5f | Python | py | |
from __future__ import print_function, division
import collections
import copy
import ctypes
import importlib
import os
import queue
import random
import signal
import sys
import time
import warnings
from typing import Optional
import numpy as np
import torch
import torch.multiprocessing as mp
from setproctitle impor... | rl_multi_agent/main.py | MIT | 13,080 | d79370b13d1e654912139f03bf2d6d2bb9a5f87d | Python | py | |
import numpy as np
import pandas as pd
import torch
import pickle
import torch.nn.functional as F
def preprocess_csv():
'''
train_id_index: dict, {'patient ID': 0, ...}
train_feats: torch_tensor, L2 normalization
train_labels_dict: dict, {'preCST': torch.tensor(...), ...}
test_id_index: dict, {'pa... | src/utils/preprocess_csv.py | MIT | 4,514 | feba1f2f5f1579237879eca0ab53f8fad22fed90 | Python | py | |
import torch
from torch.autograd import Variable
import torchvision.transforms as transforms
import torchvision.datasets as dsets
import numpy as np
from torch.optim.optimizer import Optimizer, required
import torch.nn.functional as F
import time
hhh = {}
class SGD(Optimizer):
def __init__(self, params, lr=requi... | lr.py | Apache-2.0 | 4,433 | feba202272d2e3232f0967518fa4235dfdea76a1 | Python | py | |
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
import prob
import superp
import plot3d
############################################
# This file will plot 2-D or 3-D barrier
############################################
#... | plot.py | BSD-3-Clause | 8,785 | 5e91326a796982523b4e4977c2a9b0a915888c2f | Python | py | |
#-------------------------------------------------------------------------------#
# Copyright (C) 2020-2021 ETH Zurich, Switzerland, University of Bologna, Italy.#
# All rights reserved. #
# ... | pulp-dronet-v2/testing.py | Apache-2.0 | 7,973 | 52fbcab201cd449fc9ce5a6a0bf7817ac18396d5 | Python | py | |
import matplotlib.pyplot as plt
import mmcv
import torch
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from mmseg.datasets.pipelines import Compose
from mmseg.models import build_segmentor
def init_segmentor(config, checkpoint=None, device='cuda:0'):
"""Initialize a segmentor... | mmseg/apis/inference.py | Apache-2.0 | 3,978 | 7cebac986d9c79d3c3d7027f37aec3256d24112e | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2018 Nagoya University (Tomoki Hayashi)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""E2E-TTS training / decoding functions."""
import copy
import json
import logging
import math
import os
import time
import chainer
import kaldiio
import nu... | espnet/tts/pytorch_backend/tts.py | Apache-2.0 | 26,692 | e65f710bda7a923f4336ef8a49770d0b113354e8 | Python | py | |
import torch
from torch.autograd import Variable
import torchvision
from torchvision import transforms
from PIL import Image
import numpy as np
from const import PAD
class Data_loader(object):
def __init__(self, path, imgs, labels, max_len, batch_size, is_cuda, img_size=299, evaluation=False):
self._pa... | Image-Cap/data_loader.py | MIT | 2,542 | feba7da5565bf378f29b225f3c06aa6914057fe6 | Python | py | |
import math
import torch
from ._abstract_recurrent_cell import AbstractRecurrentCell
from ..abstract import ExtendedTorchModule
from ..functional import mnac, Regualizer, RegualizerNMUZ, sparsity_error
class ReRegualizedLinearMNACLayer(ExtendedTorchModule):
"""Implements the NAC (Neural Accumulator)
Argume... | stable_nalu/layer/re_regualized_linear_mnac.py | MIT | 3,399 | 345b121d43f0e2efb0e14e9f8a84020dd44aeec5 | Python | py | |
import torch
from .Module import Module
class Replicate(Module):
def __init__(self, nf, dim=0):
super(Replicate, self).__init__()
self.nfeatures = nf
self.dim = dim
assert self.dim >= 0
def updateOutput(self, input):
assert self.dim < input.dim()
size = list(... | torch/legacy/nn/Replicate.py | MIT | 906 | 10f4d80884b976410627409a3841499ace5911b3 | Python | py | |
"""
Project: stock_prediction
File: run_attention_rnn.py
Created by: louise
On: 08/02/18
At: 12:53 PM
"""
import torch
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torch import optim
from torch.optim import lr_scheduler
from tensorboardX... | src/run_attention_rnn.py | MIT | 5,677 | 45d6eed2293984c1ae9de67e6a24bf0cc4ed6c1d | Python | py | |
# --------------------------------------------------------
# DaSiamRPN
# Licensed under The MIT License
# Written by Qiang Wang (wangqiang2015 at ia.ac.cn)
# --------------------------------------------------------
import torch.nn as nn
import torch.nn.functional as F
class SiamRPN(nn.Module):
def __init__(self, ... | code/net.py | MIT | 3,166 | ff8bb24b0ca30dc4bb99c5a1117e47c97ce61845 | 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/tests/algorithms/test_meta.py | DOC,Zlib,BSD-3-Clause | 38,166 | febad66a24aa66b86e1ff96549c6f770cad5f237 | Python | py | |
__author__ = ["Francisco Clavero"]
__email__ = ["fcoclavero32@gmail.com"]
__status__ = "Prototype"
""" Custom Ignite metrics for GANs. """
from abc import ABC
import torch
from ignite.exceptions import NotComputableError
from ignite.metrics import Metric
from ignite.metrics.metric import reinit__is_reduced
from i... | vscvs/metrics/gan.py | MIT | 7,094 | febafed73826230a0ba299cbe128ecc7bb99b4de | Python | py | |
from motionAE.src.motionTrainer import motionTrainer
import os
from tqdm import tqdm
import shutil
import numpy as np
import torch
import torch.optim as optim
from torch.autograd import Variable
from util.arg_parser import ArgParser
from motionAE.src.models import lstmAE_wo_Norm, lstmDecoder, Discriminator_frame, Dis... | motionAE/src/motionGANTrainer.py | MIT | 11,633 | 7c267a5ceeb7fa327ccbd7920b6bce154e34eefc | Python | py | |
import torch
import random
import numpy as np
from PIL import Image, ImageOps, ImageFilter
class Normalize(object):
"""Normalize a tensor image with mean and standard deviation.
Args:
mean (tuple): means for each channel.
std (tuple): standard deviations for each channel.
"""
def __ini... | dataloaders/custom_transforms.py | MIT | 5,083 | febb4012dcbc8ae6036db4bd2885c5ea1c3793ee | Python | py | |
"""
Implementation of BaseModel taken and modified from here
https://github.com/kwotsin/mimicry/blob/master/torch_mimicry/nets/basemodel/basemodel.py
"""
import os
from abc import ABC, abstractmethod
import torch
import torch.nn as nn
class BaseModel(nn.Module, ABC):
r"""
BaseModel with basic functionalities... | lib/model/BaseModelClass.py | BSD-2-Clause | 1,413 | 24ff0248403d89fbabb34046f6d8b4452572f6af | Python | py | |
from typing import List
import torch
from torch.utils.hooks import RemovableHandle
from models.networks.assisting_layers.L0_Layers import L0Linear, L0Conv2d
class FLOPCounter:
"""
Estimates current FLOPS usage of one sample or cumulatively
Loosely based on implementation from:
Rethinking the Value ... | models/statistics/Flops.py | MIT | 5,977 | a941131177489c9cb5996c1dc4648491fc30d7ee | Python | py | |
import os
import numpy as np
from PIL import Image
from scipy.ndimage import rotate
from copy import deepcopy
from sklearn.metrics import auc
from skimage import morphology, graph
import torch
import torch.nn as nn
import scipy as sp
from random import randint
def load_DRIVE(patch_size):
safe_size = int(np.ceil... | code/utils.py | MIT | 11,185 | f978d0e87fd53b936cde048e3a99a3ab0ddfd47d | Python | py | |
# coding=utf-8
# Copyright 2019 HuggingFace Inc.
#
# 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 ag... | tests/test_tokenization_common.py | Apache-2.0 | 151,549 | febb9a05c08a54ea1c3c1f0907afbbcedccf7d39 | Python | py | |
# coding: utf-8
import h5py
import scipy.io as io
import PIL.Image as Image
import numpy as np
import os
import glob
import scipy.spatial
from scipy.ndimage.filters import gaussian_filter
import torch
import cv2
def generate_GT(root):
train = root + '/train/images/'
val = root + '/val/images/'
test = ro... | data/fidt_generate_jhu.py | MIT | 4,641 | febbb1eb5163a4c11e349e858a611485ad4b2438 | Python | py | |
# Copyright 2019 Jian Wu
# License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import torch as th
try:
import kenlm
kenlm_available = True
except ImportError:
kenlm_available = False
from aps.conf import load_dict
from aps.const import EOS_TOKEN, SOS_TOKEN
class NgramLM(object):
"""
... | aps/asr/lm/ngram.py | Apache-2.0 | 2,642 | febbb2dd302a4a9885c8855eaa67745ae5102dd0 | Python | py | |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import datetime
import itertools
import logging
import os
import tempfile
import time
from collections import Counter
import torch
from fvcore.common.checkpoint import PeriodicCheckpointer as _PeriodicCheckpointer
from fvcor... | detectron2/engine/hooks.py | Apache-2.0 | 14,879 | febbb90a150f76167dd6d12ca9b8f302e4f88954 | Python | py | |
import torch
config = {
'default_device': torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu'),
'default_classes': [
'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
'parking... | detecto/config.py | MIT | 1,182 | febbc235786f70ad5b00e37773c36f15aea08278 | Python | py | |
import logging
from typing import List
from overrides import overrides
import torch
from allennlp.training.learning_rate_schedulers.learning_rate_scheduler import LearningRateScheduler
logger = logging.getLogger(__name__)
@LearningRateScheduler.register("slanted_triangular")
class SlantedTriangular(LearningRateSc... | allennlp/training/learning_rate_schedulers/slanted_triangular.py | Apache-2.0 | 7,056 | 10ad712a68be7a4da5376cb7f3dc17f8ae215b49 | Python | py | |
import onnx
import torch
from onnx_pytorch.op_code_generators import OpCodeGenerator
class AndOpCodeGenerator(OpCodeGenerator):
def __init__(self,
onnx_ver=onnx.defs.onnx_opset_version(),
torch_ver=torch.__version__):
super(AndOpCodeGenerator, self).__init__(onnx_ver, torch_ver)
... | onnx_pytorch/op_code_generators/And.py | Apache-2.0 | 687 | 4b0922691be696ae59b956b7b1290c41ecb96d9d | Python | py | |
import argparse
import json
import numpy as np
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from pynif3d.common.verification import check_not_none, check_path_exists
from pynif3d.datasets import Shapes3dDataset
from pynif3d.models import ConvolutionalOccupancyNetworksModel, PointNet_Loca... | examples/con/evaluate.py | MIT | 6,041 | d7d2a5846b3e00830354c1f99157370e07238198 | Python | py | |
import argparse
import os
import pathlib
import time
import torch
import multicam
import yolov3
def yolo_multicam_detect_demo(
frames, net, device, class_names=None, duplicate_streams=0, prob_thresh=0.05
):
"""
Args:
frames (List[np.ndarray]): List of frames from each video stream.
net (... | demo/demo.py | MIT | 4,860 | febc12c7b20d6f510f68d009b822bb2d7ee5a77c | Python | py | |
"""
MLP models.
File adapted from https://github.com/ds4dm/ecole
by Lars Sandberg @Sandbergo
May 2021
"""
import torch
class MLP1Policy(torch.nn.Module):
def __init__(self):
super().__init__()
var_nfeats = 19
self.output_module = torch.nn.Sequential(
torch.nn.LayerNorm(var_n... | branch2learn/models/mlp.py | MIT | 1,965 | e9add58f073d22362e615a0f5cd47c2e2e16de7e | Python | py | |
import torch
class KPDetection:
def __init__(self,so_path,kp_pt,person_pt) -> None:
self.so_path = so_path
self.kp_pt = kp_pt
self.person_pt = person_pt
torch.ops.load_library(so_path)
self.model = torch.ops.hr_keypoints
def forward(self,img):
img = torch.from_n... | keypoints_onnxdemov2/keypoints_cpp.py | MIT | 418 | febc1f1df454d418eb6d3263b528566ab35f6d31 | Python | py | |
import torch
from bert_seq2seq.tokenizer import load_chinese_base_vocab, T5PegasusTokenizer
from bert_seq2seq.extend_model_method import ExtendModel
import glob
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
from bert_seq2seq.t5_ch import T5Model
vocab_path = "./state_dict/t5-chinese/vocab.t... | test/t5_chinese_autotitle_test.py | Apache-2.0 | 765 | 45fc3cc0e3f7bdbd202d9aac0d0b9338ab2771c2 | Python | py | |
# Copyright 2021 Jacob Durrant
# 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, sof... | models/voxel.py | Apache-2.0 | 2,292 | 24aa3ae836d459c3af2f6f76b4f4662763c9807f | Python | py | |
import argparse
import os
import time
from datetime import datetime
import numpy as np
import torch
import ujson as json
from torch.utils.data import DataLoader
from transformers import AutoConfig, AutoModel, AutoTokenizer
from transformers.optimization import AdamW, get_linear_schedule_with_warmup
from model_balancel... | train_balanceloss.py | MIT | 14,481 | b2be92ad0ae1dfe454a633605b694f937415465d | Python | py | |
from math import prod
from typing import Union, OrderedDict, Optional
import numpy as np
import torch
from torch import Tensor
class BaseNormalizer(torch.nn.Module):
__constants__ = ["_scalar_values"]
def __init__(self, dimensions: int, scalar_values: bool = False, initial_lower_bound: Optional[torch.Tensor... | util/normalizer.py | MIT | 7,416 | 6b34d151ee25b1508604853d5cca07e3aeff4f28 | Python | py | |
#%%
import torch
import torch.nn as nn
import torch.optim as optim
import random
import torch.utils.data as data
import os
import os.path as path
import config_PL as config
import model_PL as model
import dataset_PL as dataset
import loss
import utils
import pytorch_lightning as pl
from getpaths import getpath
import p... | train_PL.py | Apache-2.0 | 2,439 | d79327f3e7a04941ae5a931be75654ee870ed798 | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2020 Patrick Lumban Tobing (Nagoya University)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
from __future__ import division
from distutils.util import strtobool
import argparse
import logging
import math
import os
import sys
import time
import... | src/bin/decode_wavernn_dualgru_compact_lpc_mband_16bit.py | Apache-2.0 | 12,789 | febcbffb70fad15f787cee3b46c4c3e61f395538 | Python | py | |
#######################################################################################
# Adapted from https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
#######################################################################################
from __future__ import print_function, division
import t... | train_model.py | MIT | 8,009 | febcd59547b4c2f5d78b18fd28d6e41b0157e526 | Python | py | |
import sys
import numpy as np
import torch
from collections import defaultdict, Counter
import random
import ipdb as pdb
class RDyck1Language():
def __init__(self, p, q):
self.pair_nums = 1
self.pairs = ['()']
self.vocabulary = ['(', ')']
self.n_letters = len (self.vocabulary)
self.openpar= [elt[0] for elt ... | src/utils/reset_dyck_generator.py | MIT | 3,245 | febce5d77470be797805106455454343eed1182b | Python | py | |
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.training.optimizers import Optimizer
from allennlp.common.testing import AllenNlpTestCase
from allennlp.training.learning_rate_schedulers import LearningRateScheduler
from allennlp.common.params import Params
class LearningRateScheduler... | allennlp/tests/training/learning_rate_schedulers/learning_rate_scheduler_test.py | Apache-2.0 | 3,025 | febcefbdfb877a075842a57ac0a9abd1444ab8be | Python | py | |
import torch
import numpy as np
import multiprocessing as mp
def geodesic_distance(pos, face, src=None, dest=None, norm=True,
max_distance=None, num_workers=0):
r"""Computes (normalized) geodesic distances of a mesh given by :obj:`pos`
and :obj:`face`. If :obj:`src` and :obj:`dest` are g... | torch_geometric/utils/geodesic.py | MIT | 3,360 | febd012fcc79f48287d70f1afad20079e1182425 | Python | py | |
# Code for "ActionCLIP: ActionCLIP: A New Paradigm for Action Recognition"
# arXiv:
# Mengmeng Wang, Jiazheng Xing, Yong Liu
import torch.optim as optim
from utils.lr_scheduler import WarmupMultiStepLR, WarmupCosineAnnealingLR
def _optimizer(config, model, fusion_model):
if config.solver.optim == 'adam':
... | utils/solver.py | MIT | 2,954 | febd1126722344ea8788bbb261aeb7b7113ec861 | Python | py | |
""" Statistics calculation utility """
from __future__ import division
import time
import math
import sys
from onmt.utils.logging import logger
class Statistics(object):
"""
Accumulator for loss statistics.
Currently calculates:
* accuracy
* perplexity
* elapsed time
"""
def __init_... | onmt/utils/statistics.py | MIT | 4,188 | e976adfbd01e4990674d74a8a6d7b0193ddf4708 | Python | py | |
import os
import numpy as np
import torch
import logging
import zconf
import jiant.utils.python.io as py_io
from jiant.utils.display import maybe_tqdm
import jiant.shared.initialization as initialization
import jiant.shared.model_resolution as model_resolution
import jiant.proj.main.components.container_setup as cont... | jiant/scripts/benchmarks/xtreme/xtreme_submission.py | MIT | 16,789 | febd3adebd39156d8b848c6ce5cd6bf848af260e | Python | py | |
import torch
import torch.nn as nn
import torch.optim as optim
from data.dataset_benchmark import BenchmarkDataset
from model.gan_network_sn import Generator, Discriminator
from model.gradient_penalty import GradientPenalty
from models.pointnet import PointNetCls, feature_transform_regularizer
from models.pointnet2 i... | evaluate.py | MIT | 12,042 | 12af9a7cb3d4630ded766d7972fa4c1834a3d1f3 | Python | py | |
import torch
import torch.nn as nn
from torch.nn.functional import mse_loss
class AvgLoss(nn.Module):
def __init__(self):
super().__init__()
self.criterion = nn.MSELoss(reduction="none")
def forward(self, x, y):
res = self.criterion(x, y)
return res.mean(dim=1)
class SonarPr... | habitat_baselines/rl/ppo/aux_sonar.py | MIT | 1,560 | febd9b018f4cb430aa41fadc2e20deac077b0a7e | Python | py | |
# Copyright (c) 2021, Soohwan Kim. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | kospeech/models/conformer/modules.py | Apache-2.0 | 6,499 | d741417748ab5c903d536e37be84aa0e690a940a | Python | py | |
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
from utils.masked_cross_entropy import *
from utils.config import *
import random
import numpy as np
import datetime
from utils.measures import wer,moses_multi_bleu
import nltk
from sklearn.met... | models/enc_vanilla.py | MIT | 14,994 | a96f70c4afaf25e545de28b74692b01075d13a49 | Python | py | |
#!/usr/bin/env python3
import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union
import string
import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn
from pathlib i... | src/run_finetuning.py | MIT | 24,346 | febdae36adcf64da82960f8c83f223676ba380b4 | Python | py | |
"""UCF24 Dataset Classes
Author: Gurkirt Singh for ucf101-24 dataset
"""
import os
import os.path
import torch
import torch.utils.data as data
import cv2, pickle
import numpy as np
CLASSES = ( # always index 0
'Basketball', 'BasketballDunk', 'Biking', 'CliffDiving', 'CricketBowling', 'Diving', 'Fencing',
... | data/ucf24.py | MIT | 10,414 | febdaedd22c47b2b94de67b52601d8dbac202b88 | Python | py | |
#!/usr/bin/env python3
# Copyright 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.
"""Implementation of the RNN based DrQA reader."""
import ipdb
import torch
import torch.nn as nn
from torch.n... | reader/multi_fusionnet/rnn_reader.py | MIT | 11,655 | febdbcef4d327e83b14acf1af83df953ade520ec | Python | py | |
from torch import nn
__all__ = ["DepthwiseSeparableConv2d"]
class DepthwiseSeparableConv2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True):
super(DepthwiseSeparableConv2d, self).__init__()
self.depthwise = nn.Conv2d(
... | pytorch_toolbelt/modules/dsconv.py | MIT | 771 | febdc29ec636c92c760bfa490b2d939edb768af5 | Python | py | |
# import multiprocessing
import math
import numpy as np
import torch
from pykdtree.kdtree import KDTree
def compute_iou(occ1, occ2):
"""Computes the Intersection over Union (IoU) value for two sets of
occupancy values.
Args:
occ1 (tensor): first set of occupancy values
occ2 (tensor): sec... | src/third_party/ConvONets/common.py | MIT | 13,789 | febdd13aea201ee6757119190b4013ece30e4456 | Python | py | |
# coding=utf-8
# Copyright 2020 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 law... | tests/test_modeling_encoder_decoder.py | Apache-2.0 | 15,167 | e61ef2cee4fce68484c906151bbd57d0ed61298e | Python | py | |
import numpy as np
import torch
from torch.utils.data import DataLoader
from torch.utils.data.dataloader import default_collate
from torch.utils.data.sampler import SubsetRandomSampler
from transformers import AutoTokenizer
class AlignCollate:
# if use phobert embedding
def __init__(self, max_length=50):
... | data_loader/base_data_loader.py | MIT | 2,874 | 7cb2ea2ba9b04ad309c1359a0dc9f792220dd89f | Python | py | |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | pytorch_lightning/callbacks/stochastic_weight_avg.py | Apache-2.0 | 13,224 | 7c8b33e2725684d66b0d72e4bd20d3b92d61b2a5 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from torch.cuda.amp import autocast, GradScaler
import os
import contextlib
from train_utils import AverageMeter
from .remixmatch_utils import consistency_loss, Get_Scalar, one_hot, mixup_one_target
from train_util... | models/remixmatch_abc/remixmatch_abc.py | MIT | 17,283 | dfd6fbedbe2d053fe8659598f8ea400a0ddaf660 | Python | py | |
# -*- coding: utf-8 -*-
"""This module implements an abstract base class (ABC) 'BaseDataset' for datasets.
It also includes common transformation functions (e.g., get_transform, __scale_width), which can be later used in subclasses.
"""
import random
import numpy as np
import torch.utils.data as data
from PIL import ... | data/base_dataset.py | Apache-2.0 | 5,425 | febe088831bbdc115cb86456d80f4ee6030ac056 | Python | py | |
import torch.nn as nn
from models.backbones.wideresnet import WideResNet
from models.classifiers.basic_classifiers import FC_Classifier, Cos_Classifier, \
Dot_Classifier, PostNorm_Classifier, TDESim_Classifier,\
PostProc_Classifier, CDT_Classifier, CosPlus_Classifier, Cos_Center_Classifier
from models.classifie... | models/Networks.py | FSFAP | 4,363 | febe126a9fbaea3064b2a7d90b606f5341eae282 | Python | py | |
'''
Description:
Author: Jinguang Tong
Affliction: Australia National University, DATA61 CSIRO
Date: 2021-07-26 14:05:16
LastEditTime: 2021-08-03 18:00:27
'''
import torch
import os
import sys
sys.path.append(os.getcwd())
from torch import nn
from modules.functions import *
class Integrator(nn.Module):
def __ini... | modules/integrator.py | MIT | 3,413 | b263597aaaeafcaca62f41905b577b20c6686530 | Python | py | |
import torch
import os
import statistics
import numpy as np
import hpbandster.core.result as hpres
from envs.env_factory import EnvFactory
import matplotlib.pyplot as plt
# from gridworld.py
G_RIGHT = 0
G_LEFT = 1
G_DOWN = 2
G_UP = 3
LOG_DIR = '/home/nierhoff/master_thesis/learning_environments/results/GTNC_evaluate... | experiments/GTNC_visualize_gridworld_learned_reward_env.py | MIT | 6,502 | e634359deb4c5dcf9896da0f77fba80f4925fa4f | Python | py | |
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Train a YOLOv5 model on a custom dataset
Usage:
$ python path/to/train.py --data coco128.yaml --weights yolov5s.pt --img 640
"""
from shutil import copyfile
from datetime import datetime
import argparse
import logging
import math
import os
import random
import sy... | train/train.py | MIT | 34,429 | 7084ab17bf2e98ef789e641adb821d3b353250b7 | Python | py | |
import numpy as np
import sys, csv, os
import torch
from torch.utils.data import DataLoader
from dgl.data.utils import split_dataset
from model import training, inference
from dataset import GraphDataset
from util import collate_reaction_graphs
from model import reactionMPNN
from sklearn.metrics import r2_score, mean... | run_code.py | Apache-2.0 | 2,776 | febe48cd4529b86b70859f6aabc3a075ed7cea7e | Python | py | |
import os
import torch
import random
import pickle
import numpy as np
import torchvision.transforms as transforms
import torch.nn.functional as F
from PIL import Image
from torch.utils.data.dataset import Dataset
from libs.utils import *
from libs.modules import *
from libs.line_generator import *
class Train_Datas... | Reflection_symmetry_axes_detection/DNet/code/dataset.py | MIT | 9,227 | ff3a022de496ea196ff286c55687149df1a70645 | Python | py | |
from ..registry import DETECTORS
from .two_stage import TwoStageDetector
import torch
import torch.nn as nn
from mmdet.core import bbox2result, bbox2roi, build_assigner, build_sampler
from .. import builder
from .test_mixins import BBoxTestMixin, MaskTestMixin, RPNTestMixin
from ..domain_classifier import DC_img
impor... | mmdet/models/detectors/MAF.py | Apache-2.0 | 15,188 | d721431f635c996bdc1add31d9c342549ddef0aa | Python | py | |
import numpy as np
import time
import os
import torch
import _pickle as cPickle
from src.RL import RL
from src.toric_model import Toric_code
from NN import NN_11, NN_15, NN_17
from ResNet import ResNet18, ResNet34, ResNet50, ResNet101, ResNet152
#########################################################################... | train_script.py | MIT | 2,575 | 5fa92e6bd6234e89305bf8ae12a05dd4a70c4c79 | Python | py | |
"""Torch modules for graph attention networks(GAT)."""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from .... import function as fn
from ...functional import edge_softmax
from ....base import DGLError
from ..utils import Identity
from ....utils import expand_as_p... | python/dgl/nn/pytorch/conv/gatconv.py | Apache-2.0 | 13,579 | 28f1fbdb6938f2b1dc1cd30a1f58cee909aaf07b | Python | py | |
import torch
import numpy as np
import yaml, librosa, pickle, os
from random import sample, shuffle
from itertools import combinations
from Audio import Audio_Prep, Mel_Generate
with open('Hyper_Parameter.yaml') as f:
hp_Dict = yaml.load(f, Loader=yaml.Loader)
class Train_Dataset(torch.utils.data.Dataset):
d... | Datasets_bak.py | MIT | 10,343 | ff7edf65e9a04edc1c02fe0c74868c9f3c33d445 | Python | py | |
import torch
from torch import optim
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super(Net,self).__init__()
self.fc1 = nn.Linear(5,2)
self.fc2 = nn.Linear(5,3)
def forward(self,x):
x1 = self.fc1(x)
x2 = self.fc2(x)
return x1,x2
def testgrad(... | Stage_3 Multi-classification/testgrad.py | MIT | 2,276 | febe7868f32c9459f3f8d4837f77118d0f9e06a1 | 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 pprint
from typing import List, Union
import torch
from classy_vision.generic.util import is_pos_int
from classy_vision.meters import Cl... | vissl/meters/mean_ap_list_meter.py | MIT | 5,161 | 421da71f4a7fd775c5a8538b3f609f64c50c1104 | Python | py | |
# This file is covered by the LICENSE file in the root of this project.
import torch
from torch.utils.data import Dataset
import torchvision.transforms as transforms
import os
import numpy as np
from PIL import Image
import random
import torchvision.transforms.functional as TF
import cv2
import albumentations
'''
me... | train/tasks/segmentation/dataset/coco/parser.py | MIT | 11,308 | febe9caff30c4c5925f69b6fb2c2a2036def020b | Python | py | |
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from collections import OrderedDict
# from .utils import load_state_dict_from_url
from torch import Tensor
from torch.jit.annotations import List
__all__ = ['DenseNet', 'densenet121', 'densenet1... | Networks/DenseNet.py | MIT | 12,712 | 4568ef68f41033f45566040599931d3cbcfb8e42 | 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... | 3d_segmentation/torch/unet_training_dict.py | Apache-2.0 | 7,948 | febecb4162584eed3b23641ae83992c8f362c928 | Python | py | |
from torch import models as model
from torchsummary import summary
PATH='/home/tione/notebook/x/mmdetection/checkpoints/vfnet_r50_fpn_mdconv_c3-c5_mstrain_2x_coco_20201027pth-6879c318.pth'
# model_dict=torch.load(PATH)
model_dict=model.load_state_dict(torch.load(PATH))
# summary(model, (3, 1333, 800))
print(model_dict... | model_vis.py | Apache-2.0 | 321 | 28c6b95df75f5dc7ee75e28e8c91856ae89c7285 | Python | py | |
"""
This script combines training_OnlineContrastiveLoss.py with training_MultipleNegativesRankingLoss.py
Online constrative loss works well for classification (are question1 and question2 duplicates?), but it
performs less well for duplicate questions mining. MultipleNegativesRankingLoss works well for duplicate
quest... | examples/training_quora_duplicate_questions/training_multi-task-learning.py | Apache-2.0 | 9,674 | 24945a4d5072444c1b044f8db0158c59139f00ee | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.... | built-in/PyTorch/Official/cv/image_object_detection/Faster_Mask_RCNN_for_PyTorch/detectron2/utils/comm.py | Apache-2.0 | 13,206 | d7c16e03b5bf44ea76ed79a381832f34aa710b94 | Python | py | |
import os
import torch
import numpy as np
import SimpleITK as sitk
from blast_ct.nifti.datasets import FullImageToOverlappingPatchesNiftiDataset
from blast_ct.nifti.patch_samplers import get_patch_and_padding
from blast_ct.nifti.rescale import create_reference_reoriented_image
CLASS_NAMES = ['background', 'iph', 'eah'... | blast_ct/nifti/savers.py | Apache-2.0 | 5,909 | f9712963139547a502b13b5f3e335ef1967500d0 | Python | py | |
#!/usr/bin/env python
# coding=utf-8
# Copyright 2021 The HuggingFace Inc. 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/LI... | examples/pytorch/question-answering/run_qa_no_trainer.py | Apache-2.0 | 35,536 | febf1b616d44864cbaf2b1c0eb2e9d63b9ee9661 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import contextlib
import datetime
import io
import itertools
import json
import logging
import pickle
import numpy as np
import os
import shutil
import pycocotools.mask as mask_util
import multiprocessing as mp
from itertools import product
from fvcore.common.timer im... | herbarium/data/datasets/herb.py | Apache-2.0 | 17,175 | ff1cc418cd5ea6201f4b628153aeeac53a1e8cda | Python | py | |
# -*- coding: utf-8 -*-
"""autoencoder+deepgp_colab.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1QpjIw_BKCmtlV0Meg9YBGKGP85btug0Y
"""
!pip install gpytorch -q
!pip install datatable -q
# Commented out IPython magic to ensure Python compatibi... | autoencoder+deepgp_colab.py | Apache-2.0 | 13,621 | 5e3aecefa65fb0ad50e93bc1b7f777fc80ca0dc9 | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2018 Nagoya University (Tomoki Hayashi)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""E2E-TTS training / decoding functions."""
import copy
import json
import logging
import math
import os
import time
import chainer
import kaldiio
import nu... | espnet/tts/pytorch_backend/tts.py | Apache-2.0 | 33,178 | febf3a04e7791a51c11deda9036a4532fee092f2 | Python | py | |
import argparse
import os, sys
import numpy as np
import torch as tc
sys.path.append("../../")
def to_tree_namespace(params):
"""
handle only depth-1 tree
"""
for key, val in vars(params).copy().items():
if "." in key:
delattr(params, key)
group, sub_key = key.split("."... | demo/conf_set/opts/options.py | Apache-2.0 | 25,912 | febf5539b306b3e807dce12e873b517d4539a6e8 | Python | py | |
import argparse
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
from torch.utils.data import DataLoader
import mdd.transforms.defaults as t
from mdd.data.dataset import CyclicDataset
from mdd.data.domain_adaptation import ImageClef, Office31, OfficeHome
from mdd.models im... | main.py | MIT | 7,795 | 426162ff194a8ed642b898e1e08b28fa4d8d4b92 | Python | py | |
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.utils.data as Data
from torch.autograd import Variable
import matplotlib.pyplot as plt
import numpy as np
import os
import torch.nn.functional as F
from prettytable import PrettyTable
import time
# predefine some const
EPO... | v11 1D-CNN.py | Apache-2.0 | 5,599 | fdbfc1c7ab463f624c44e5e3483b58c6b89ca564 | Python | py | |
import os
import os.path
import glob
import cv2
import numpy as np
import torch
import torchvision.utils
import models.modules.architectures.seg_arch as seg_arch
from data.util import imresize, modcrop
import utils.util as util
# options
test_img_folder_name = 'samples' # image folder name
test_img_folder = '../da... | codes/test_seg.py | Apache-2.0 | 3,227 | 1044d178b335c54f82f786e1e4cda6bf4324aae5 | Python | py | |
from torch.utils.data import DataLoader, Dataset, Sampler
from pathlib import Path
from collections import defaultdict
import json
import random
from multiprocessing import Pool
import h5py
import pickle
import math
from tqdm import tqdm
import torch
import numpy as np
from torch.utils.data.distributed import Distrib... | VL-T5/src/gqa_raw_data.py | MIT | 15,756 | 12e86d864457ce447dfb5590ecd415c9a4eba4ba | Python | py | |
"""
Utility functions to construct model.
Reference: https://github.com/qiuqiangkong/audioset_tagging_cnn/blob/master/pytorch/models.py
The MIT License
"""
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def freeze_model(model):
for name, param in model.named_par... | models/model_utils.py | MIT | 20,835 | 70750b3ed704e86157e3e0e51dce3331ea03a829 | Python | py | |
import torch
def ker_by_channel(channel, ker):
m, _ = channel.size()
k, _ = ker.size() # assumes square kernel
channel_v = channel.view(-1)
dbl_circulant = torch.zeros((m-k+1)**2, m**2)
shift = 0 # controls shift when convolution switches to new row
for i in range(dbl_circulant.size(0)):
... | test.py | MIT | 1,659 | febf6ec14c18a13d239b0cce1cedafaa19735d65 | Python | py | |
import os.path as osp
import PIL
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
THIS_PATH = osp.dirname(__file__)
ROOT_PATH = osp.abspath(osp.join(THIS_PATH, '..'))
IMAGE_PATH = osp.join(ROOT_PATH, 'data/cub/images')
SPLIT_PATH = osp.join(ROOT_PATH, 'd... | examples/fewshot/dataloader/cub.py | MIT | 1,991 | 6b42ccd6715401d6787e4bcd47678369368c38dd | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Conv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1):
super(Conv, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size, stride, kernel_size/... | SPP_PANet.py | MIT | 4,029 | dff8484630a5c7d0660470c1b329e408865e2478 | Python | py | |
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import argparse
import torch
from torch.distributions import constraints
import pyro
import pyro.optim
import pyro.distributions as dist
from pyro.infer import SVI, config_enumerate, TraceEnum_ELBO
from pyro.contrib.autoname imp... | examples/contrib/autoname/scoping_mixture.py | Apache-2.0 | 2,264 | e98dde49563ab7ddca6d4dc447bbe0bb43e30564 | Python | py | |
import copy
import torch
import torch.nn as nn
import numpy as np
from typing import Dict
from yacs.config import CfgNode
from module.unet import UNet
from data.preprocess import RandomCrop, Resize
class FENs(nn.Module):
def __init__(self,
cfg: CfgNode,
init_freeze: bool = False... | module/fen.py | MIT | 6,795 | 5e2e5dc93c04d903252e171521735bf7fa714a9d | Python | py | |
'''
This script handling the training process.
'''
import argparse
import math
import time
from tqdm import tqdm
import torch
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
import transformer.Constants as Constants
from dataset import TranslationDataset, paired_collate_fn
from tra... | train.py | MIT | 9,939 | febfbcf6e79eb371b90191b3edd08189466db5a9 | Python | py | |
"""
Copyright (c) 2018 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 writin... | pytorch_toolkit/face_recognition/train.py | Apache-2.0 | 13,681 | 03bbe4f6d312ef6311b3ec90b3d3de98ca745e83 | Python | py | |
import math
import torch
from torch import nn, einsum
from einops import rearrange
# translated from tensorflow code
# https://gist.github.com/aravindsrinivas/56359b79f0ce4449bcb04ab4b56a57a2
# positional embedding helpers
def pair(x):
return (x, x) if not isinstance(x, tuple) else x
def expand_dim(t, dim, k):... | bottleneck_transformer_pytorch/bottleneck_transformer_pytorch.py | MIT | 7,255 | 1091a8d4e030a6a1528af7619663d91fa39418a7 | Python | py | |
#! /usr/bin/env python
# Copyright (c) 2019 Uber Technologies, Inc.
#
# 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... | ludwig/features/text_feature.py | Apache-2.0 | 17,298 | fda8c97b73ab04e5a548c4c984eab939494a7e99 | Python | py | |
#!/usr/bin/env python3 -u
# 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.
"""
Train a new model on one or across multiple GPUs.
"""
import sys
import collections
import math
import random
imp... | train.py | MIT | 13,535 | fec02e5683d547463e1d2ce07cdb391948ec3966 | Python | py | |
import numpy as np
import torch
class ResidualCoder(object):
def __init__(self, code_size=7, encode_angle_by_sincos=False, **kwargs):
"""
loss中anchor和gt的编码与解码
7个参数的编码的方式为
∆x = (x^gt − xa^da)/d^a , ∆y = (y^gt − ya^da)/d^a , ∆z = (z^gt − za^ha)/h^a
∆w = log (w^gt / w^... | pcdet/utils/box_coder_utils.py | Apache-2.0 | 10,701 | fec03fb9697451e150231665d851fcd12a49fab6 | 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... | tests/collections/asr/test_label_datasets.py | Apache-2.0 | 4,842 | fec04a5459904ed9224c334ff47dda18d454380f | Python | py | |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import logging
import math
import pytest
import torch
from torch.autograd import grad
from torch.distributions import constraints
from tests.common import assert_equal
# put all funsor-related imports here, so test collection works ... | tests/contrib/funsor/test_tmc.py | Apache-2.0 | 6,348 | fec050cb488532f583130550b01a22422eeafceb | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.