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 |
|---|---|---|---|---|---|---|---|
# 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/model_checkpoint.py | Apache-2.0 | 18,423 | 29eb2b1fb5dd85b702814527cd7352a5de6f996c | Python | py | |
import argparse
import glob
import importlib
import os
import sys
import numpy as np
import torch as th
import yaml
from stable_baselines3.common.utils import set_random_seed
import utils.import_envs # noqa: F401 pylint: disable=unused-import
from utils import (
ALGOS,
create_test_env,
get_latest_run_id,... | enjoy.py | MIT | 11,444 | e61705aacf39ce74d464ca261f5794df51719020 | Python | py | |
from inference_tool import InfTool
from collections import Counter
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
import argparse
import cv2
import os
import glob
import pathlib
import torch.nn.functional as F
import torch
def parse_args(argv=None):
parser = argparse.Argume... | yolact_vision/process_video.py | MIT | 4,630 | 6547e61b7cffbe747eea9e0ba13b87006e6d85d5 | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Created : 2021/09/02 1:32 오후
# @Author : Junhyung Kwon
# @Site :
# @File : loss.py
# @Software : PyCharm
import torch
import torch.nn as nn
from torch.nn.modules.loss import _Loss
import torch.nn.functional as F
class RobustLoss(_Loss):
def __init_... | src/training/loss.py | Apache-2.0 | 1,333 | a92b17b5d57907e4a1a20b0f06560ef675dd73d4 | Python | py | |
'''
The Base-Net described in our paper.
'''
import torch
import torch.nn as nn
from src.network import Conv2d
import time
class base(nn.Module):
def __init__(self, pool, bn=False):
super(base, self).__init__()
kernel_size = 5
self.pool = pool
if kernel_size==7:
... | src/models/base.py | MIT | 2,788 | 29eb72092e60d84195e66cee7d003a8cce5f710e | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import argparse
import copy
import logging
import os
import numpy as np
import torch
from tools.scripts.features.extraction_utils import chunks, get_image_files
from tools.scripts.features.frcnn.frcnn_utils import Config
from tools.scripts.features.frcnn.modeling_f... | mmf_modified/tools/scripts/features/frcnn/extract_features_frcnn.py | MIT | 11,197 | 29eb7fa65eaaa07913e8bb1f90a0c65ea710ab52 | Python | py | |
from collections import OrderedDict
from copy import copy
from typing import Tuple, Sequence, Dict, Iterable, Union
from warnings import warn
import torch
from torch.nn import Parameter, ModuleDict, ParameterDict
from torch_kalman.internals.batch import Batchable
from torch_kalman.covariance import CovarianceFromLog... | torch_kalman/design.py | MIT | 18,279 | 29eb821c4f4e7293cd1871b9d95cb17a82c063e0 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class ResidualBlock(nn.Module):
"""Residual Block with instance normalization."""
def __init__(self, dim_in, dim_out):
super(ResidualBlock, self).__init__()
self.main = nn.Sequential(
nn.Conv2d(di... | model.py | MIT | 3,776 | 29eb914bd2324d1e18d6cfe31880bc60ab232e07 | Python | py | |
#-*- coding: utf-8 -*-
import sys
import random
import re
import time
import torch
from torch.autograd import Variable
from torch import optim
import torch.nn as nn
import torch.nn.functional as F
from fattn_model import *
from data_utils import *
def init_command_line(argv):
from argparse import ArgumentParser
... | seq2seq/general/fast_attn/fattn_predict.py | MIT | 5,081 | a937f32d54cfaa49ea921908d320a03278803729 | Python | py | |
import torch
import numpy as np
import math
def _flatten(sequence):
flat = [p.contiguous().view(-1) for p in sequence]
return torch.cat(flat) if len(flat) > 0 else torch.tensor([])
def compute_cc_weights(nb_steps):
lam = np.arange(0, nb_steps + 1, 1).reshape(-1, 1)
lam = np.cos((lam @ lam.T) * math.... | adaptiveSTFT/UMNN/models/UMNN/ParallelNeuralIntegral.py | MIT | 4,099 | 7cb9f2a4a04336ff86123b4502113f1f932fef68 | Python | py | |
# utils for working with 3d-protein structures
import os
import numpy as np
import torch
from functools import wraps
from einops import rearrange, repeat
# bio
import mdtraj
try:
from sidechainnet.utils.sequence import ProteinVocabulary as VOCAB
from sidechainnet.utils.measure import GLOBAL_PAD_CHAR
from s... | alphafold2_pytorch/utils.py | MIT | 31,270 | 29eba5bc114cfd8af06a85e920c6cfbfb92cbf6a | Python | py | |
import torch
import itertools
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
import time, numpy as np
class CycleGANGuessModel(BaseModel):
"""
This class implements the CycleGAN model, for learning image-to-image translation without paired data.
The model t... | models/cycle_gan_guess_model.py | BSD-3-Clause | 17,699 | 29ebb2570952cf9b013b84a707fe0bf8d0d60892 | Python | py | |
# ------------------------------------------------------------------------
# Modules to compute the matching cost and solve the corresponding LSAP.
# Copyright (c) 2021 Microsoft. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------... | models/matcher.py | Apache-2.0 | 4,941 | 29ebb5b628c644ce3a0a13980cf3f0e8f0666b77 | Python | py | |
# Pytorch Tabular
# Author: Manu Joseph <manujoseph@gmail.com>
# For license information, see LICENSE.TXT
"""Base Model"""
import logging
from abc import ABCMeta, abstractmethod
from typing import Callable, Dict, List, Optional
import pytorch_lightning as pl
import torch
import torch.nn as nn
from omegaconf import Dic... | pytorch_tabular/models/base_model.py | MIT | 8,294 | 29ebcacf2319f3de50cda99f02152113fa5ab9f8 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import layers
from utils import vocab, pos_vocab, ner_vocab, rel_vocab
class TriAN(nn.Module):
def __init__(self, args):
super(TriAN, self).__init__()
self.args = args
self.embedding_dim = 300
self.embedding = nn.E... | src/trian.py | MIT | 8,970 | fcc76db9a4bb5e9842a57497a9a9ca7c2f24769f | Python | py | |
# calculate averaged weight of a model without SMC
import torch
from decimal import Decimal
import shamir_smc as ss
def share_weights(models):
state_dicts = []
state_dicts = [models[i].state_dict() for i in range(len(models))]
for key in state_dicts[0]:
#print(0,state_dicts[0][key])
fo... | smc_utils/weight_averaging.py | MIT | 4,298 | 6b42516cc764e2f54bb0ca7bb9c0e976d81e5944 | Python | py | |
import logging
import torch
from torchvision import transforms, datasets
from torch.utils.data import DataLoader, RandomSampler, DistributedSampler, SequentialSampler
logger = logging.getLogger(__name__)
def get_loader(args):
if args.local_rank not in [-1, 0]:
torch.distributed.barrier()
transfor... | utils/data_utils.py | MIT | 2,990 | 29ec20aaf331a9bfeb8d283ab1beb1c30f311ef9 | Python | py | |
from gym.envs.atari import AtariEnv
import cv2
import numpy as np
import torch
import torch.optim as optim
import torch.nn.functional as F
from memory import MemoryReplay
from CONST import *
from tqdm import tqdm
makeEnv = lambda game: AtariEnv(game,
obs_type= 'image',
... | actors.py | MIT | 16,224 | 5f9b87c779095afbdddefba9c7628c2137968102 | Python | py | |
#%%
import os
import matplotlib.pyplot as plt
import numpy as np
import torch
from torchvision import transforms
import random
from PIL import Image
from torchvision.transforms import Compose, ToTensor, Normalize
import torchvision.transforms.functional as F
class CrowdDataset(torch.utils.data.Dataset):
'''
C... | dataset.py | MIT | 5,135 | 4bbb8ba363a1e1c2e69ecd61690273804af44732 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import transforms, models
from torchvision.models import resnet18
from models.train import train
# from scripts.load_data import get_data
from models.resnet import resnet34, resnet18
class MNIST_Net(nn.Module):
... | models/simple_model.py | MIT | 3,815 | 52bccac71d0b2bb7e2b0793c96e3c33c9ff22935 | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
from utils.net import make_conv, make_fc, convert_conv2convws_model
from rcnn.utils.poolers import Pooler
from rcnn.modeling import registry
from rcnn.core.config import cfg
@registry.ROI_BOX_HEADS.register("roi_xconv1fc_head")
class roi_xconv1fc_head(nn.Module):... | rcnn/modeling/fast_rcnn/heads/convfc_heads.py | MIT | 2,130 | 29ec971b38812f150ec04686c696eb9fbb7c6a7d | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import atexit
import torch
import torch.multiprocessing as mp
from ..utils.stop_token import _StopToken
from .predictor import Predictor
from tsn.util import logging
logger = logging.get_logger(__name__)
class AsycnPredi... | demo/slowfast/visualization/predictor/async_predictor.py | Apache-2.0 | 3,747 | 29ec97a6e9d0cb7ba74353813553a6c89c67db1b | Python | py | |
import random
import os
import numpy as np
import torch
import nltk
from torch.utils.data import TensorDataset, DataLoader
nltk.download('punkt')
import argparse
import os
from transformers import AutoTokenizer
from utils.model import *
from utils.data_loader import pad_and_truncate_seqs, create_vocab, read_data, text... | test.py | MIT | 5,550 | f9ee513754c4fdacb454637dfbf22b29484c73f6 | Python | py | |
import matplotlib.pyplot as plt
import torch
import numpy as np
LOG_FILE = '../results/cmc_compare_reward_envs/best0.pt'
def get_data():
data = torch.load(LOG_FILE)
reward_list = data['reward_list']
print(len(reward_list))
count = 0
for rewards in reward_list:
if max(rewards) > 90:
... | experiments/GTNC_visualize_cmc_compare_reward_envs_print_baseline.py | MIT | 414 | 29ecb42705ada9068b647e78aa1e0a49f84586fc | Python | py | |
import json
import logging
import numpy as np
import pathlib
import torch
import platalea.dataset as D
import platalea.rank_eval as E
from utils.extract_transcriptions import extract_trn
from platalea.experiments.config import get_argument_parser
args = get_argument_parser()
logging.basicConfig(level=logging.INFO)
... | platalea/utils/evaluate_pipeline.py | Apache-2.0 | 2,373 | ff42f36ed1f21905758a545766133d8fa11b6d8b | Python | py | |
from typing import Callable
import torch
# Slow implementation, to be improved
# See https://github.com/pytorch/pytorch/issues/8304
@torch.jit.ignore
def elementwise_apply_pt18(f, x: torch.Tensor) -> torch.Tensor:
# TODO: torch.vmap in 1.9
# NOTE: torch.vmap still isn't in stable in PyTorch 1.9, it can be cal... | src/python/ksc/torch_utils.py | MIT | 1,063 | 45cf221b358722d67c24a5f91a80470fc46c2acb | Python | py | |
import comet_ml # logging hook must be imported before torch # noqa F401
import torch
from adaptor.adapter import Adapter
from adaptor.evaluators.generative import BLEU, ROUGE, BERTScore
from adaptor.lang_module import LangModule
from adaptor.objectives.seq2seq import Sequence2Sequence
from adaptor.objectives.seq_ber... | experiments/sbert_context/adapt_emea_es-en.py | MIT | 7,215 | 29ecfe8a0ab491accc14c3021f0a2b808c799700 | Python | py | |
import torch
from torch import nn
import torch.nn.functional as F
import utils
import torchvision as tv
from classifier import SimpleClassifier
from fc import FCNet
from attention import Attention
class vgg16_modified(nn.Module):
def __init__(self):
super(vgg16_modified, self).__init__()
vgg = tv.m... | model_agentplace365_verbq_diffeval_topkmax.py | MIT | 8,263 | 1e3e33be3d5c35aae43bbc76d2dd4a224582b1bb | Python | py | |
import torch
import torch.nn as nn
from ..utils import load_state_dict_from_url
__all__ = [
'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
'vgg19_bn', 'vgg19',
]
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
'vgg13': 'https://download.pytorc... | references/edgeailite/xvision/models/backbone/vgg.py | BSD-3-Clause | 7,234 | 29ed1ee1e80bcbdce82316afb01f5533b91c1f39 | Python | py | |
"""This library gathers utilities for data io operation.
Authors
* Mirco Ravanelli 2020
* Aku Rouhe 2020
* Samuele Cornell 2020
"""
import os
import shutil
import urllib.request
import collections.abc
import torch
import tqdm
import pathlib
import speechbrain as sb
import re
def undo_padding(batch, lengths):
... | speechbrain/utils/data_utils.py | Apache-2.0 | 16,459 | 52affc4cf877e200664514fdbe203333665e9226 | Python | py | |
import torch
import time
import numpy as np
from all.core import State
from .writer import ExperimentWriter, CometWriter
from .experiment import Experiment
from all.environments import VectorEnvironment
from all.agents import ParallelAgent
import gym
class ParallelEnvExperiment(Experiment):
'''An Experiment obje... | all/experiments/parallel_env_experiment.py | MIT | 4,791 | 03ab1d9b5cfff006d75a9d4987a632a42100dc93 | Python | py | |
import glob
import os
import random
import shutil
from pathlib import Path
import cv2
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
from tqdm import tqdm
# from . import torch_utils # , google_utils
matplotlib.rc('font', **{'size': 11})
# Set printoptions
t... | pipert/contrib/detection_demo/utils.py | MIT | 34,980 | d7716e796855c2393770e488bafd2be5df8ca84e | Python | py | |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.distributions import Normal
from torch.distributions.categorical import Categorical
from collections import deque
import sys
from PIL import Image
import PIL
import numpy as np
np.set_printoptions(threshold=sys.ma... | Other_Agents/agent2.py | MIT | 14,227 | 29ed7470f1b317a08e9098476ebf3528251626ac | Python | py | |
import os
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision.transforms as standard_transforms
import misc.transforms as own_transforms
import tqdm
from model.locator import Crowd_locator
from misc.utils import *
from PIL import Image, ImageOps
import cv2
import json
d... | test.py | MIT | 9,309 | 52c84f4383f205f62d3ee3390610b6394d44b85d | Python | py | |
"""
This file defines the core research contribution
"""
import math
import torch
from torch import nn
import pprint
from models.stylegan2.model import Generator
from configs.paths_config import model_paths
from models.encoders import fpn_encoders, restyle_psp_encoders
from utils.model_utils import RESNET_MAPPING
cl... | models/psp.py | Apache-2.0,BSD-2-Clause,MIT | 6,550 | e91c21e1dbe1fdb19693ac6f7be27ce594a948f5 | Python | py | |
import grpc
from nbt import nbt
import json
import torch
import os
from collections import OrderedDict
from evocraftsearch.evocraft import minecraft_pb2_grpc
from evocraftsearch.evocraft.minecraft_pb2 import *
channel = grpc.insecure_channel('localhost:5001') #WORLD ORIGIN: (0,4,0)
client = minecraft_pb2_grpc.Minecraf... | evocraft/utils.py | MIT | 7,570 | 5f9b4dbed895a60ed76e67ef86f9eeeb7ec6cfd3 | Python | py | |
import torch
import numpy as np
from deluca.lung.core import Controller
from deluca.lung.utils.core import BreathWaveform
from deluca.lung.utils.core import Phase
class ResidualExplorer(Controller):
def __init__(self, base_controller, waveform, **kwargs):
self.base_controller = base_controller
se... | deluca/lung/controllers/_residual_explorer.py | Apache-2.0 | 2,674 | 5f855d94aaa8071bd8841d45427303d18e13c1c1 | Python | py | |
import os
import pytest
import torch
import pytorch_pfn_extras.onnx as tou
from tests.pytorch_pfn_extras_tests.onnx.test_export_testcase import Net
@pytest.mark.filterwarnings("ignore:Named tensors .* experimental:UserWarning")
def test_onnx_load_model():
model = Net()
outdir = "out/load_model_test"
tou... | tests/pytorch_pfn_extras_tests/onnx/test_load_model.py | MIT | 918 | 6b42790dafdbd5621ed121da922a0750203f73ba | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Agents for handling the generation aspects of Wizard.
"""
from itertools import chain
from functools import lru_cach... | projects/wizard_of_wikipedia/generator/custom_code/agents.py | MIT | 12,070 | 29edf233b2b5166a4ae0989247edea7b258b3376 | Python | py | |
import argparse
import datetime
import random
import time
from pathlib import Path
import numpy as np
import torch
from torch.utils.data import DataLoader
from utils import misc as utils
from datasets.StaticDataset import build_dataset, collate_fn
from datasets import samplers
from engine import train_one_epoch
from mo... | train.py | Apache-2.0 | 8,693 | 700a4cb3261704771a3dc1d274a005dcc06ac4ae | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
#from torchsummary import summary
from torch.autograd import Variable
from protonets.models import register_model
from .utils import euclidean_dist
class Flatten(nn.Module):
def __init__(self):
super(Flatten, self).__init__()
def for... | protonets/models/few_shot.py | MIT | 2,422 | a9827d698266d6e56983ae19c98c930a7b5c3d19 | Python | py | |
import torch
import numpy as np
from rlpyt.models.mlp import MlpModel
from rlpyt.utils.tensor import infer_leading_dims, restore_leading_dims
class PixelControlModel(torch.nn.Module):
def __init__(
self,
input_shape,
fc_sizes,
reshape,
channels,
... | rlpyt/ul/models/ul/pixel_control_models.py | MIT | 3,825 | ffab8e57fa831b480c4b762ac7a6f15dc08fabc2 | Python | py | |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 22 21:50:35 2022
@author: taeni
"""
cfg = m4cfg
dataset = m4dataset
model_type='interpretable'
seasonal_pattern = cfg.seasonal_patterns[0]
lookback = cfg.lookbacks[0]
loss = cfg.losses[0]
from torchinfo import summary
summary(model, )
import numpy as np
import pandas... | doodle.py | MIT | 10,298 | 1e38e34373df92c4df094b923866f9b62e0e3efb | Python | py | |
import torch
from torch.nn import functional as F
from maskrcnn_benchmark.structures.bounding_box_3d import cat_boxlist_3d
from data3d.dataset_metas import DSET_METAS
DEBUG = False
WALL_ID = DSET_METAS.class_2_label0['wall']
SHOW_PROPOSALS = 0
class SeperateClassifier():
def __init__(self, seperate_classes, num_... | maskrcnn_benchmark/modeling/seperate_classifier.py | MIT | 15,776 | 29ee244e92b4d4eae1c3322740030e6f364ca8e7 | Python | py | |
"""
Some simple logging functionality, inspired by rllab's logging.
Logs to a tab-separated-values file (path/to/output_directory/progress.txt)
"""
import json
import joblib
import shutil
import numpy as np
import pandas as pd
# import tensorflow as tf
import torch
import os.path as osp, time, atexit, os
import warn... | lstm_td3/utils/logx.py | MIT | 17,911 | 29ee39ecd76f2b85dc81456572b6c7642f1f7e17 | Python | py | |
import onnx
import torch
from onnx_pytorch.op_code_generators import OpCodeGenerator
class GemmOpCodeGenerator(OpCodeGenerator):
def __init__(self,
onnx_ver=onnx.defs.onnx_opset_version(),
torch_ver=torch.__version__):
super(GemmOpCodeGenerator, self).__init__(onnx_ver, torch_ver... | onnx_pytorch/op_code_generators/Gemm.py | Apache-2.0 | 1,030 | 7c1f69fa48e54afe81626f177e82980d8f4a8cb8 | Python | py | |
# coding=utf-8
# Copyright 2018 Salesforce and HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# h... | transformers/modeling_tf_ctrl.py | Apache-2.0 | 24,548 | 29ee5113a4640f13219d2b62b31c489f2ac27e90 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import CONV_LAYERS, ConvAWS2d, constant_init
from mmcv.ops.deform_conv import deform_conv2d
@CONV_LAYERS.register_module(name='SAC')
class SAConv2d(ConvAWS2d):
"""SAC (Switchable Atrous Convolution)
This is an implementation of... | mmcv_bak/ops/saconv.py | Apache-2.0 | 4,696 | 29ee6a7b79adb68185108f5ed5d27fc2f86e9415 | Python | py | |
#!/usr/bin/env python3
import torch
def _create_batch_indices(batch_shape, repeat_size, device):
"""
A helper method which creates a list of batch indices for use with the LazyTensor _get_indices method
"""
batch_indices = []
for i, batch_size in enumerate(batch_shape):
batch_index = torc... | gpytorch/utils/batch.py | MIT | 634 | 5e65f6f924e004a17ca1a117a03eb5c25fb950d3 | Python | py | |
import torch
from torch import nn
from torch.nn import functional
class YoloV1Loss(nn.Module):
def __init__(self, Lambda=4, S=7, B=1, C=20):
super(YoloV1Loss, self).__init__()
self.Lambda = Lambda
self.S, self.B, self.C = S, B, C
def forward(self, predict, target):
batches = t... | models/Loss/YoloV1.py | MIT | 1,460 | 29eea676eeb77a671cc26390367c0517264f3596 | Python | py | |
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import importlib
import os
import json
import logging
import pickle
from unittest import mock
import pytest
import numpy as np
import pandas as pd
import sklearn.datasets as datasets
import yaml
import mlflow.pyfunc as pyfunc
import mlflow.pyt... | tests/pytorch/test_pytorch_model_export.py | Apache-2.0 | 45,095 | 5eb2228ecb45daf7dd7655017de70c238a69cb18 | Python | py | |
import torch
from torch import nn
class ClassificationLoss(nn.Module):
def __init__(self):
super().__init__()
self.loss = None
def forward(self, targets, *outputs):
"""
:param targets:
:param outputs:
:return: loss and accuracy values
"""
output... | classifier/losses.py | MIT | 1,474 | e9d144bab6474e2dd33fee0f6f862cbcb6fbc5b5 | Python | py | |
from abc import ABCMeta, abstractmethod
import torch
import torch.distributions as dist
from ..util.affine import apply_warp
from ..rendering import render_image
from ..parameters import Parameters
class ConceptImageDist(object):
__metaclass__ = ABCMeta
def __init__(self, lib):
self.lib = lib
@... | pybpl/model/image_dist.py | MIT | 2,041 | 29eecc1a31d97e16e6efae38365f3933ba7613a5 | Python | py | |
# -*- coding: utf-8 -*-
#
# Developed by Haozhe Xie <cshzxie@gmail.com>
import json
import logging
import os
import random
import sys
from enum import Enum, unique
import numpy as np
import scipy.io
import scipy.ndimage
import torch.utils.data.dataset
from PIL import Image
import utils.binvox_rw
@unique
class Data... | src/models/Pix2Vox/utils/data_loaders.py | MIT | 14,871 | 29ef3dd919b6a290db662ca1b7583aabd107773e | Python | py | |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
import os.path as osp
import torch
from typing import List
from decimal import Decimal
from colossalai.context import ParallelMode
from colossalai.core import global_context as gpc
from colossalai.registry import HOOKS
from colossalai.logging import Distribute... | colossalai/trainer/hooks/_log_hook.py | Apache-2.0 | 12,331 | 29ef4efa3c5e99db28fddffb5ca2dcb7fc18a408 | Python | py | |
import csv
import os
from torchaudio.datasets import ljspeech
from torchaudio_unittest.common_utils import (
TempDirMixin,
TorchaudioTestCase,
get_whitenoise,
normalize_wav,
save_wav,
)
class TestLJSpeech(TempDirMixin, TorchaudioTestCase):
backend = "default"
root_dir = None
data = ... | test/torchaudio_unittest/datasets/ljspeech_test.py | BSD-2-Clause | 2,650 | 7c1128c31b0e7f4e55a4a13054c56e7d5d3a74a5 | Python | py | |
import torch
import torch.nn as nn
from torch.nn import init
from torchvision import models
from torch.autograd import Variable
import pretrainedmodels
import timm
######################################################################
def weights_init_kaiming(m):
classname = m.__class__.__name__
# print(classn... | model.py | MIT | 9,326 | 107df8500b5bce77b6ff6b181b43e874f6ae9e81 | Python | py | |
# Copyright 2021 Zilliz. 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 law or agree... | tests/unittests/models/layers/test_cond_conv2d.py | Apache-2.0 | 1,292 | 29eff46fc0e8ca1cb811791a32f7fe71e29b6b33 | Python | py | |
from __future__ import division
import math
import torch
def perspective(vertices, angle=30.):
'''
Compute perspective distortion from a given angle
'''
if (vertices.ndimension() != 3):
raise ValueError('vertices Tensor should have 3 dimensions')
device = vertices.device
angle = torch.... | neural_renderer/perspective.py | MIT | 632 | 29eff5dc2f718e89b52b06951e2e414f3d1607c5 | Python | py | |
import os
import sys
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
def setup(rank, world_size):
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] =... | examples/pytorch_train_ddp.py | MIT | 1,500 | 24d08641062e0350d91cf5b5695bbf329a7fcd2b | Python | py | |
# -*- 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
import logging
import sys
import time
import math
import torch
import torch.nn.functional as F
import torch.fft
from torch import nn
from tor... | src/nets/vcneuvoco.py | Apache-2.0 | 161,316 | 804b2e13a6827e8d7e034a6318642a8128c87998 | Python | py | |
""" A easy script to run GIN model.
"""
import os
import os.path as osp
from datetime import datetime
import random
import logging
import torch
import yaml
from slgnn.configs.base import Grid, Config
from slgnn.configs.arg_parsers import ModelTrainingArgs
from slgnn.data_processing.zinc_dataset import ZINC
from slgnn... | slgnn/training/pretrain_gin_with_zinc.py | MIT | 2,759 | 29f007e63b751a8a63f8a4107fa1de672890fc4d | Python | py | |
# -*- coding: utf-8 -*-
import torch
import numpy as np
import inspect
from ..layer import create_tensor
from ....optim import Optimizer
from ....optim import prepare_optim as desc_to_optim_scipy
class TorchOptimizer(Optimizer):
"""Wrapper for a PyTorch optimization algorithm.
The :class:`TorchOptimizer` pro... | ceml/backend/torch/optimizer/optimizer.py | MIT | 4,983 | a9039d31d88d9520606a9caa76bff273b4d6b1ef | Python | py | |
from typing import List
import numpy
import torch
from torch.optim.optimizer import Optimizer
from torch.utils.tensorboard import SummaryWriter
from learning_models.abstract_model import AbstractModel
import utils.derivatives as derivatives
from learning_models.optimizers.sir_optimizer import SirOptimizer
from utils.... | learning_models/new_torch_sir.py | MIT | 12,131 | 70984c4e0e52e93a0a68facde88ea1a61d5e1999 | Python | py | |
"""
AllenNLP just uses
`PyTorch learning rate schedulers <http://pytorch.org/docs/master/optim.html#how-to-adjust-learning-rate>`_,
with a thin wrapper to allow registering them and instantiating them ``from_params``.
The available learning rate schedulers are
* `"step" <http://pytorch.org/docs/master/optim.html#torc... | allennlp/training/learning_rate_schedulers.py | Apache-2.0 | 1,865 | 803dc94609723938174fd81f5988496bbd7f0c8f | Python | py | |
import logging
import sys
from time import strftime, gmtime
import numpy as np
import torch
import torch.nn as nn
from metrics.nll import NLL
from utils.data_loader import GenDataIter
class Signal:
"""Running signal to control training process"""
def __init__(self, signal_file):
self.signal_file = ... | src/utils/helpers.py | MIT | 6,237 | 3467b849993f02e1ede412e07c7b3c9d8c6adb67 | Python | py | |
import torch
from torch import nn
from torch import Tensor
from models.SplineActivations.deepBspline import DeepBSpline
from models.SplineActivations.deepBspline_lipschitz_maxprojection import DeepBSplineLipschitzMaxProjection
from models.SplineActivations.deepBspline_lipschitz_orthoprojection import DeepBSplineLipschi... | models/SplineActivations/basemodel.py | MIT | 16,304 | d768b1c4a99248deca50a3699a4719964f9807cc | Python | py | |
from ..core import Node, Operator, ApplyToDataDict, DataDict, Data
from .ImageData import ImageClassificationData
from typing import List, Tuple
from pathlib import Path
import torch
import torch.nn.functional as F
from tqdm import tqdm
import gc
class BatchTrainer(Node):
def __init__(self, model, **kwargs):
... | potok/vision/BatchTrainer.py | Apache-2.0 | 2,419 | a994eac94d5709d3db76410c5e34da21dd18fee6 | Python | py | |
import logging
import torch
import torch.nn
import torch.nn.functional as F
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class NumModel(torch.nn.Module):
"""Monomodal model of numerical feature.
Text module is based on BioBERT.
"""
def __init__(self, num_feature_dim: int, drop... | src/models/modules/num_module.py | MIT | 898 | 457e4ee8d68b72a4d96c66c4f215c09772fd4fe1 | Python | py | |
from torch.utils.data import Dataset
import torch
import numpy as np
from numpy.random import randint, choice
import glob
class bearing_dataset(Dataset):
def __init__(
self, path: str = './data/Image/train',
class_lst: list = ['Ball', 'Normal', 'Inner_break', 'Outer_break'],
train: bool = T... | project_header/dataset.py | MIT | 1,898 | 29f04bb15f18ed3bd6fcb02bb9abb3d8521292a3 | Python | py | |
import os, h5py
import numpy as np
from PIL import Image
import torch
from torch.utils.data import Dataset
from torchvision.transforms import Compose, Normalize, ToTensor
from lib.alphabet import strLabelConverter
from lib.path_config import data_roots, data_paths
class Hdf5Dataset(Dataset):
def __init__(self, r... | lib/datasets.py | MIT | 5,090 | 29f05dcdfa3cbd374a5fb20e2079e9d1061573e3 | Python | py | |
import os
import numpy as np
import torch, cv2
import random
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
def fixed_resize(sample, resolution, flagval=None):
if flagval is None:
if sample.ndim == 2:
flagval = cv2.INTER_NEAREST
else:
flagval = cv2... | refinement/dataloaders/utils.py | MIT | 3,248 | 1e09f4c198399f322a8852598576737334c3e834 | Python | py | |
"""
DUF testing script, test Vid4 (SR) and REDS4 (SR-clean) datasets
write to txt log file
"""
import os
import os.path as osp
import glob
import logging
import numpy as np
import cv2
import torch
import utils.util as util
import data.util as data_util
import models.archs.DUF_arch as DUF_arch
def main():
######... | codes/test_Vid4_REDS4_with_GT_DUF.py | Apache-2.0 | 10,419 | fcec690d0e864714bc7183d77e31df9499a3f8e9 | Python | py | |
import os
import numpy as np
import torch
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 container_setup
imp... | jiant/scripts/postproc/xtreme/xtreme_submission.py | MIT | 16,576 | 45d723b02083ef0f75136322549398f74653732d | Python | py | |
# -*- coding: utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the... | vega/search_space/fine_grained_space/operators/mix_ops.py | MIT | 4,746 | 1077557c50b8ddec86fd4ed54ed5505180ec88a0 | Python | py | |
# pgir, policy gradients from intrinsic reward sample
# replace pedl reward and value functions altogether with Unif(-1, 1) samples.
import torch, random, os, pdb, copy, random, pickle, agents
import numpy as np
import torch.nn as nn
import torch.multiprocessing as mp
import torch.optim as optim
import pandas as pd
fro... | run_pgir.py | MIT | 8,042 | 29f07691d7c1a7c5e91235a409fff18d49009fd7 | Python | py | |
#!/usr/bin/env python3
# https://github.com/higgsfield/RL-Adventure
import time
import torch
import torch.multiprocessing as mp
from torch import optim
import os
from codes.f_utils.common_utils import make_gym_env
from config.names import PROJECT_HOME
print(torch.__version__)
from common.fast_rl import actions, expe... | rl_main/base/02_cartpole_rainbow_main.py | MIT | 4,883 | 420a7ad9466e06697de97ca8e4bd61b276b2c41b | Python | py | |
import os
import sys
import torch
from torch.testing import FileCheck
from typing import List
# Make the helper files in test/ importable
pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(pytorch_test_dir)
from torch.testing._internal.jit_utils import JitTestCase, freeze_... | test/jit/test_remove_mutation.py | Intel | 10,058 | 29f07f8404bc1076dc0e75cb85a008bc7927d8d8 | Python | py | |
# encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
import logging
import math
import torch
from torch import nn
from fastreid.layers import (
IBN,
SELayer,
Non_local,
get_norm,
)
from fastreid.utils.checkpoint import get_missing_parameters_message, get_unexpected_parame... | fastreid/modeling/backbones/resnet.py | Apache-2.0 | 12,480 | 4b57fd7776a130a5e8e4d83f77b77badd5da481e | Python | py | |
# Yizhak Ben-Shabat (Itzik) <sitzikbs@gmail.com>
# Chamin Hewa Koneputugodage <chamin.hewa@anu.edu.au>
import os, sys, time
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from shapespace.dfaust_dataset import DFaustDataSet
import torch
import utils.visualizations as vis
import numpy as np
... | shapespace/train_shapespace.py | MIT | 9,762 | 29f08c86f8ec139e11863e352487e31452b87037 | Python | py | |
import os
import random
import logging
import numpy as np
from tensorboardX import SummaryWriter
from libbots import data, model, utils
import torch
import torch.optim as optim
import torch.nn.functional as F
import argparse
from model_test import run_test_cosine
device = torch.device("cuda" if torch.cuda.is_availa... | train_rl_cosine.py | MIT | 7,552 | 29f0bc3efef1decc57f5173eb8d4fc72c95010ab | Python | py | |
import math
from time import time
import datasets
import numpy as np
import torch
from model_code.retriever_bert_qa_train import make_qa_retriever_model
def embed_questions_for_retrieval(q_ls, qa_tokenizer, qa_embedding, max_length=128, device='cuda:0'):
q_toks = qa_tokenizer.batch_encode_plus(q_ls, max_length=... | model_code/retriever_bert_qa_embedding.py | MIT | 1,911 | 6b20daac404502e899369db2c40cc30167abbf71 | Python | py | |
# Copyright 2020 - 2021 MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in wri... | tests/test_handler_mean_dice.py | Apache-2.0 | 2,418 | 6b4bea594e6127257e967fc3f0c744a451241cc6 | Python | py | |
import random
import numpy as np
import os
import json
import argparse
import torch
import dataloaders
import models
import math
import copy
from utils import Logger
from trainer_our import TrainerOur
from trainer import Trainer
import torch.nn.functional as F
from utils.losses import abCE_loss, CE_loss, consistency_we... | train_our.py | MIT | 6,033 | 29f0e4c6df8effead0e2360cc2a438b74c21d3df | Python | py | |
import os
from PIL import Image
import os.path
import numpy as np
import matplotlib.pyplot as plt
import cv2
import torch
from torchvision import models, transforms, datasets
import torch.nn.functional as F
from scipy import misc
import pandas as pd
from Networks import *
from tqdm import tqdm
device = torch.devic... | src/classification code/classification_main_savinglog.py | MIT | 9,942 | 29f1085dfa293e893aee998db4c2de94bec64eac | Python | py | |
# determine the units most frequently 'influential' to classification decisions
import argparse
import os
import pickle
import numpy as np
import torch
import torch.utils.data
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torchvision.transforms as transforms
from munch import Munch
from torch.auto... | interpretability/generate_unit_rankings_resnet18.py | MIT | 10,422 | f948837d439cd105ed8aa4a63524e9c905d707b9 | 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/utilities/fetching.py | Apache-2.0 | 15,133 | fd9baf3e9c4f151a5570279f30b7576dde8db37b | Python | py | |
from __future__ import absolute_import, division, print_function, unicode_literals
import torch
import random
from tests.utils import jitVsGlow
import unittest
class TestMatMul(unittest.TestCase):
def test_matmul_1d_1d(self):
"""Test of aten::matmul with two 1d inputs Glow."""
def test_f(a, b):... | torch_glow/tests/nodes/matmul_test.py | Apache-2.0 | 3,384 | 29f12951399421c94fb9d164b6d7ce878c836207 | Python | py | |
"""
Code source: https://github.com/pytorch/vision
"""
from __future__ import division, absolute_import
import torch.utils.model_zoo as model_zoo
from torch import nn
from .efdmix import EFDMix
__all__ = [
'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152',
'resnext50_32x4d', 'resnext101_32x8d', 're... | DomainGeneralization/reid/models/resnet_efdmix.py | MIT | 19,768 | 29f16fe86c2a215e32b286066a99f576f0833826 | Python | py | |
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import argparse
import datetime
import numpy as np
import time
import torch
import torch.backends.cudnn as cudnn
import json
from pathlib import Path
from timm.data import Mixup
from timm.models import create_model
from timm.loss import LabelSmoothin... | train.py | Apache-2.0 | 24,468 | fcb2dc01b40e80ec773729bd5746a403accadba8 | Python | py | |
import numpy as np
import random
import copy
from collections import namedtuple, deque
#from model import Actor, Critic
from model2 import Actor, Critic
import torch
import torch.nn.functional as F
import torch.optim as optim
BUFFER_SIZE = int(1e5) # replay buffer size
BATCH_SIZE = 128 # minibatch size
GAMMA... | Policy-Based_Methods/DDPG/Pendulum/ddpg_agent2.py | MIT | 7,934 | 29f17e9043c46e892e6bef1e406ade00dcff683a | Python | py | |
"""Copyright 2020 ETH Zurich, Seonwook Park
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distr... | util/eve_util.py | BSD-3-Clause | 15,804 | 29f191a59f2ce1a3020d05b7181a5aaa25ac7279 | Python | py | |
from collections import abc
import numpy as np
import torch
def cast_tensor_type(inputs, src_type, dst_type):
"""Recursively convert Tensor in inputs from src_type to dst_type.
Args:
inputs: Inputs that to be casted.
src_type (torch.dtype): Source type.
dst_type (torch.dtype): Destin... | mmpose/core/fp16/utils.py | Apache-2.0 | 969 | 29f191acd3f571ccf875780087e6950fc902659b | Python | py | |
import argparse
from collections import defaultdict
from os import mkdir
import os
import numpy as np
import torch
import datetime
from extension.config import get_parser
from extension.distributed import is_main_process
from extension.utils import str2bool
# opts.title : 图标题
# opts.width : 图宽
# opts.height : 图高
# o... | extension/visualization.py | MIT | 6,762 | 45e0926fe1a7a2f2c1b98fe600424ca3b257f164 | Python | py | |
"""
Script to evaluate the various network configurations for their rendering performance.
Quality is not a concern here
"""
import numpy as np
import sys
import os
import io
import subprocess
import itertools
import imageio
import json
import torch
import matplotlib.pyplot as plt
import matplotlib.ticker
import matpl... | applications/volnet/eval_NetworkConfigsGrid.py | MIT | 15,925 | 42342d2db7d34df1ed028a151a16416f2a1d12c7 | Python | py | |
from pytorch_lightning import LightningDataModule, LightningModule
import torch
from torch.utils.data import Dataset, DataLoader
from torch.optim import AdamW
class TweetDataset(Dataset):
def __init__(self, csv_file, tokenizer):
self.csv_file = csv_file
self.tokenizer = tokenizer
def __len__(... | models/pl_modules.py | MIT | 4,060 | 709de4846821dc41c109f5c50eecec9ec73662df | Python | py | |
from typing import Any
import cv2
import torchvision.transforms as T
from omegaconf import DictConfig
def create_transform(config: DictConfig) -> Any:
if config.mode == 'MPIIGaze':
return T.ToTensor()
elif config.mode == 'MPIIFaceGaze':
return _create_mpiifacegaze_transform(config)
elif c... | ptgaze/transforms.py | MIT | 1,250 | d7bc8f9e8787e2a51d627ef586445d5439d9f6e1 | Python | py | |
# transformer_chatbot
# Copyright (C) 2018 Golovanov, Tselousov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ve... | TCFC/bt_beam/model/loss.py | MIT | 3,439 | 29f1e065bf7254cea9b25da9f21479a44366067c | Python | py | |
#!/usr/bin/env python3
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch
from scipy import sparse
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split
import numpy as np
import pdb
batch_size=20
class DenseNet(nn... | NN Model/dense.py | Apache-2.0 | 4,233 | 1e38fd722e2d3e23eaf0c327edcceed97288edf8 | 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 pathlib
import random
import shutil
import time
import os
import numpy as np
import torch
import torchvision
from ten... | train_unet_essimtv_aug_scSE3.py | MIT | 14,121 | 109c6ab541f2dd1bea3dc795209c7a7ad2cd0c71 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.