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 numpy as np
import random
import torch as T
from torch import nn, optim, autograd
from common_functions import bucket_and_batch, pretty_print
from models.BVAE import BVAE, ELBO, nll_fn, penalty_fn, ER_penalty_fn, mean_accuracy
import argparse
random.seed(101)
val_size = 5000
batch_size = 128
display_step = 100
... | MNIST_1/train_IRM.py | MIT | 5,924 | 29ba54e676dabb4a7f28e690aeee25ec8da1b837 | Python | py | |
import numpy as np
import torch
import glob
import torch.nn.functional as F
from envs.abb.models.utils import hard_update
from torch.distributions import Categorical
from envs.abb.models.model import GaussianPolicy1D, Option, ValueNetwork, QNetwork
if torch.cuda.is_available():
torch.cuda.empty_cache()
d... | code/pytorch/methods/HRLSAC.py | MIT | 21,328 | 24f8bba8bcd4709846c1a286eb3fbe2fb2236e53 | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.module import Module
from torch.nn.parameter import Parameter
from .. import BaseModel, register_model
class GraphConvolutionBS(Module):
"""
GCN Layer with BN, Self-loop and Res connection.
"""
def ... | cogdl/models/nn/dropedge_gcn.py | MIT | 24,304 | 29ba706b46db05cc9b5e1b001a0cf5f18bc532de | Python | py | |
from unittest import mock
import pytest
import torch
from differentiable_robot_model.robot_model import DifferentiableRobotModel
# this file contains no dummy link
urdf_clean_file = r"""
<robot name="test_robot">
<link name="link_base"/>
<joint name="joint_1" type="continuous">
<parent link="link_bas... | tests/test_urdf_robot.py | MIT | 5,482 | 29ba7b59e124cec9bb1afeb095a6eced9d639a5b | Python | py | |
from __future__ import print_function
import argparse
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.util... | main.py | BSD-3-Clause | 12,929 | 29ba83083bc5a607caeeecd435fc86b2d96efedb | Python | py | |
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-17 21:54
import logging
from typing import Dict, Any, List, Union, Iterable, Callable
import torch
from torch.utils.data import DataLoader
from elit.common.dataset import SamplerBuilder, PadSequenceDataLoader
from hanlp_common.document import Document
from elit.... | elit/components/mtl/tasks/ud.py | Apache-2.0 | 7,613 | 29ba9ad1af0d6eca2ebc209b933a86860cca4124 | Python | py | |
# coding=utf-8
# Copyright 2021 rinna 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | src/task/pretrain_roberta/train.py | Apache-2.0 | 25,620 | 29baa89c5b15745d7839198993ad13e785867780 | Python | py | |
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision.utils import save_image
from torch.utils.data import Dataset, DataLoader, TensorDataset
from torchvision import transforms, datasets
import tqdm
class Generator(nn.Module):
def __init__(self):
super().__init__()
self.... | NikuGan.py | MIT | 1,927 | 29baad2a7034988b671fd11bc886aa3060cdb704 | Python | py | |
from typing import List
import torch
from torch import nn
from catalyst.contrib.models.cv.segmentation.blocks.core import DecoderBlock
from catalyst.contrib.models.cv.segmentation.blocks.unet import (
DecoderConcatBlock,
)
from catalyst.contrib.models.cv.segmentation.decoder.core import DecoderSpec
class UNetDe... | catalyst/contrib/models/cv/segmentation/decoder/unet.py | Apache-2.0 | 2,381 | 24ce18e65de4a1a71f80accfa06c9178ab50eef2 | Python | py | |
# encoding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path as osp
import sys
import time
import numpy as np
from easydict import EasyDict as edict
import argparse
import torch.utils.model_zoo as model_zoo
C = edict()
config = C
cfg =... | model/crfasrnn/cil.crfasrnn.R50/config.py | MIT | 2,954 | 10602742161a9946203a25eb444d902cc2acf428 | Python | py | |
from __future__ import division
import torch
import torch.nn as nn
from .base import BaseDetector
from .test_mixins import RPNTestMixin, BBoxTestMixin, MaskTestMixin
from .. import builder
from ..registry import DETECTORS
from mmdet.core import (build_assigner, bbox2roi, bbox2result, build_sampler,
... | mmdet/models/detectors/cascade_rcnn.py | Apache-2.0 | 17,458 | 29bad05ae89da998170d43ea554f850c7bf41ef0 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from __future__ import division
import torch
class ImageList(object):
"""
Structure that holds a list of images (of possibly
varying sizes) as a single tensor.
This works by padding the images to the same size,
and... | fcos_core/structures/image_list.py | BSD-2-Clause | 2,557 | 29bad2d010a35634a68259c0123d4006a9e4c46a | Python | py | |
import copy
import time
import torch
from torch.nn.utils import clip_grad_norm_
import torch.distributed as dist
from tensorboardX import SummaryWriter
from gyrospd import config
from gyrospd.utils import get_logging, write_results_to_file, compute_metrics, avg_side_metrics, \
get_run_id_with_epoch_name
class Ru... | gyrospd/runner.py | MIT | 13,099 | 29bae371b24bd59f76292aeff399b22217e50005 | Python | py | |
import torch
from torch import nn
from dataset_loader import BikeDataset
from torch.utils.data import DataLoader
from models import GRUmodel
import torch.optim as optim
import argparse
import numpy as np
import pandas as pd
import random
from metrics import Metric
from utils import save_results
def seed_e... | main.py | MIT | 6,549 | 1ee4ff97398248acf09e9fa16a1e0cb92f9d37fa | Python | py | |
from collections import OrderedDict
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms, models
from torch.utils.data import DataLoader
import shutil, argparse, json
from torch.autograd import Variable
from PIL import Image
... | predict.py | MIT | 4,020 | 34033e91e23740056fb77c488ad5e3e046837e69 | Python | py | |
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as T
class DQN(nn.Module):
def __init__(self, input_size, outputs):
super(DQN, self).__init__()
#Number of layers
self.nn = nn.Sequential(
nn.Linear(input_size, 12... | dqn_model/dqn.py | MIT | 821 | 4b0d00f4bb0ad9c99f3a78ca7904e7e185036df9 | Python | py | |
################################################################################
# Copyright (c) 2021 ContinualAI. #
# Copyrights licensed under the MIT License. #
# See the accompanying LICENSE file for terms. ... | avalanche/benchmarks/classic/clear.py | MIT | 9,164 | 29bb132a4d8bd2ed3a8c0ebcb4241b9db76520b0 | Python | py | |
#!/usr/bin/env python
# coding=utf-8
# Copyright The HuggingFace Team 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.ap... | examples/multiple-choice/run_swag.py | Apache-2.0 | 18,326 | 10af91ee6a67a3351c699245fd040559b2d82286 | Python | py | |
import sys
from unittest.mock import MagicMock, Mock, patch
import pytest
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
from mmaction.apis.test import (collect_results_cpu, multi_gpu_test,
single_gpu_test)
class OldStyleModel(nn.Module):
def... | tests/test_runtime/test_apis_test.py | Apache-2.0 | 2,784 | 29bb376b282fc858c5b2a044834955bcc6126e00 | Python | py | |
import torch
import torch.nn as nn
def conv3x3(in_planes, out_planes, stride=1, has_bias=False):
"3x3 convolution with padding"
return nn.Conv2d(
in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=has_bias
)
def conv3x3_bn_relu(in_planes, out_planes, stride=1):
return nn.Se... | wireframe/models/resnet_baseline.py | MIT | 6,327 | 29bb51070d26effa86887070546c2f0aa549ebca | Python | py | |
# This file is mostly taken from BTS; author: Jin Han Lee, with only slight modifications
import os
import random
import cv2
import numpy as np
import torch
import torch.utils.data.distributed
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
def _is_pil_image... | networks/adabins/dataloader.py | MIT | 9,831 | d7fd1a3aa35f874f6661a1c0e6e8a43ad2f62ab4 | Python | py | |
import torch
# Code was adapted and mofified from https://github.com/wolny/pytorch-3dunet/blob/master/pytorch3dunet/unet3d/losses.py
def expand_as_one_hot(input, C, ignore_index=None):
"""
Converts NxDxHxW label image to NxCxDxHxW, where each label gets converted to its corresponding one-hot vector
:param... | lib/losses3D/basic.py | MIT | 3,078 | 29bb7db09ee76012b4856c082aa9729e0cc0a067 | Python | py | |
#!/usr/bin/env python3
"""An example to train TD3 algorithm on InvertedDoublePendulum PyTorch."""
import torch
from torch.nn import functional as F
# from garage.np.exploration_policies import AddGaussianNoise
from garage import wrap_experiment
from garage.envs import GymEnv, normalize
from garage.experiment.determini... | src/garage/examples/torch/td3_halfcheetah.py | MIT | 3,477 | 29bb8890ae9e37e75761dd14db9476274838a3af | Python | py | |
from utils.typings import AttacksType, FreeRiderAttack
from aggregators.Aggregator import allAggregators
from typing import List
import torch
from experiment.DefaultExperimentConfiguration import DefaultExperimentConfiguration
# Naked imports for allAggregators function
from aggregators.FedAvg import FAAggregat... | experiment/CustomConfig.py | MIT | 9,966 | 5e1856e69ffd43e920494128da8b7a737cbd92a5 | Python | py | |
# -*- coding: utf-8 -*- #
"""*********************************************************************************************"""
# FileName [ upstream/tera/hubconf.py ]
# Synopsis [ the tera torch hubconf ]
# Author [ S3PRL ]
# Copyright [ Copyleft(c), Speech Lab, NTU, Taiwan ]
"""****************... | upstream/tera/hubconf.py | MIT | 5,442 | 29bbf680364a6c97609bcc6205d01f84bccda6f4 | Python | py | |
import numpy as np
from numpy import isnan
import os
import matplotlib.pyplot as plt
import torch
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def fill_missing_one_day(values):
one_day = 1
for row in range(values.shape[0]):
for col in range(values.shape[1]):
if ... | utils.py | MIT | 996 | 29bbfe57a13cf1e83b0a549967b6b2329e1512f4 | Python | py | |
import glob
import math
import os
import pickle
import sys
import types
from argparse import Namespace
from pathlib import Path
import cloudpickle
import pytest
import torch
from omegaconf import OmegaConf
import tests.base.utils as tutils
from pytorch_lightning import Callback, LightningModule, Trainer
from pytorch_... | tests/trainer/test_trainer.py | Apache-2.0 | 33,829 | 5e4cf3544e911ff4d65f4e77eec281fa4a296655 | Python | py | |
"""
author: Prabhu
"""
import numpy as np
import sys
import csv
from torch.utils.data import Dataset
import pandas as pd
class Dataset_(Dataset):
def __init__(self, file_path = None, classes_file_path = None, char_wise_max_length_text = 1014):
self.file_path = file_path
self.vocabulary = list("""a... | src/dataset.py | MIT | 2,512 | 10dc21ab101795b782778f19f3f662e0963d86f9 | Python | py | |
"""
Lightning makes multi-gpu training and 16 bit training trivial.
.. note:: None of the flags below require changing anything about your lightningModel definition.
Choosing a backend
==================
Lightning supports two backends. DataParallel and DistributedDataParallel.
Both can be used for single-node mult... | pytorch_lightning/trainer/distrib_parts.py | Apache-2.0 | 22,557 | 29bc8178b8525a3efbd794c0d47336069fc66075 | Python | py | |
# coding=utf-8
from tqdm import tqdm
import torch
from torch import nn
from torch.utils.tensorboard import SummaryWriter
from util import *
def train(config, dataloaders, model, optimizers, evaluation, val_plot=None):
# configure train
log_name = config['log_name']
tqdm_bar = '{desc} {n_fmt}/{total_fmt}... | base_train.py | Apache-2.0 | 5,411 | 29bc947105490f00292b10a05631fd0206815540 | Python | py | |
"""
Implementation of Total Variation Loss
(https://en.wikipedia.org/wiki/Total_variation_denoising) copied and slightly
modified from the original Apache License 2.0 traiNNer
Authors https://github.com/victorca25/traiNNer/tree/master
# Copyright 2021 traiNNer Authors
#
# Licensed under the Apache License, Version 2.... | nowcasting_utils/models/losses/TotalVariationLoss.py | MIT | 7,272 | 29bcb2edae0753a13264bbcb93ebe34870aacd2a | Python | py | |
from abc import ABC, abstractmethod
import torch
import torch.nn.functional as F
from torch import nn, topk
from torch.nn import NLLLoss2d, MSELoss, BCEWithLogitsLoss
class LossCalculator(ABC):
@abstractmethod
def calculate_loss(self, outputs, sample):
pass
def r2_loss(output, target):
eps = 1... | training/losses.py | Apache-2.0 | 15,050 | 344f9f80795ac024809582a37f8b456bad4e4f86 | Python | py | |
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this so... | torch_utils/ops/upfirdn2d.py | MIT | 16,394 | 29bcd40631d52ee695025ca1e1154d59144c0311 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from maskrcnn_benchmark.modeling.box_coder import BoxCoder
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.boxlist_ops import cat_boxlist
from maskrcnn_benchmark.structures.boxlist_ops... | maskrcnn_benchmark/modeling/rpn/inference.py | MIT | 7,503 | 29bcde7e40b7f33cd57e7011b7f396d818071063 | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import mmcv
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmcv.runner import BaseModule
from .make_divisible import make_divisible
# class SELayer(nn.Module):
class SELayer(BaseModule):
"""Squeeze-and-Excitation Module.
Args:
channels (int... | mmcls/models/utils/se_layer.py | Apache-2.0 | 2,274 | 703c18ca0bdd2d682cd197a7d1e31bce150de59c | Python | py | |
# Adapted from SQLova script for interaction.
# @author: Ziyu Yao
# Oct 7th, 2020
#
import os, sys, argparse, re, json, pickle, math
from copy import deepcopy
from matplotlib.pylab import *
import torch.nn as nn
import torch
import torch.nn.functional as F
import random as python_random
# import torchvision.datasets as... | interaction_sqlova.py | MIT | 130,317 | 29bcfcb73f2ec441c96911dafb8c20ab8c7a89e4 | Python | py | |
import progressbar as pb
import torch
import time
from sys_monitor import memory_usage_in_megabytes
from ppo_agent import PPOAgent
from model import Actor, Critic
import numpy as np
from collections import deque
def train(env, agent, episodes, max_t, print_every, logger, checkpoints_dir):
widget = ['training loop... | p2_continuous-control_ppo/train.py | MIT | 3,349 | 29bd07da811f477f4d16878c597f758e85d0fd2f | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.output_layer import *
from models.utils import *
from models import base
class Model(base.SRNNBase):
def __init__(self, d_data, d_emb, d_mlp, d_rnn, d_lat, n_layer, dropout=0.,
**kwargs):
super(Model, self).__init__(d_... | midi/models/srnn_hier_inp.py | MIT | 2,762 | 5fcffc0bf8ba55c1f90a3391df28257b8d004549 | Python | py | |
import io
import os
import re
import torch
from setuptools import setup, find_packages
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
def get_cuda_compile_archs(nvcc_flags=None):
"""Get the target CUDA architectures from CUDA_ARCH_LIST env variable"""
if nvcc_flags is None:
nvcc_... | pytorch_binding/setup.py | MIT | 3,458 | 29bd2e67e8f325d01b2fcd99f96e6cf70ab8c9fa | Python | py | |
import logging
import os
from os import PathLike
from typing import Dict, List, Set, Type, Optional, Union
import numpy
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.common.params import Params
from allennlp.common.registrable import Registrable
from allennlp.data import Instance, V... | simplejson_test/testdata/allennlp/models/tmp.py | Apache-2.0 | 5,909 | 29bd35544892075f2132590af2da7d6e5d451c9d | Python | py | |
from __future__ import division
from __future__ import print_function
import time
import argparse
import numpy as np
import torch
import torch.nn.functional as F
import torch.optim as optim
from tensorboardX import SummaryWriter
from earlystopping import EarlyStopping
from sample import Sampler
from me... | src/train_new.py | MIT | 12,622 | fd881fda86582169d7365e1513f0cd66a317951b | Python | py | |
import math
import time
import torch
import torch.cuda.nvtx as nvtx
import numpy as np
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
from tqdm import tqdm
from utils.initializers import args_initialize, env_initialize, log_initialize, model_initialize
from a2c.helper import call... | examples/ppo/train.py | BSD-3-Clause | 13,286 | 03996e2ca927a761b42b02e3284d99342206463c | 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... | flash/pointcloud/segmentation/open3d_ml/sequences_dataset.py | Apache-2.0 | 6,345 | 29bd534e15f3d14010afc7ed9afdd247f01cdb48 | Python | py | |
# Dataloader of Gidaris & Komodakis, CVPR 2018
# Adapted from:
# https://github.com/gidariss/FewShotWithoutForgetting/blob/master/dataloader.py
from __future__ import print_function
import os
import os.path
import numpy as np
import random
import pickle
import json
import math
import torch
import torch.utils.data as ... | data/tiered_imagenet.py | Apache-2.0 | 18,511 | 29bd581615050c3d312b847f6c489a0e0327a084 | Python | py | |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision.models.vgg as VGG
import torchvision.models.resnet as Resnet
class MNIST_VGG(nn.Module):
"""
VGG-style MNIST.
"""
def make_layers(self, cfg, batch_norm=False):
layers = []
... | models/classifiers.py | MIT | 16,053 | 29bd95697aa081af79bb9f155fdcda06ca2b3c80 | Python | py | |
import torch
import torch.nn as nn
import numpy as np
from models.real_nvp.real_nvp import RealNVP
from models.resnet.resnet import ResNet
class MLP_ACVAE(nn.Module):
"""RealNVP Model
Based on the paper:
"Density estimation using Real NVP"
by Laurent Dinh, Jascha Sohl-Dickstein, and Samy Bengio
... | models/mlp_acvae/mlp_acvae.py | MIT | 2,769 | 45f331920c0ba65492fc28ef4c9346ab640e20f9 | Python | py | |
from __future__ import absolute_import, division, print_function
import logging
from collections import namedtuple, OrderedDict
import numpy as np
import pytest
import scipy.special as sc
import torch
import pyro
import pyro.distributions as dist
from pyro import optim
from pyro.contrib.glmm import (
zero_mean_u... | tests/contrib/oed/test_eig.py | MIT | 7,174 | 52da1e21af3fce5961c484dc6b0a224686f6039e | Python | py | |
import torch as th
th.backends.cudnn.deterministic = True # noqa
th.backends.cudnn.benchmark = False # noqa
from collections import defaultdict # noqa
from tqdm import tqdm
import torch.utils.data as td
import os
import cv2
from matplotlib import pyplot as plt # noqa
import pandas as pd
from zipfile import ZipFile
... | See/Model_001_f00/submit_segmentation.py | MIT | 4,983 | 29bdae38aa9e1beeb2dba6edfe4227ac3315e8b8 | Python | py | |
"""
Unit tests for data related operations.
"""
import copy
import os
import shutil
import tempfile
import unittest
import numpy as np
import torch
from texar.torch.data.data.record_data import RecordData
from texar.torch.data.data.data_iterators import DataIterator
from texar.torch.data.data_utils import maybe_down... | texar/torch/data/data/record_data_test.py | Apache-2.0 | 7,029 | 29bde4aad9956560ea4ac4f7f3b4fba6f84b1571 | Python | py | |
class DatasetWrapper:
def __init__(self, image_folder):
from torchvision.transforms import Resize, CenterCrop, ToTensor, Normalize
self.image_folder = image_folder
self.image_size = 64
self.transforms = [
Resize(self.image_size),
CenterCrop(self.image_size),... | src/dataset/datasetWrapper.py | MIT | 1,005 | 4575a6bc4c52b59ea7adce8848d085bae8ecd397 | Python | py | |
import os.path
import numpy as np
import torchvision
import torchvision.transforms as transforms
import torch
import h5py
import time
from data.base_dataset import *
from PIL import Image
import math, random
def make_dataset_fromlst(listfilename):
"""
NYUlist format:
imagepath seglabelpath depthpath HHApa... | data/VOC_dataset.py | MIT | 3,001 | 45a896d1de14842bd6023ae2146c0a41def34035 | Python | py | |
import argparse
import datetime
import glob
import os
import re
import time
from pathlib import Path
import numpy as np
import torch
from tensorboardX import SummaryWriter
from eval_utils import eval_utils
from pcdet.config import cfg, cfg_from_list, cfg_from_yaml_file, log_config_to_file
from pcdet.datasets import b... | tools/test.py | Apache-2.0 | 8,712 | 80210751c444e6c61685a7552d6606d00b3a127d | Python | py | |
"""Training using 8-mile API
"""
import os
from argparse import ArgumentParser
from audio8.data import AudioTextLetterDataset
from audio8.text import TextVectorizer, read_vocab_list
from audio8.wav2vec2 import create_acoustic_model, load_fairseq_bin
from torch.utils.data import DataLoader
from eight_mile.utils import... | audio8/test.py | Apache-2.0 | 6,879 | dfa5e3ad56f8fccc4bc1309dedd70f09c8bbba5b | 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.... | cnn/model_search.py | Apache-2.0 | 7,330 | 29be71b7bd6efc1319ad3a93f754d0e77f841cb3 | Python | py | |
import torch
import torch.nn as nn
from dassl.data import DataManager
from dassl.optim import build_optimizer, build_lr_scheduler
from dassl.utils import count_num_param
from dassl.engine import TRAINER_REGISTRY, TrainerXU
from dassl.metrics import compute_accuracy
from dassl.engine.trainer import SimpleNet
from dassl... | dassl/engine/da/dael.py | MIT | 7,522 | 458df7da350d8d4a4d876362bee88632ecab7d52 | Python | py | |
from src.dennet import DENNet
import torch
import torch.nn as nn
import torch.utils.data as data
import pytorch_lightning as pl
import numpy as np
import matplotlib.pyplot as plt
class HNN(nn.Module):
def __init__(self, hamiltonian: nn.Module, dim=1):
super().__init__()
self.H = hamiltonian
... | mass_spring.py | Apache-2.0 | 3,092 | b240163b75ba9e4cbf7146f785f81081107026a1 | Python | py | |
import torch
import torch.nn.functional as F
import torch.nn as nn
class multi_head_attention_2d(torch.nn.Module):
def __init__(self, in_channel, key_filters, value_filters,
output_filters, num_heads, dropout_prob=0.5, layer_type='SAME'):
super().__init__()
"""Multihead scaled-dot-product at... | modeling/model_utils/non_local_parts.py | Apache-2.0 | 4,974 | 7c1aa50a6f137de7f86c9cddce8a90d9fb5f4ee0 | Python | py | |
from collections import OrderedDict
import numpy as np
import torch
import torch.optim as optim
from torch import nn as nn
from typing import Iterable
from torch.optim.optimizer import Optimizer
import rlkit.torch.pytorch_util as ptu
from rlkit.core.eval_util import create_stats_ordered_dict
from rlkit.torch.torch_r... | rlkit/torch/td3/td3.py | MIT | 6,577 | 5f2ffc2d917e13fa0717a2949de5768965848caf | Python | py | |
import torch
import torch.nn as nn
_input_size = 28*28
_hidden_size = 512
_output_size = 10
class NeuralNetwork(nn.Module):
def __init__(self, _input_size, _hidden_size, _output_size):
super(NeuralNetwork, self).__init__()
self.flatten = nn.Flatten()
self.linear_relu_... | pytorch/neural-networks/python/model.py | Apache-2.0 | 720 | 5fd2ca0fb43e7270765cdc51fba3f9859ab3888a | Python | py | |
from torch.utils.tensorboard import SummaryWriter
import torch
import pytz
import json
import os
class Logger(object):
def __init__(self):
self.dirs = self.make_dirs()
self.save_config()
self.writer = SummaryWriter(self.dirs['worker'])
def log_scalar(self, value, tag, i):
self.writer.add_scala... | src/muzero/logger.py | MIT | 1,382 | d74703463ad0cc4855f67c2727d69d01259cc832 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import cv2
import torch
import numpy as np
from torchvision import transforms as T
from maskrcnn_benchmark.modeling.detector import build_detection_model
from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer
from maskrcnn_benchmark... | demo/predictor.py | MIT | 10,202 | 42953b5a6a249daf0fa12443ba357d983e014dbc | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from torch.distributions import Normal
import scipy.stats
import sys
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Implementation of Twin Delayed Deep Deterministic Policy Gradients (TD3)
# Pap... | Policies/Policy.py | MIT | 9,183 | 29bf33647f09449a24b0c09e19c47304d08f21f6 | Python | py | |
import attr
import torch
import torch.nn as nn
from model.attention import Attention, SelfAttention
from model.classification import Classifier
from model.fusion import calculate_similarity_matrix
from model.multi_layer_net import MultiLayerNet
from model.question_embedding import QuestionEmbedding, WordEmbedding
from... | model/vqa_model.py | MIT | 6,649 | 29bf4ea2faec789fe233d136adb2f8fcb41c6e33 | Python | py | |
# MIT License
#
# Copyright (c) 2021 Soohwan Kim and Sangchun Ha and Soyoung Cho
#
# 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... | openspeech/models/transformer_transducer/model.py | Apache-2.0,MIT | 5,387 | 6b3375257bf046827e66a81c0e01e9d2a3b504e5 | Python | py | |
# flake8: noqa
# yapf: disable
# __import_lightning_begin__
import math
import torch
import pytorch_lightning as pl
from filelock import FileLock
from torch.utils.data import DataLoader, random_split
from torch.nn import functional as F
from torchvision.datasets import MNIST
from torchvision import transforms
import ... | python/ray/tune/examples/mnist_pytorch_lightning.py | Apache-2.0 | 9,321 | 10d482286aab8dc1e756cb43927bbeb5b823b1bd | Python | py | |
import argparse
import json
import os
import pickle
import sys
import sagemaker_containers
import pandas as pd
import torch
import torch.optim as optim
import torch.utils.data
from model import LSTMClassifier
def model_fn(model_dir):
"""Load the PyTorch model from the `model_dir` directory."""
print("Loading ... | project-sentiment-deployment/train.py | MIT | 6,254 | cc1985ed866c5359b5f612f2d081eb1d88115807 | Python | py | |
import csv
import itertools
import cv2
import numpy
import torch
import enum
import logging
import random
from skimage import io
from PIL import Image
class Placements(enum.Enum):
CENTER = 1
RIGHT = 2
UP = 3
def describe(self):
return self.name.lower(), self.value
... | ThreeD60/common.py | MIT | 5,432 | 29bfc1168753a559b46c6fe2f7106ebe3abc999e | Python | py | |
import argparse
import os
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.cuda import amp
from torch.utils.tensorboard import SummaryWriter
from pathlib import Path
from copy import deepcopy
from tqdm import tqdm
from classification.models import Model
from classification.lo... | train.py | MIT | 21,795 | 29bfed1180ef9bd79066cbf35efd0a8d5e83a66a | Python | py | |
import warnings
from typing import Optional
import numpy as np
import scipy.stats
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
# isort: off; pylint: disable=E0611,E0401
from compressai._CXX import pmf_to_quantized_cdf as _pmf_to_quantized_cdf
from compressai.ops import... | compressai/entropy_models/entropy_models.py | Apache-2.0 | 21,247 | 4b0efb7fb74f06cc2016714efe52c30cf5f796ef | Python | py | |
import time
import logging
import os
import random
from tqdm import tqdm
import numpy as np
import torch
from apex import amp
from apex.optimizers import FusedAdam
from apex.parallel import DistributedDataParallel as DDP
from data.RACEDataModule import RACEDataModule
from modeling import BertForMultipleChoice
from fil... | run.py | MIT | 7,206 | 52d70162d4af9bdbb04193b6661da5d9d0696530 | Python | py | |
#basics
import shutil
from typing import List, Tuple, Dict, Callable, Union
import json
import numpy as np
import os
import pwd
import pandas as pd
from glob import glob
#pytorch
import torch
# segnlp
from segnlp import get_logger
from .loop_train import TrainLoop
from .loop_test import TestLoop
from .loop_hp_tune ... | segnlp/pipeline/pipeline.py | Apache-2.0 | 7,703 | 29c0201ad537d0d5f1aa6d207ebbe26877ae13cb | Python | py | |
from modules.agents import REGISTRY as agent_REGISTRY
from components.action_selectors import REGISTRY as action_REGISTRY
from .basic_controller import BasicMAC
import torch as th
from utils.rl_utils import RunningMeanStd
import numpy as np
# This multi-agent controller shares parameters between agents
class NMAC(Basi... | src/controllers/n_controller.py | Apache-2.0 | 1,165 | 70316dba8c67a92e6b914ea5587a8819bfe39585 | Python | py | |
import random
import librosa as lr
import torch
from torch import Tensor
from hw_asr.augmentations.base import AugmentationBase
class PitchShift(AugmentationBase):
def __init__(self, **kwargs):
self.steps = kwargs.get("steps")
self.sampling_rate = kwargs.get("sampling_rate", 16000)
def __ca... | hw_asr/augmentations/wave_augmentations/pitch_shift.py | MIT | 562 | e919aeab86967733c4f35776c7fe810753db3cab | Python | py | |
#----------------------------------------------------#
# 获取测试集的ground-truth
# 具体视频教程可查看
# https://www.bilibili.com/video/BV1zE411u7Vw
#----------------------------------------------------#
import colorsys
import os
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from PIL import Im... | get_dr_txt.py | MIT | 5,900 | 24ebf52280b86da9128687b25a32e080f98b37cb | Python | py | |
import os
from collections import defaultdict,OrderedDict
import torch.nn as nn
from utils.parse_config import *
from utils.utils import *
import time
import math
try:
from utils.syncbn import SyncBN
batch_norm=SyncBN #nn.BatchNorm2d
except ImportError:
batch_norm=nn.BatchNorm2d
def crea... | models_diou.py | MIT | 18,471 | 5e04ce8484da3b92517bdf548f7a9c8582e5ded6 | Python | py | |
import argparse
import os
import logging
import random
import pickle
import numpy as np
from tqdm import tqdm, trange
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
from torch.utils.data.distributed import DistributedSampler
from tensorboardX import SummaryWriter
from transform... | main.py | Apache-2.0 | 35,591 | d7c39f5ed38f33c6dd42a50c355f43f72edaea6e | Python | py | |
"""Author: Zahra Sheikhbahaee- March 2020 """
import torch
from torch import nn, optim
import torch.nn.functional as F
import os
from torch.utils import data
from torchvision import datasets, transforms
from PIL import Image
class ResizeConv2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size,... | VAE_ResNET.py | MIT | 9,237 | 29c0981e294d546044ec0856a6f5d0ff0ac0af6e | Python | py | |
import torch
from torch import nn
from torch.nn import init
class VentilatorNet(nn.Module):
def __init__(self,
input_dim: int = 4,
lstm_dim: int = 256,
lstm_layers: int = 4,
logit_dim: int = 256,
num_layers: int = 256,
... | src/models/ventilator_model__0_0.py | MIT | 11,720 | 28c820515deca932db690bbd2346f7208cf23cfd | Python | py | |
import argparse
import os
from util import util
import torch
class BaseOptions():
def __init__(self):
self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
self.initialized = False
def initialize(self):
self.parser.add_argument('--dataroot', req... | options/base_options.py | MIT | 5,717 | 6b346064e025b588b94984fc1e047951a716f29f | Python | py | |
from .clip_model.clip import load
from timm.models.vision_transformer import resize_pos_embed
from .backbone import Backbone
from .build import BACKBONE_REGISTRY
import logging
import numpy as np
import fvcore.nn.weight_init as weight_init
import torch
import torch.nn.functional as F
from torch import nn
from detect... | CLIP-ViL-Direct/vqa/detectron2/detectron2/modeling/my_clip.py | MIT | 5,047 | 421d21df0717380d9e2e779562765a942ed6767a | Python | py | |
import torch
import torch.nn as nn
import torch.autograd as autograd
import numpy as np
from common.replay_buffers import PrioritizedBuffer
from perDQN.models import ConvDQN, DQN
class PERAgent:
def __init__(self, env, use_conv=True, learning_rate=3e-4, gamma=0.99, buffer_size=10000):
self.env = env
... | Deep-Q-Networks/perDQN/per_dqn.py | MIT | 2,627 | cc27ea44e625bde58369bf0d7b8c8b878c6be17f | Python | py | |
import os
import sys
import argparse
import time
parser = argparse.ArgumentParser()
parser.add_argument('-gpu', default='0', type=str)
args = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"]=args.gpu
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim ... | extract_fineFEAT.py | MIT | 6,659 | f9df4d78877efdd16daa14ef16663ab9ea51a1c1 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from collections import defaultdict
from collections import deque
import torch
class SmoothedValue():
"""Track a series of values and provide access to smoothed values over a
window or the global series average.
"""
def __init__... | smoke/utils/metric_logger.py | MIT | 1,838 | 29c0e8b66d4afbf7f15d9195c15cc84f46f4a720 | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Tuple
import numpy
__author__ = "Christian Heider Nielsen"
__doc__ = ""
import torch
import torch.nn as nn
from neodroidvision.regression.vae.architectures.vae import VAE
__all__ = ["HigginsVae", "BurgessVae"]
class HigginsVae(VAE):
"""Model p... | neodroidvision/regression/vae/architectures/beta_vae.py | Apache-2.0 | 4,452 | 4b169344af4ab592bcfdc89f0a6a63eca4be99b6 | Python | py | |
# -*- coding: utf-8 -*-
# nn_benchmark
# author - Quentin Ducasse
# https://github.com/QDucasse
# quentin.ducasse@ensta-bretagne.org
import unittest
import torch
import torch.nn as nn
import torch.nn.functional as F
from nn_benchmark.networks import LeNet5
from nn_benchmark.networks.common import *
import nn... | tests/networks/test_lenet5.py | MIT | 2,506 | d78731223dabc60ad8358ad06c4afb6e998e3e82 | Python | py | |
import sys
import pickle
sys.path.append('.')
sys.path.append('..')
from lib.networks.model_repository import *
from lib.utils.net_utils import smooth_l1_loss, load_model, compute_precision_recall
import torch
from lib.ransac_voting_gpu_layer.ransac_voting_gpu import ransac_voting_layer_v3
from lib.utils.evaluation_uti... | pose/tools/verification_pipe2_full.py | MIT | 7,941 | 29c1018b0cafb37b6e40239e4944fb1ad50af2a1 | Python | py | |
from torch import nn
from torch.nn import Sequential
from hw_asr.base import BaseModel
class BaselineModel(BaseModel):
def __init__(self, n_feats, n_class, fc_hidden=512, *args, **kwargs):
super().__init__(n_feats, n_class, *args, **kwargs)
self.net = Sequential(
# people say it can a... | hw_asr/model/baseline_model.py | MIT | 821 | 7c3c9c2be4a59724428e3395594d7cd8e7e0bb20 | Python | py | |
import torch
from .group_norm import GroupNorm3d as groupnorm
torch_ver = torch.__version__[:3]
__all__ = ['ConvContextBranch']
import torch
import torch.nn as nn
def normal_conv_blocks(in_channels, out_channels):
return nn.Sequential(
nn.Conv3d(in_channels, out_channels, 3, padding=1),
groupnor... | experiments/convcontextbranch.py | MIT | 1,419 | 29c1349ebfe856d10d624ac1f1e3e70f6142ed11 | Python | py | |
from __future__ import print_function, absolute_import
import argparse
import os.path as osp
import random
import numpy as np
import sys
from apex import amp
import torch
from torch import nn
from torch.backends import cudnn
from torch.utils.data import DataLoader
from visda import datasets
from visda import models
f... | examples/source_pretrain.py | MIT | 9,664 | e96749831c311e6d55b96f6e9ad11060ad6b693c | Python | py | |
"""
Modified from OpenAI Baselines code to work with multi-agent envs
"""
import numpy as np
import torch
from multiprocessing import Process, Pipe
from abc import ABC, abstractmethod
from onpolicy.utils.util import tile_images
class CloudpickleWrapper(object):
"""
Uses cloudpickle to serialize contents (other... | onpolicy/envs/env_wrappers.py | MIT | 28,209 | 1e1806db1e446eefbcb8c7256e67cdae6c522fee | Python | py | |
import torch.nn as nn
import numpy as np
class Generator(nn.Module):
def __init__(self, batchnorm, latent, img_shape):
super(Generator, self).__init__()
if batchnorm:
self.model = nn.Sequential(
nn.Linear(latent, 128),
nn.ReLU(),
nn.Batc... | gan/net.py | MIT | 2,233 | 105ac69320234dd736ae5d8d6fd3c9bb9251abb4 | Python | py | |
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "5"
import logging
import random
import sys
from tqdm import tqdm
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchnet.meter import ConfusionMeter
from man_models import *
from data_prep.msda_preprocessed_amazon_... | code/train_exp2_with_F_d_target_with_pre-training_weight.py | MIT | 20,846 | 24fdf39bd9027202dc451d612be323167c949eee | Python | py | |
import torch
from models.fatchord_version import WaveRNN
from models.forward_tacotron import ForwardTacotron
from utils.text.symbols import symbols
from utils.text import text_to_sequence
from utils.dsp import reconstruct_waveform
from utils import hparams as hp
import numpy as np
def init_hparams(hp_file):
hp.c... | notebook_utils/synthesize.py | MIT | 2,379 | 4272a84b426b25605bf1a0d82d583383eb8b28d4 | Python | py | |
import torch
from torchsso import Curvature, DiagCurvature, KronCurvature
class CovLinear(Curvature):
def update_in_backward(self, grad_output):
data_input = getattr(self._module, 'data_input', None) # n x f_in
assert data_input is not None
n = data_input.shape[0]
if self.bias:... | torchsso/curv/cov/linear.py | MIT | 3,452 | 7c0fdccf071ace0bd15595035b93ca8340c02ec0 | Python | py | |
# Copyright 2020 Lorna Authors. 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 l... | research/utils.py | Apache-2.0 | 5,976 | 29c18149e210fe43fb8134c8ff427fcf5ba32173 | Python | py | |
import os
import sys
import glob
import setuptools
from setuptools import setup, Extension, find_packages
from setuptools.command.build_ext import build_ext
from setuptools.command.develop import develop
from setuptools.command.install import install
from distutils.cmd import Command
from wheel.bdist_wheel import bdist... | py/setup.py | BSD-3-Clause | 10,968 | 1e272d3d8dd08caf1736fd1539e8dac3e27aab57 | Python | py | |
# -*-coding:utf-8-*-
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import argparse
import logging
import time
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torchvision.transforms as transforms
import yaml
from easydict import EasyDict
from torch.utils.tensorboard import SummaryWri... | train.py | MIT | 7,078 | 29c1abad7ea0d88676e9fce9322db4bd90c6bcc6 | Python | py | |
# modified by Sherif Abdelkarim on Jan 2020
import numpy as np
from numpy import linalg as la
import math
import logging
import json
import torch
from torch import nn
from torch.nn import init
import torch.nn.functional as F
from torch.autograd import Variable
import nn as mynn
from core.config import cfg
import uti... | lib/modeling/reldn_heads_reltransformer.py | MIT | 23,467 | 29c1abf65040b37eddb122c9f6e1f9871697173c | Python | py | |
from __future__ import division
import numpy as np
import torch
import torch.nn as nn
from mmcv.cnn import normal_init
from mmdet.core import (AnchorGenerator, anchor_target, delta2bbox, force_fp32,
multi_apply, multiclass_nms)
from ..builder import build_loss
from ..registry import ... | mmdet/models/anchor_heads/anchor_head.py | Apache-2.0 | 14,234 | 1edd786a609bb3d675adca8e2c1c28d961730a79 | Python | py | |
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import itertools
import numbers
from collections import OrderedDict
import opt_einsum
import pytest
import torch
import pyro.ops.jit
from pyro.distributions.util import logsumexp
from pyro.ops.contract import _partition_terms, co... | tests/ops/test_contract.py | Apache-2.0 | 25,695 | fd68439c4ab685ac538fe523ced9e4cae1a167b4 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.