content stringlengths 200 198k | repo stringlengths 4 186 | path stringclasses 1
value | license stringclasses 101
values | size int64 200 198k | sha stringlengths 40 40 | lang stringclasses 1
value | ext stringclasses 1
value |
|---|---|---|---|---|---|---|---|
import copy
import tempfile
from dataclasses import asdict
import torch
from transformers import (
ADAPTERFUSION_CONFIG_MAP,
MODEL_WITH_HEADS_MAPPING,
AdapterConfig,
AutoModelWithHeads,
PfeifferConfig,
)
from transformers.adapters.composition import Fuse
from transformers.testing_utils import requ... | tests/test_adapter_fusion_common.py | Apache-2.0 | 7,750 | 24b82c45e3de84f461d66f2c98b7b03fa82f2879 | Python | py | |
import numpy as np
import torch
import sys
sys.path.append('../../')
import popsan_drl.popsan_td3.core_cuda as core
class ReplayBuffer:
"""
A simple FIFO experience replay buffer for DDPG agents.
with Running Mean and Var from hill-a/stable-baselines
"""
def __init__(self, obs_dim, act_dim, siz... | popsan_drl/popsan_td3/replay_buffer_norm.py | MIT | 4,023 | 8b3818c6669e2200acdab60ca044b388e622c265 | Python | py | |
r"""Parameterizable probability distributions and sampling functions."""
import math
import torch
from textwrap import indent
from torch import Tensor, Size
from torch.distributions import *
from torch.distributions import constraints
from typing import *
from .transforms import *
Distribution._validate_args = Fal... | lampe/distributions/__init__.py | MIT | 17,041 | 8b381ce9e238ab4815c112753253f73e17037fa3 | Python | py | |
#!/usr/bin/python3
"""
Copyright 2018 Marco Lattuada
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 ... | apps/pytorch.py | Apache-2.0 | 46,668 | 8b3820fb50199d114e2d79424f364d5efad7305a | Python | py | |
import torch
from difflr.models import LinearClassifier
from difflr.data import MNISTDataset
from difflr import CONFIG
from difflr.experiments import Tuner
import time
CONFIG.DRY_RUN = False
def main():
torch.manual_seed(0)
start_time = time.time()
config = {
'model_name': 'simpleffn_tuned',
... | difflr/experiments/hpt_experiments/archived_experiments/experiment_v1.py | MIT | 892 | 8b38230bf627acc21efa6f5d9643300fc94bb6f3 | Python | py | |
import torch
import torch.nn as nn
class WordEmbedding(nn.Module):
def __init__(self, args, is_train_embd=True): # In QA-LSTM model, embedding weights is fine-tuned
super(WordEmbedding, self).__init__()
self.embedding = nn.Embedding(args.vocab_size, args.embd_size)
if args.pre_embd is not ... | models.py | Apache-2.0 | 1,320 | 8b38374d1154fc58605b9c900cde7d452a19d196 | Python | py | |
import torch
from transformers import BertTokenizer, BertModel
from BeamSearcher import BeamSearcher
from format_attn_tuple import format_attn_tuple
torch.set_printoptions(profile="full")
#sentence_a = "Dylan is a songwriter"
sentence_a = input("Please input your sentence: \n")
print("\nReceive sentence: ", sentenc... | test-beam-searcher.py | Apache-2.0 | 896 | 8b385e5bff82f80232e37ad63d8597c02a7c8327 | Python | py | |
import os
import pickle
import torch
from torch.utils.data import Dataset
from problems.op.state_op import StateOP
from utils.beam_search import beam_search
class OP(object):
NAME = 'op' # Orienteering problem
@staticmethod
def get_costs(dataset, pi):
if pi.size(
-1
) ... | problems/op/problem_op.py | MIT | 5,103 | ffb72563d5e45ab48107585277137086e3576ba2 | 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/loops/epoch/evaluation_epoch_loop.py | Apache-2.0 | 9,672 | 8b38d0f898aaf1d65972286736c4da5c4b86d3cd | Python | py | |
import argparse
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import normalize
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch.optim import Adam
import utils
from model import GAT, pseudo_gat
from evaluation imp... | DAEGC/custom_pretrain.py | MIT | 2,954 | 8b38f75c5f4fb5833c6d961ccef62c9f9b7069f5 | Python | py | |
#!/usr/bin/env python3
import argparse
import os
import os.path
import ctypes
from shutil import rmtree, move
from PIL import Image
import torch
import torchvision.transforms as transforms
import torch.nn.functional as F
import model
import dataloader
import platform
from tqdm import tqdm
# For parsing commandline arg... | video_to_slomo.py | MIT | 7,918 | e9e12ba5bcb884539f820c316fe99093a51340b5 | Python | py | |
import time
import datetime
from collections import defaultdict, deque
import torch
import torch.distributed as dist
import os
import errno
def distributed_concat(tensor, num_total_examples):
output_tensors = [tensor.clone() for _ in range(dist.get_world_size())]
dist.all_gather(output_tensors, tensor)
co... | opendc/train/utils.py | MIT | 6,289 | 455854119e899935dacf600c0131c7f4833940de | Python | py | |
import numpy as np
#import pyvirtualcam
import argparse
import cv2
import sys
import os
import mxnet as mx
import datetime
from skimage import transform as trans
#import insightface
import configparser
import torch
import time
def square_crop(im, S):
if im.shape[0] > im.shape[1]:
height = S
width =... | emotion_analysis/yolo_insightface/model_implementation.py | MIT | 5,778 | 52cdbb1f7f5fac03a1389c15ee63c3669fdafed1 | Python | py | |
import logging
import copy
import torch as th
import torch.nn as nn
from pgc_torch.utils.graph import NLayerFeedForwardNet
from pgc_torch.utils.substructure import V1Inception, InceptionBaseRoute, EMTABMetaClass
logger = logging.getLogger('django')
IncMapping = dict()
EMTABMetaClass.IncMapping = IncMapping
class ... | pgc_torch/emb_net/graphs/graph0.py | MIT | 4,765 | 4b83a5250307dcd84c22d64f6cca24cb66304b88 | Python | py | |
import argparse
import os, time, random
import numpy as np
import gym
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from utils.tools import hard_update, soft_update, OUNoise, get_output_folder
from utils.buffer import ReplayBuffer
from utils import logz
FloatTensor = to... | V1/DDPG/ddpg_v3.py | Apache-2.0 | 7,911 | e91dee4b83f7a47170316893db0cf08c2a116119 | Python | py | |
# The fastai DataLoader is a drop-in replacement for Pytorch's;
# no code changes are required other than changing the import line
from fastai.data.load import DataLoader
import os,torch
from torch.nn import functional as F
from catalyst import dl
from catalyst.contrib.data.transforms import ToTensor
from catalyst.co... | nbs/examples/migrating_catalyst.py | Apache-2.0 | 1,335 | 1e02572d06aeaf4aaff11336460ba622b0735e1d | Python | py | |
from __future__ import division
import os, time, scipy.io
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import glob
import re
import cv2
import argparse
from PIL import Image
from models import ISP
from tensorboardX import SummaryWriter
from utils import *
parser = argparse.Argument... | train_isp.py | CC-BY-4.0 | 3,642 | 24c3cd89d5c3914cf65abc78f65ae5f523360d4c | Python | py | |
""" TensorMONK :: utils """
import torch
import numpy as np
import PIL.Image as ImPIL
import random
from typing import Union
from PIL import ImageDraw, ImageOps
from torchvision import transforms
class PillowUtils:
tensor_to_pil = transforms.ToPILImage()
@staticmethod
def to_pil(image: Union[str, ImPIL.... | tensormonk/utils/pillow_utils.py | MIT | 18,675 | 29f9149612d01f9aecb3611dc70f3e801e1360ed | Python | py | |
import cv2
import torch
import numpy as np
from torchvision import transforms, ops
#########################################################################################################
SIZE = 224
SEGMENT_SIZE = 520
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
IMAGENET_MEAN = [0.485, 0.456... | References and Tests/Pytorch Tests/utils.py | MIT | 27,731 | e92b243b17ce3472e2c849a8c88ec0c79ca75f57 | Python | py | |
import torch
import torch.optim as optim
import torch.utils.data
import time
from datetime import datetime
import torch.nn.functional as F
from torch.autograd import Variable
from model_logging import Logger
from wavenet_modules import *
def print_last_loss(opt):
print("loss: ", opt.losses[-1])
def print_last_v... | wavenet_training.py | MIT | 4,717 | 8b396b3c32b4542de7c135c72dd599b1fe4214d0 | 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/trainer/trainer.py | Apache-2.0 | 48,272 | 10545a075cb32e6c2e3c67fa442c9d3505e0caea | 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_20190106182642.py | MIT | 17,266 | 8b397f5e03a5d176162f1f7e75266c12ad51c4fb | Python | py | |
# -*- coding: utf-8 -*-
# @Time : 2021/9/29 14:09
# @Author : vivian
from torch import nn
from models.losses.basic_loss import BalanceCrossEntropyLoss, MaskL1Loss, DiceLoss
class DBLoss(nn.Module):
def __init__(self, alpha=1.0, beta=10, ohem_ratio=3, reduction='mean', eps=1e-6):
"""
Implement... | models/losses/DB_loss.py | Apache-2.0,MIT | 4,846 | ff127c5bd08399198c8b22117d1fd2a752590bdb | Python | py | |
"""DenseNet module."""
import torch
import torch.nn as nn
from typing import List
from mdlearn.nn.utils import get_activation
class DenseNet(nn.Module):
def __init__(
self,
input_dim: int,
neurons: List[int] = [128],
bias: bool = True,
relu_slope: float = 0.0,
inpla... | mdlearn/nn/modules/dense_net.py | MIT | 3,058 | 4b9c8f8eee8871c76f7c173f2bd340bf730c6cfe | Python | py | |
'''
Edit form train_ocr
'''
import os, sys
import numpy as np
import cv2
import net_utils
import math
import torch.nn.functional as F
import collections
import glob
import csv
import editdistance
import torch
from ocr_utils import ocr_image, ocr_batch, crnn_batch # next(iter(data_loader))
from data_gen import draw_b... | net_eval.py | MIT | 32,996 | 8b39c27ae88f5e5aa763cdac1776caf9e337e134 | Python | py | |
import os,sys,time
from array import array
import numpy as np
# torch
import torch
import torch.nn as nn
import torch.nn.functional as F
# sparse submanifold convnet library
import sparseconvnet as scn
# ROOT
import ROOT as rt
from larcv import larcv
from func_intersect_ub import IntersectUB
class SparseLArFlow3D... | networks/larflow/models/loss_sparse_larflow.py | Apache-2.0 | 6,419 | 8b39e2f4126d3b3dac6e90a39f306704264acaaa | Python | py | |
import torch
def underline(content, style='-'):
"""Underlining a sentence."""
return content + '\n' + style * len(content.strip())
def empty_tensor():
"""Returns an empty tensor."""
return torch.tensor(0)
def is_empty_tensor(t):
"""Returns whether t is an empty tensor."""
return len(t.s... | utils/__init__.py | MIT | 332 | 1e12ec733069e32f813221f7ac60106a2504f445 | Python | py | |
import torch
from torch import nn
class Swish(torch.autograd.Function):
@staticmethod
def forward(ctx, i):
result = i * i.sigmoid()
ctx.save_for_backward(result, i)
return result
@staticmethod
def backward(ctx, grad_output):
result, i = ctx.saved_variables
sig... | pade_activation_unit/utils.py | MIT | 2,343 | 5f6a3063c0d4de73f853cf5191dfda510a336072 | Python | py | |
""" train extractor (ML)"""
import argparse
import json
import os
from os.path import join, exists
import pickle as pkl
from cytoolz import compose
import torch
from torch import optim
from torch.nn import functional as F
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.data import DataLoader
... | train_extractor_ml.py | MIT | 12,560 | 6b443216a9e96603e586300db0af355e825957f4 | Python | py | |
import torch
import numpy as np
from graphgallery.sequence import FullBatchSequence, Sequence
from graphgallery import functional as gf
from graphgallery.gallery.nodeclas import PyTorch
from graphgallery.gallery.nodeclas import Trainer
from graphgallery.nn.models import get_model
@PyTorch.register()
class GMLP(Traine... | graphgallery/gallery/nodeclas/pytorch/graphmlp.py | MIT | 3,394 | a92af4f406e49c8b37533c9d247775e70cac944e | Python | py | |
from __future__ import division
import sys
import time
import torch
from tqdm import tqdm
tqdm.monitor_interval = 0
from torch.utils.tensorboard import SummaryWriter
from utils import CheckpointDataLoader, CheckpointSaver
import time
class BaseTrainer(object):
"""Base class for Trainer objects.
Takes care of ... | utils/base_trainer.py | MIT | 7,805 | d7c88477534ea7f53a89cee9aa58a66d36a95f5f | Python | py | |
import os
import copy
import numpy as np
from PIL import Image
from os.path import join
from itertools import chain
from collections import defaultdict
import torch
import torch.utils.data as data
from torchvision import transforms
from src.datasets.root_paths import DATA_ROOTS
class Aircraft(data.Dataset):
NUM... | src/datasets/meta_datasets/aircraft.py | MIT | 4,125 | 28c34fd33180f02fb70962f4c826a7678e3ca465 | 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.
#
"""
This file contains the definition of encoders used in https://arxiv.org/pdf/1705.02364.pdf
"""
import numpy as np
import t... | InferSent/model.py | Apache-2.0 | 8,924 | 8b3aa1082acb088c602580df91786c47403abd67 | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import xavier_init
from mmdet.ops.carafe import CARAFEPack
class PixelShufflePack(nn.Module):
""" Pixel Shuffle upsample layer
Args:
in_channels (int): Number of input channels
out_channels (int): Number of output channels
... | mmdet/models/utils/upsample.py | MIT | 2,250 | fd880fb05af1ae0b890af9771a9a1e0feeb52ef6 | Python | py | |
#
# BSD 3-Clause License
#
# Copyright (c) 2017 xxxx
# All rights reserved.
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain ... | built-in/PyTorch/Official/cv/image_classification/DenseNet169_ID0454_for_Pytorch/references/segmentation/train.py | Apache-2.0 | 10,082 | e965eebc4f83e96c69de6cb50012eb60ca2582bb | Python | py | |
######
# Author: Faidon Mitzalis
# Date: June 2020
# Comments: Use results of testing to evaluate distance between [CLS] embeddings
######
import json
import torch
import operator
import numpy as np
# English captions 002:
# filepath_en = "/experiments/faidon/VL-BERT/checkpoints/output/pretrain/pretrain_prec/002_pre... | retrieval/evaluate_distance.py | MIT | 5,591 | 42279fbf611c3f4f53e6714b0d3d29c156b7de41 | Python | py | |
"""
Layer 2 final model.
"""
import re
from collections import defaultdict
import six
import numpy as np
import torch
from torch import nn
from aw_nas import ops, utils
from aw_nas.final.base import FinalModel
from aw_nas.final.cnn_model import AuxiliaryHead, AuxiliaryHeadImageNet
from aw_nas.common import genotype_... | aw_nas/btcs/layer2/final_model.py | MIT | 30,575 | 1034d58a7fb5c1dbc637a8351eb1d6b868bffad8 | Python | py | |
import os
import sys
import random
import math
import numpy as np
import cv2
import json
import pydicom
import pandas as pd
import glob
from PIL import Image
import torch
from torch.utils.data.dataset import Dataset
from torch.utils.data import DataLoader
from torchvision import transforms
from torchsample import St... | pneumoRL/data_util.py | MIT | 7,470 | 8b3ad9bc977c41dd1a79f9ed77173ae84041541a | Python | py | |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
"""
Detection Training Script.
This scripts reads a given config file and runs the training or evaluation.
It is an entry point that is made to train standard models in detectron2.
In order to let one script support training of many models,
this s... | projects/faster_rcnn_swin_transformer/train_net_swit.py | Apache-2.0 | 10,708 | 8b3ae0037a2ae211602e73400743657e01ce2887 | Python | py | |
import pytest
import torch
from torch import nn
from easyfsl.methods import RelationNetworks
class TestPrototypicalNetworksInit:
@staticmethod
@pytest.mark.parametrize(
"backbone",
[
nn.Flatten(),
],
)
def test_constructor_raises_error_when_arg_doesnt_output_3d_fea... | easyfsl/tests/methods/relation_networks_test.py | MIT | 1,405 | 10f90b57f3b8f7702dc6868a70c4eef19a4d49e5 | Python | py | |
import supersuit as ss
import torch
from ray import tune
# from ray.rllib.utils import try_import_tf
from ray.rllib.env.wrappers.pettingzoo_env import ParallelPettingZooEnv
from ray.rllib.models import ModelCatalog
# for APEX-DQN
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.tune.registry imp... | tutorials/rllib_pistonball.py | Apache-2.0 | 3,906 | 8b3aebe3ad3a4c109777793ddbd96a4ab8771e26 | Python | py | |
#STD MODULES
import os
import numpy as np
import math
import shutil
#TORCH MODULES
import torch
import torch.nn as nn
import torch.nn.functional as F
#LOCAL MODULES
from . import netlearningrate
#from . import graphic as gph
from . import utils
#----------------------------------------------------------------------... | pytvision/neuralnet.py | MIT | 11,486 | f9bfd6a390f7e6702baff8f033c16c70fe818efb | Python | py | |
import torch.nn as nn
from .utils import *
warnings.filterwarnings("ignore")
# import gc
use_dmpc = 0
class RRB(torch.nn.Module):
"""
We should use centerline. For the speed, we can use the last value or the value of the closest veh infront.
"""
def __init__(self, n_obs, n_pred, devic... | trajnetbaselines/trajnetbaselines/mlp/mlp.py | BSD-2-Clause | 51,200 | 8b3b25936d8e85481e1ef4b59cdb492f60b0200f | Python | py | |
from torch.optim.optimizer import Optimizer
import numpy as np
class ReduceLROnPlateau(object):
"""Reduce learning rate when a metric has stopped improving.
Models often benefit from reducing the learning rate by a factor
of 2-10 once learning stagnates. This scheduler reads a metrics
quantity and if n... | ailib/lr_scheduler/lr_plateau_reduce.py | Apache-2.0 | 7,038 | 5e38379394f29e5a300e196931ae3091e8dd827c | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as f
import torch.optim as optim
import time
import random, numpy, argparse, logging, os
from collections import namedtuple
import numpy as np
import datetime, math
import gym
# Hyper Parameters
MAX_EPI=10000
MAX_STEP = 10000
SAVE_INTERVAL = 20
TARGET_UPDA... | dqn.py | Apache-2.0 | 10,514 | d76a8295781722dd80e8ee1f82da24e1d8204041 | Python | py | |
import torch
import numpy as np
import tqdm
from apex import amp
from sklearn.metrics import f1_score,precision_score,recall_score,cohen_kappa_score,accuracy_score
from prettytable import PrettyTable
# 计算f1值
def compute_weight_score(class_out, targets, details, number_class, avg_loss, train_logger, epoch):
... | Utils/Trainer.py | MIT | 4,499 | 5f286a14b04c2b35182b70cd7178e50492b2cef5 | Python | py | |
from typing import List, Tuple
import numpy as np
import torch
from torch import nn, optim
from torch.nn import functional as F
from .base_model import VariationalBaseModel
# Convolutional Variational AutoEncoder Model
class ConvVAE(nn.Module):
def __init__(self, input_sz: Tuple[int, int, int] = (3, 64, 64),
... | src/models/conv_vae.py | MIT | 5,237 | e91cc27c532de10ff6c2fead1e3dac5ddffeb74f | Python | py | |
import argparse
import torch
parser = argparse.ArgumentParser(description='ASR training')
parser.add_argument('--model', default='TRFS', type=str, help="TRFS:transformer")
parser.add_argument('--name', default='model', help="Name of the model for saving")
# train
parser.add_argument('--train-manifest-list', nargs='+... | utils/constant.py | MIT | 5,650 | e9548b1553fbe7d1e9d6a482ce7c5974ceb3670e | Python | py | |
import torch
from code.ml.vocab import vocab
from evaluate import compare
from train_lstm_scorer import LSTMScorer
best_path = "scorer_best.bin"
scorer = LSTMScorer(
len(vocab.i2w), 250, 128, 256, emb_dropout=0.1, rnn_dropout=0.25,
pretrained_path="scorer_best.bin"
)
scorer.model.load_state_dict(torch.load... | code/scoring/compare_test_preds.py | Apache-2.0 | 513 | a901d0c61b616245177af2738749a27058f1a8ad | Python | py | |
import warnings
warnings.simplefilter("ignore", UserWarning)
import copy
import datetime
import sys
import os
import time
import shutil
import argparse
import logging
# misc
import numpy as np
import pandas as pd
import random
import sklearn
from scipy.spatial.transform import Rotation as R
from math import pi
import... | tools/lightning.py | MIT | 20,265 | d78f13f51e747863aa0b7629f78f07762d851dd5 | Python | py | |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
import torch
import torch.nn as nn
from .darknet import Darknet
from .network_blocks import BaseConv
class YOLOFPN(nn.Module):
"""
YOLOFPN module. Darknet 53 is the default backbone of this model.
... | yolox/models/yolo_fpn.py | Apache-2.0 | 2,486 | 8b3ba1473c005a57187247fd276ee5920750add8 | Python | py | |
import math
import numpy as np
import torch
import matplotlib.pyplot as plt
import torch_optimizer as optim
from hyperopt import fmin, hp, tpe
plt.style.use('seaborn-white')
def rosenbrock(tensor):
# https://en.wikipedia.org/wiki/Test_functions_for_optimization
x, y = tensor
return (1 - x) ** 2 + 100 *... | examples/viz_optimizers.py | Apache-2.0 | 5,930 | 8b3bb95ce7f7777fe588b60959ebceab3c67d727 | Python | py | |
# Copyright (c) 2021 - present / Neuralmagic, Inc. 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 b... | src/sparseml/pytorch/nn/se.py | Apache-2.0 | 2,822 | 45a5c739460b50c054c8590c6c008c612c84c6f4 | 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 logging
import numpy as np
import torch
from fairseq.data import Dictionary, FairseqDataset
from fairseq.tasks import LegacyFairseqTa... | fairseq/benchmark/dummy_mt.py | MIT | 3,677 | 28d78cffdbf8c2bcee69b454a79891cb34def200 | Python | py | |
"""Top-level model classes.
Author:
Chris Chute (chute@stanford.edu)
"""
import layers
import r_net_layers
import rnl
import torch
import torch.nn as nn
import time
class BiDAF(nn.Module):
"""Baseline BiDAF model for SQuAD.
Based on the paper:
"Bidirectional Attention Flow for Machine Comprehension... | models.py | MIT | 10,484 | 106d0a5cba9464cf716336e5cf25919ce41e5e19 | Python | py | |
import torch
import torchvision.models as models
from PIL import Image
import numpy as np
#加载测试图片调整大小
image = Image.open("test.jpg") #图片发在了build文件夹下
image = image.resize((224, 224),Image.ANTIALIAS)
#进行预处理
image = np.asarray(image)
image = image / 255
image = torch.Tensor(image).unsqueeze_(dim=0)
#变换维度
image = image.per... | cpp_test/resnet50_by_pytorch.py | MIT | 834 | 3406b374c1e68bf8a92ef0a79102be401bffd3a6 | Python | py | |
from __future__ import print_function
import torch
import numpy as np
from PIL import Image
import os
import cv2
# Converts a Tensor into a Numpy array
# |imtype|: the desired type of the converted numpy array
def tensor2im(image_tensor, imtype=np.uint8):
image_numpy = image_tensor[0].cpu().float().numpy()
#i... | util/util.py | BSD-3-Clause | 1,606 | 8b3bfeef3a9d9d556c426076538faf5b85caa409 | Python | py | |
import math
import torch
import torch.nn as nn
# Tips: 相当令人迷惑的代码, 可能是为了在 GPU 上更快吧
class MeanShift(nn.Conv2d):
def __init__(
self, rgb_range,
rgb_mean=(0.4488, 0.4371, 0.4040), rgb_std=(1.0, 1.0, 1.0), sign=-1):
super(MeanShift, self).__init__(3, 3, kernel_size=1)
std = tor... | code/model/super_resolution_model/common.py | MIT | 2,624 | 8b3c05465d33361ad0c634231cfb12de44eafc08 | Python | py | |
import os
import time
from collections import namedtuple
import torch
try:
from apex import amp
from apex.amp import _amp_state
except ImportError:
pass
#raise ImportError("Please install apex from https://www.github.com/nvidia/apex if you want to use fp16.")
# Parameter to pass to batch_end_callback
... | common/trainer.py | MIT | 7,670 | e632adbcd48867bbbd6ea09c7babddf2c5edc17f | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from typing import List, Tuple, Union, Optional
import os
from overrides import overrides, EnforceOverrides
from torch.utils.data.dataset import Dataset
import torchvision
from torchvision.transforms import transforms
from archai.datasets.data... | archai/datasets/providers/sport8_provider.py | MIT | 2,270 | 8b3c2ad341b7fb999101d14d2755a07ff2358123 | 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.
from collections import OrderedDict
import copy
from itertools import chain
import logging
from math import inf
from typi... | fairscale/optim/oss.py | MIT,Apache-2.0,BSD-3-Clause | 26,659 | 8b3c3285be60f1503aaac062d7cba70161e829cb | Python | py | |
# Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch.nn as nn
import torch.nn.functional as F
from pysot.core.config import cfg
from pysot.models.loss import se... | pysot/models/model_builder.py | Apache-2.0 | 3,686 | 7c32fffb0061984db7316d42ec9e8a2a221c9255 | Python | py | |
# source: https://github.com/edenton/svg/blob/master/data/moving_mnist.py
import numpy as np
from numpy.random import randint
from torchvision import datasets, transforms
class MovingMNIST(object):
"""Data Handler that creates Bouncing MNIST dataset on the fly."""
def __init__(self, train, data_root, se... | vq-video-diffusion/data/moving_mnist.py | MIT | 3,395 | 654a940d1ec93069902a2d7c76d7e5a625130883 | Python | py | |
import torchvision
from torch.utils.data import random_split, DataLoader
from pytorch_lightning import LightningDataModule
import typing as tp
from torchvision import transforms as T
def get_preprocessing_transforms(transforms):
transforms_list = []
for transform_name, transform_args in transforms.items():
... | homework/3-NF_VAE/datamodule.py | MIT | 2,504 | f9acd51006bffa6a18827d204ae0ecfc42d744db | Python | py | |
import torch
import torch.nn as nn
from .encoders import LBSNet, LEAPOccupancyDecoder, BaseModule
class INVLBS(LBSNet):
def __init__(self, num_joints, hidden_size, pn_dim, fwd_trans_cond_dim):
self.fwd_trans_cond_dim = fwd_trans_cond_dim
super().__init__(num_joints, hidden_size, pn_dim)
... | leap/modules/modules.py | BSD-3-Clause | 6,032 | 8b3c611240ff4b09ba2322e25e9e424c32c9a560 | Python | py | |
import io
import pathlib
import time
import warnings
from typing import Any, Dict, List, Optional, Tuple, Type, Union
import gym
import numpy as np
import torch as th
from stable_baselines3.common.base_class import BaseAlgorithm
from stable_baselines3.common.buffers import DictReplayBuffer, ReplayBuffer
from stable_b... | stable_baselines3/common/off_policy_algorithm.py | MIT | 26,839 | 8b3c66786d5a05d3995544819e3b2efcbdc4c1ea | Python | py | |
import math
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from torch.nn import functional as F
from torch.nn import init
class LinearWithPGN(torch.nn.Module):
def __init__(self, in_params, in_features, out_features, bias=True):
super(LinearWithPGN, self).__init__()
... | udapter/udapter_models/linear.py | MIT | 3,064 | 426b113e5bb10ad4c679ed35144f4f30253139c4 | Python | py | |
import torch
import torch.nn as nn
from transformer.layers import MultiHeadAttention, PositionWiseFeedForward, get_mask
# torch.manual_seed(1)
class Decoder(nn.Module):
def __init__(self, nb_layers=6, nb_heads=8, d_model=512, nb_neurons = 2048, dropout=0.1):
super(Decoder, self).__init__()
self.nb... | transformer/decoder.py | MIT | 1,449 | ff63a7aae6314ad80bf3a7ea1b4facc4a6b52417 | Python | py | |
import model.regnet, model.loss, model.util, utils.structure
import torch, os
import SimpleITK as sitk
import matplotlib.pyplot as plt; plot_dpi = 300
import numpy as np
import logging, tqdm
logging.basicConfig(level=logging.INFO, format = '%(levelname)s: %(message)s')
from scipy import interpolate
device = torch.devi... | registration_dirlab.py | BSD-3-Clause | 9,084 | cc07f605ea06a93b3d98a3e0bd44a46cf40656f1 | Python | py | |
import logging
logging.basicConfig(level=logging.INFO)
import random
import numpy as np
import torch
from setting import config as cfg
from data.dataset import TrafficDataset
from model.nas import AutoSTG
from run_manager import RunManager
def system_init():
""" Initialize random seed. """
random.seed(cfg.s... | src/train.py | MIT | 3,159 | 03d6f20aff2c7de5d08ed308d85ca1dac34cefdb | Python | py | |
import gc
import os
import math
import random
import warnings
import albumentations as A
import cv2
import numpy as np
import pandas as pd
import timm
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as torchdata
from pathlib import Path
from typin... | exp/exp011_use_kaggledr_pretrained.py | MIT | 39,332 | 8b3c9f626a92a1c3de4290a30309890861579b1b | Python | py | |
#!/usr/bin/env python
# coding=utf-8
'''
Author: JiangJi
Email: johnjim0816@gmail.com
Date: 2021-04-29 12:59:22
LastEditor: JiangJi
LastEditTime: 2021-12-22 16:27:13
Discription:
Environment:
'''
import sys,os
curr_path = os.path.dirname(os.path.abspath(__file__)) # 当前文件所在绝对路径
parent_path = os.path.dirname(curr_path)... | SoftActorCritic/task0.py | MIT | 4,678 | e910749a03bdad837e985c0c2104745422781c31 | Python | py | |
import torch
import torchvision.transforms as transforms
import numpy as np
import cv2
import logging
from .reid_feature_extractor import ReidExtractor
from .osnet_ain import osnet_ain_x1_0
class AlignedExtractor(ReidExtractor):
def __init__(self, model_path, use_cuda=True):
super().__init__(model_p... | deep_sort/deep/aligned_feature_extractor.py | MIT | 1,248 | 703110c03533181ddf4fb93a26187a40f92564b7 | 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... | code/examples/classifier_compression/run_waveq_cifar10.py | CNRI-Python | 50,111 | 247cd8e1094e0498ffb37d7eaeaac6d7a43596f9 | Python | py | |
import functools
from pathlib import Path
import torch
import cargan
###############################################################################
# Directories
###############################################################################
# Location of preprocessed features
CACHE_DIR = Path(__file__).parent.pa... | config/cargan.py | MIT | 5,934 | b239b61ab63f44f5e446628ea1c7da0d517bf220 | Python | py | |
# ***************************************************************
# Copyright (c) 2021 Jittor. All Rights Reserved.
# Maintainers:
# Dun Liang <randonlang@gmail.com>.
# Meng-Hao Guo <guomenghao1997@gmail.com>
#
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of ... | python/jittor/__init__.py | Apache-2.0 | 39,679 | 8b3cf880bb90ceec17a46ac824b3766acde730d2 | Python | py | |
# coding=utf-8
# Copyright 2022 Facebook AI and 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/LICENSE-... | src/transformers/models/vit_mae/modeling_vit_mae.py | Apache-2.0 | 39,556 | 8b3d0f90dc5f7d6cf588949477eefc0277cf00bf | Python | py | |
# Based on https://gist.github.com/colllin/0b146b154c4351f9a40f741a28bff1e3
import torch
import math
class GroupedAdam(torch.optim.Optimizer):
"""
Arguments:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float, optional): learning rate... | grouped_adam.py | MIT | 2,861 | 45fa5563f81a033055bc32a76aa88ce0b5a525ac | Python | py | |
import torch
from torch import nn
class DeformConv2d(nn.Module):
def __init__(self, inc, outc, kernel_size=3, padding=1, stride=1, bias=None, modulation=False):
"""
Args:
modulation (bool, optional): If True, Modulated Defomable Convolution (Deformable ConvNets v2).
"""
... | deformconv.py | MIT | 5,508 | 8b3d2f72f3cedeaf4c7265f6417299cec32fd985 | Python | py | |
import itertools
import json
from dataclasses import dataclass
import numpy as np
import pandas as pd
import seqeval.metrics as seqeval_metrics
import torch
from sklearn.metrics import f1_score, matthews_corrcoef
from scipy.stats import pearsonr, spearmanr
from typing import Dict, List
import jiant.shared.model_resol... | jiant/tasks/evaluate/core.py | MIT | 41,244 | 8b3d3638ac7810a820e0414bddd1b8f36f1ebc7c | Python | py | |
import functools
import torch
import torch.nn as nn
from torch.nn import init
from torch.optim import lr_scheduler
import torch.nn.functional as F
from MeshCNN.models.layers.mesh_conv import MeshConv
from MeshCNN.models.layers.mesh_pool import MeshPool
from MeshCNN.models.layers.mesh_unpool import MeshUnpool
######... | models/networks.py | MIT | 14,819 | 8b3d3dce10a2a937a52845c121d2aa45e4810053 | Python | py | |
import numpy as np
import math
import sys
import os
import random
from glob import glob
from skimage import io
from PIL import Image
import time
#from scipy.spatial.distance import directed_hausdorff
from scipy.spatial.distance import directed_hausdorff
from numpy.core.umath_tests import inner1d
from skimage.io import ... | segmentation/models/UNet3D/tester.py | MIT | 9,837 | 420dc644e9e56484f9df59da3819d4f23fa67059 | Python | py | |
# -*- encoding: utf-8 -*-
# @File : binary_dataset.py
# @Time : 2021/07/10 23:39:23
# @Author : Ming Ding
# @Contact : dm18@mail.tsinghua.edu.cn
# here put the import lib
import os
import sys
import math
import random
import torch
from torch.utils.data.dataset import Dataset
import numpy as np
from cog... | cogdata/datasets/binary_dataset.py | MIT | 2,212 | fddd4ffc1fd15913454f031b2ce858179c80d69a | Python | py | |
# -*- coding: utf-8 -*-
# @Time : 2021/3/3 2:32 PM
# @Author : Kevin
from torch import nn
import math
import torch
class LayerNorm(nn.Module):
'''
层规范化:接收[batch size,seq len,embedding dim]
防止多层计算后的数值过大或过小
'''
def __init__(self,embedding_dim,eps=1e-6):
# eps小数,分母用,防止除0
super(L... | encoder/LayerNorm.py | Apache-2.0 | 891 | cc0b3691d4a1023a1e1147420fb23d594fcbe43e | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
from copy import deepcopy
import argparse
from typing import List, Tuple
import multiprocessing
import higher
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn, optim, Tensor
from kbc.util import is_torch_tpu_av... | kbc-cli-realmeta_higher_gradaccum.py | MIT | 30,416 | 8b3dbb28fa0bf57741bbfe38337efe3449eff8bb | Python | py | |
from typing import Union, Tuple, Dict
import gym
import copy
import torch
import torch.nn.functional as F
from ....memories.torch import Memory
from ....models.torch import Model
from .. import Agent
DDPG_DEFAULT_CONFIG = {
"gradient_steps": 1, # gradient steps
"batch_size": 64, #... | skrl/agents/torch/ddpg/ddpg.py | MIT | 14,813 | b2530a51a1ca5cc9e51a674c2149a869236fa920 | Python | py | |
__doc__ = """Encode a depths matrix and a tnf matrix to latent representation.
Creates a variational autoencoder in PyTorch and tries to represent the depths
and tnf in the latent space under gaussian noise.
Usage:
>>> vae = VAE(nsamples=6)
>>> dataloader, mask = make_dataloader(depths, tnf)
>>> vae.trainmodel(datalo... | vamb/encode.py | MIT | 19,117 | b248ce9c77029f8aa85d3fe83fbadb996063da4b | Python | py | |
"""Preset Transforms for Demos"""
from PIL import Image
import numpy as np
import torch
import torchvision.transforms as transform
__all__ = ['load_image']
input_transform = transform.Compose([
transform.ToTensor(),
transform.Normalize([.485, .456, .406], [.229, .224, .225])])
def load_image(filename, size=N... | gluoncvth/utils/preset.py | MIT | 850 | 8b3dd871b07d1279dc63c882166dfb0260b5185d | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
class DynamicLSTM(nn.Module):
'''
LSTM which can hold variable length sequence, use like TensorFlow's RNN(input, lenght...).
'''
def __init__(self, input_size, hidden_size, num_layers=1, bias=True, batch_first=True, dropout=0,
... | models_utils/rnn_helper.py | MIT | 3,803 | 347644e008f55b10c02ed1dbb4e061fad1c3bb9a | Python | py | |
import pytorch_lightning as pl
import torch
import torch.nn.functional as F
from torch import nn
class LitAutoEncoder(pl.LightningModule):
def __init__(self):
super().__init__()
self.encoder = nn.Sequential(
nn.Linear(64*64*4, 64),
nn.ReLU(),
nn.Linear(64, 3)
... | model_layer/DummyAutoEncoder.py | MIT | 1,170 | 8b3de863211a5e3441157c4611d6246651e82e8d | Python | py | |
""" Vision Transformer
A PyTorch implementation of Vision Transformers:
'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale'
- https://arxiv.org/abs/2010.11929
The official jax code is available at
https://github.com/google-research/vision_transformer
"""
from copy import deepcopy
from funct... | vistrans/models/vit.py | MIT | 12,805 | ff8a991040ac188b78563ac11d8ce85f0f931c3a | Python | py | |
## ResNet18 for CIFAR
## From: https://gitlab.com/harvard-machine-learning/double-descent/-/blob/master/models/resnet18k.py
import torch.nn as nn
import torch.nn.functional as F
class PreActBlock(nn.Module):
'''Pre-activation version of the BasicBlock.'''
expansion = 1
def __init__(self, in_planes, plane... | examples/models/resnet18k.py | MIT | 3,291 | 5f604a44c91872057fee2ed922b318bdac883c6a | Python | py | |
# camera-ready
import sys
sys.path.append("/root/3DOD_thesis/utils")
from kittiloader import LabelLoader2D3D, calibread, LabelLoader2D3D_sequence # (this needs to be imported before torch, because cv2 needs to be imported before torch for some reason)
import torch
import torch.utils.data
import os
import pickle
impo... | Frustum-PointNet/datasets.py | MIT | 90,617 | 8b3e1e1239e34523fcf43ba4ddcda3fb6d5243ca | Python | py | |
from typing import Callable
import torch
from colossalai import nn as col_nn
from colossalai.registry import MODELS
from torch import dtype, nn
from model_zoo.vit.vit import ViTBlock, ViTEmbedding
from utils import heads, objectives
import torch.nn.functional as F
from colossalai.nn.layer.colossalai_layer import LayerN... | image/vilt/models/vilt.py | Apache-2.0 | 5,629 | 8b3e2225e03899495e2684fad69fe1d060ab1a02 | Python | py | |
# coding: utf-8
import torch
def save_model(model, path='model/unet.pt'):
"""
Save the model `model` to `path`\\
Args:
path: The path of the model to be saved
model: The model to save
"""
torch.save(model.state_dict(), path)
def load_model(model, path, device):
"""
Load `... | save_load_net.py | Apache-2.0 | 663 | 52e50fc51f3368cc966a15b2e98a9db09bc641ab | Python | py | |
# coding=utf-8
"""Evaluate embeddings on downstream tasks."""
import os
import math
import torch
import pprint
import numpy as np
from tqdm import tqdm
import utils.logging as logging
from torch.utils.tensorboard import SummaryWriter
from utils.parser import parse_args, load_config, setup_train_dir
from models import... | evaluate.py | MIT | 8,894 | 7083a59f16722ceada41ae54bafcc1d628353d1a | Python | py | |
"""
Unit tests for connectors.
"""
from __future__ import unicode_literals
from collections import namedtuple
import unittest
import torch
import torch.distributions as tds
from texar.torch.core import layers
from texar.torch.modules.connectors.connectors import ConstantConnector
from texar.torch.modules.connectors.... | texar/torch/modules/connectors/connectors_test.py | Apache-2.0 | 7,641 | 5f4f64c12dd4d831e162e86fe760e1fbbc1adba5 | Python | py | |
import torch
import numpy as np
import cv2
import os
from util.config import config as cfg
from util import canvas as cav
def visualize_network_output(output, tr_mask, mode='train'):
vis_dir = os.path.join(cfg.vis_dir, cfg.exp_name + '_' + mode)
if not os.path.exists(vis_dir):
os.mkdir(vis_dir)
b... | util/visualize.py | MIT | 2,255 | 8b3e644c8ee7e86d742e618cc1b0ae2f9665b755 | Python | py | |
#!/usr/bin/env python3
import math
import torch
from torch.distributions import MultivariateNormal as TMultivariateNormal
from torch.distributions.kl import register_kl
from torch.distributions.utils import _standard_normal, lazy_property
from .. import settings
from ..lazy import DiagLazyTensor, LazyTensor, delazif... | gpytorch/distributions/multivariate_normal.py | MIT | 12,425 | 8b3e6552d80ebe6d735e398c0f98796d529d07f9 | Python | py | |
import numpy as np
import torch.nn as nn
import torch.optim as optim
import torch.utils.data
from rampwf.utils import BaseGenerativeRegressor
from mbrltools.pytorch_utils import train
torch.manual_seed(7)
n_epochs = 300
LR = 1e-3
N_LAYERS_COMMON = 2
LAYER_SIZE = 200
BATCH_SIZE = 50
VALIDATION_FRACTION = 0.1
DROP_... | benchmark/acrobot_sincos/submissions/dmdn_single_det/generative_regressor.py | BSD-3-Clause | 5,685 | 12c36b62e8c36c930f71c8101a94ecb7621595ad | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.