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 |
|---|---|---|---|---|---|---|---|
from __future__ import print_function, division
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
import time
import os
import copy
import pickle
... | Networks/RI_4fam1/netRI_4fam1.py | Apache-2.0 | 8,611 | 3462e5696079296d62cda89bfc3802abca94e575 | Python | py | |
import torch
import torch.nn as nn
import numpy as np
from pathlib import Path
class RandInputImage(nn.Module):
def __init__(self, shape=(406, 438, 3)):
super(RandInputImage, self).__init__()
self.shape = shape
self.im = nn.Parameter(torch.rand(self.shape, dtype=torch.float32), requires_gr... | Models/utils/RandInputImage.py | MIT | 706 | 456d88455e838125edbecc2956664362a8dbeb92 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import lib.utils as utils
from lib.encoder_decoder import *
from lib.likelihood_eval import *
from torch.distributions.normal import Normal
from torch.distributions import kl_divergence
class VAE_Baseline(nn.Module):
def __init__(self,
input... | lib/base_models.py | MIT | 6,078 | d7051c3f5e4ed59638a43278125529c3c1a5d183 | Python | py | |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | tests/vision/detection/test_model.py | Apache-2.0 | 2,372 | 70453e6e73f4c2792a94134e5d1f59cb35f92f74 | Python | py | |
# Lab 12 RNN
from string import ascii_uppercase
from collections import OrderedDict
from itertools import count
# In order to use Tensorboard with pyTorch...
from logger import Logger
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
import pre_process as pre
'''
BLSTM ... | cipher/BLSTM.py | MIT | 12,756 | 10d686867aaf0cc035a66900d919146b1ae2d42a | Python | py | |
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def bpr_loss(pos: torch.Tensor, neg: torch.Tensor)-> torch.Tensor:
"""Bayesian Personalized Ranking Loss
Parameters
----------
pos : torch.Tensor
Ranking logit (0..1)
neg : torch.Tensor
... | utils.py | MIT | 456 | 3a22a508466ee8aa1591b50e37a438aded77b43a | Python | py | |
# coding: utf-8
"""
An example of training two sentences classification model with
QNLI dataset.
@author: Weijie Liu
"""
import os
import torch
import sys
fastplm_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
sys.path.append(fastplm_dir)
from fastplm import FastPLM_S2
kernel_name = 'google_a... | examples/double_sentence_classification/train.py | MIT | 1,886 | 3a22b72ab7de29fd32c2fba84680dff53e622252 | Python | py | |
from alibi.api.interfaces import Explainer, Explanation
from alibi.utils.frameworks import has_pytorch, has_tensorflow
from alibi.explainers.cfrl_base import CounterfactualRL, Postprocessing, _PARAM_TYPES
from alibi.explainers.backends.cfrl_tabular import sample, get_conditional_vector, get_statistics
import numpy as ... | alibi/explainers/cfrl_tabular.py | Apache-2.0 | 23,174 | 3a22bc61e5d237c54e5003a1131621f2595616b6 | Python | py | |
import torch
from inputters.constants import PAD
def pad_subtokens(seq, pad_symb):
"""
batch is a list of lists (seq - subtokens)
"""
max_len = max([len(elem) for elem in seq])
seq = [elem+[pad_symb]*(max_len-len(elem)) for elem in seq]
return seq
def vectorize(ex, model):
"""Vectorize a s... | var_misuse/inputters/vector.py | MIT | 2,178 | 3a22c080886d346d055dd1e623c2e58daf560f47 | Python | py | |
# File: adversarial.py
# Creation: Saturday September 19th 2020
# Author: Arthur Dujardin
# Contact: arthur.dujardin@ensg.eu
# arthurd@ifi.uio.no
# --------
# Copyright (c) 2020 Arthur Dujardin
# Basic imports
import sys
import os
from tqdm import tqdm
import numpy as np
import torch
import torch.nn as nn
im... | img2poem/trainers/adversarial.py | MIT | 11,578 | fd7b42284459126be6f3e83d7636c935a3192e05 | Python | py | |
import os
import math
import json
import logging
import torch
import torch.optim as optim
from utils.util import ensure_dir
class BaseTrainer:
"""
Base class for all trainers
"""
def __init__(self, model, loss, metrics, resume, config, train_logger=None):
self.config = config
self.logg... | base/base_trainer.py | MIT | 6,084 | 3a22d823b2cf431a8a91b81ae31b776f3beeb934 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from functools import partial
from my_pvt_v2_ap import (Block, DropPath, to_2tuple, trunc_normal_,register_model, _cfg)
import math
import matplotlib.pyplot as plt
vis = False
class Mlp_old(nn.Module):
def __init__(self, in_features, hidden_featu... | my_pvt23.py | Apache-2.0 | 52,020 | ff87a938f768ceb3a927321127c7dc8f75f108ee | Python | py | |
import os
import torch
from tqdm import tqdm
import numpy as np
from scipy.stats import norm
import sklearn.preprocessing as preprocessing
import argparse
from dataset import Dataset
from model import DeepPunctuation
from config import *
parser = argparse.ArgumentParser(description='Punctuation restoration test')
pa... | src/test.py | MIT | 14,528 | 3a231e889e772366a28c1003668784a33305fff2 | Python | py | |
import argparse
from tqdm import tqdm
import logging
import torch
import torch.nn as nn
import itertools
from collections import Counter
import numpy as np
from sklearn.model_selection import train_test_split
from data import create_data,pad_sequences
import os
import pickle
import time
from data import IM... | cloud/sentiment_analysis/pytorch/eval.py | Apache-2.0 | 6,046 | 454c9791120f3b95429e823a454cb911682eceff | Python | py | |
import mmcv
import numpy as np
import torch
from mmdet.datasets import to_tensor
from mmdet.datasets.transforms import ImageTransform
from mmdet.core import get_classes
def _prepare_data(img, img_transform, cfg, device):
ori_shape = img.shape
img, img_shape, pad_shape, scale_factor = img_transform(
i... | mmdet/apis/inference.py | Apache-2.0 | 1,971 | 3479febc0c082168a28c67c38ad89362cf87ac77 | Python | py | |
import datetime
import math
import os
import time
from multiprocessing import Process
from multiprocessing import Queue
import imageio
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.optim as optim
import torch.optim.lr_scheduler as lrs
matplotlib.use("Agg")
class time... | src/utility.py | Apache-2.0 | 7,555 | 4290e1d2b0c9719ebbca8d5c4ce15da15649cbfe | Python | py | |
# -*- coding: utf-8 -*-
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.optim import Adam
from torch.utils.data import DataLoader
from torch.nn.utils import clip_grad_norm_
import torch.nn.functional as functional
import matplotlib.pyplot as plt
from tqdm i... | language_model.py | Apache-2.0 | 11,434 | b265b1b1622958b3b8af9d9ab73562c6f60f2d45 | Python | py | |
import argparse
import torch
from torchvision import utils
import numpy as np
import random
import copy
from model import Generator
import gradio
torch.set_grad_enabled(False)
class Sampler:
def __init__(self, args):
self.device = args.device
self.seed = random.randint(1,99999)
... | stylegan2/gradio_app.py | MIT | 3,897 | 5eab3b2870c3b81e448f49283f4493d9064b5a6a | Python | py | |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: Yaoyao Liu
## Modified from: https://github.com/pytorch/pytorch
## Tianjin University
## liuyaoyao@tju.edu.cn
## Copyright (c) 2019
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in th... | inclearn/convnet/tools/conv_mtl.py | MIT | 4,162 | b242a1e72a3c0d1533de080a3ee6c814e17c89dc | Python | py | |
# -*- coding: utf-8 -*-
import logging
from torch.utils.data import Dataset
from torch.utils.data.sampler import BatchSampler, SequentialSampler, RandomSampler
from . import get_dataset
from .collate import get_collate
from ..samplers import get_sampler
logger = logging.getLogger('nmtpytorch')
class MultimodalDatas... | nmtpytorch/datasets/multimodal.py | MIT | 6,331 | 24d3ba8adfa800e6eab83599abe75ef934f33978 | Python | py | |
"""Modified AlexNet for depth feature extraction"""
import torch.nn as nn
from torchvision.models.alexnet import AlexNet
import torch.utils.model_zoo as model_zoo
import math
__all__ = ['AlexNetDepth', 'alexnet_depth']
model_urls = {
'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth',
}
c... | lib/depth_backbone/alexnet_depth.py | MIT | 2,849 | d7920e00ed76347b51969ab466b06d0ed7b84376 | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import copy
import os
import random
import string
import unittest
from collections import OrderedDict
from tempfile import TemporaryDirectory
import torch
from torch import nn
from fvcore.common.checkpoint import Checkpoint... | tests/test_checkpoint.py | Apache-2.0 | 8,116 | b270264f4f96ae22d4be4fe5cef3972b9391a957 | Python | py | |
from __future__ import print_function
import os
import argparse
import torch
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingLR, StepLR
from util.data_util import PartNormalDataset
import torch.nn.functional as F
import torch.nn as nn
from model.DGCNN_PAConv import PAConv
import numpy as... | part_seg/main.py | Apache-2.0 | 19,448 | 10cb3c7d09a065d95d6fdcfc1c042383edb9f2d4 | Python | py | |
import torch
import numpy as np
import os
import sys
import optparse
import utils
from PerformanceRNN.config import device, model as model_config
from PerformanceRNN.network import PerformanceRNN
from utils.sequence import EventSeq, Control, ControlSeq
# pylint: disable=E1101,E1102
# =================================... | mg/model/PerformanceRNN/generate.py | Apache-2.0 | 6,984 | 3a23d9db8783302f70dff33bdbc7fa125e68ae14 | Python | py | |
# PPO-LSTM
import gym
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
# Hyperparameters
learning_rate = 0.0005
gamma = 0.98
lmbda = 0.95
eps_clip = 0.1
K_epoch = 2
T_horizon = 20
class PPO(nn.Module):
def __init__(self):
... | ppo-lstm.py | MIT | 4,545 | 4b0212cdef38cc2626c27d813c8a957f3bbd0250 | Python | py | |
from __future__ import division
import sys
from yolov3.utils.utils import load_classes, rescale_boxes
from yolov3.utils.datasets import ImageFolder
from yolov3.yolo import YOLOv3
import os
import time
import random
import datetime
import argparse
import numpy as np
from PIL import Image
import torch
from torch.util... | examples/detect.py | MIT | 4,730 | 5f9dd1095eb2f7110830fc2940f300723de2af38 | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
from typing import cast, Dict, List, Optional, Tuple
import torch
from torc... | torchrec/distributed/planner/shard_estimators.py | BSD-3-Clause | 32,657 | 3a23f8648a6f979a13633443fd510e2b3c690bf2 | Python | py | |
import contextlib
import threading
import time
import torch
import numpy
import task.resnet152 as resnet152
import task.common as util
TASK_NAME = 'resnet152_inference'
@contextlib.contextmanager
def timer(prefix):
_start = time.time()
yield
_end = time.time()
print(prefix, 'cost', ... | task/resnet152_inference.py | Apache-2.0 | 1,483 | d74e759ba333b91e9f95f7e63a8cae129c1afbba | Python | py | |
import torch
import torch.nn as nn
from torch.nn import init
import functools
from torch.nn.parameter import Parameter
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
from torchvision import models
def get_norm_layer(norm_type='instance'):
if norm_type == 'batch':
nor... | models/networks.py | MIT | 19,766 | 3a241611f54723b2bb2f29b626f67f165bf67d2b | Python | py | |
from torch.distributions.transforms import Transform
from torch.distributions import constraints
from torch.nn.functional import softplus
import torch
import math
class TanhTransform(Transform):
r"""
Transform via the mapping :math:`y = \tanh(x)`.
It is equivalent to
```
ComposeTransform([AffineTra... | src/utils/transforms.py | MIT | 1,351 | 24ae2574a54a998be4f92071324f7111555168f7 | Python | py | |
# Copyright (c) 2022-present, FriendliAI Inc. All rights reserved.
"""The module for classes
"""
import math
import torch
class ResumableSequentialSampler:
""" The resumble sequential sampler.
"""
def __init__(self,
samples_per_epoch: int,
batch_size: int,
... | periflow_sdk/dataloading/sampler.py | Apache-2.0 | 4,851 | 3a245501fcbbccc910f21f620493c4e4c88fa9a9 | Python | py | |
from argparse import ArgumentParser
from pathlib import Path
import pytorch_lightning as pl
from sklearn.model_selection import train_test_split
from torch import Tensor
from torch.utils.data import DataLoader
from torchvision import transforms
from lib import dataset
from lib.dataset import StylizationDataset, files... | lib/lightning/datamodule.py | MIT | 4,356 | 24e4315a589994d6ce9405077af432520e6e6118 | Python | py | |
# ------------------------------------------------------------------------------------
# BaSSL
# Copyright (c) 2021 KakaoBrain. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# Modified by: craig.starr
# -------------------------------------------------------------------... | bassl/pretrain/utils/hydra_utils.py | Apache-2.0 | 4,404 | 102a904a8f1de3093a465570384f9552ebe2723e | Python | py | |
import os
import random
import torch
from torch.utils.data import Dataset
from torchsupport.modules.structured import connected_entities as ce
from torchsupport.data.graphio import LazyNodes, LazyAdjacency
class LazySubgraphDataset(Dataset):
def __init__(self, path, node_name, edge_names, depth=3):
self.depth ... | torchsupport/data/structured.py | MIT | 1,457 | 5f0931f26cf1ae26f1a22a0b049b7f4ab82a9fff | Python | py | |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | tests/trainer/test_lr_finder.py | Apache-2.0 | 8,187 | 7c128dc42c67310f3b5fc2ee84577a1f071fad3f | Python | py | |
# Author: Tao Hu <taohu620@gmail.com>
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import math
from cl_utils import pytorchgo_logger as logger
from cl_utils.pytorchgo_util import model_summary
__all__ = [
"VGG",
"vgg11",
"vgg11_bn",
"vgg13",
"vgg13_bn",
"vgg16",
... | models/deeplabv1.py | Apache-2.0 | 12,516 | 3a249f6706d66fcb5a05487733c09ef3bd269af5 | Python | py | |
"""yolo_with_plugins.py
Implementation of TrtYOLO class with the yolo_layer plugins.
"""
from __future__ import print_function
import ctypes
import numpy as np
import cv2
import tensorrt as trt
import pycuda.driver as cuda
import torch
import torchvision
try:
ctypes.cdll.LoadLibrary('./plugins/libyolo_layer.... | utils/yolo_with_plugins.py | MIT | 15,967 | 3a24b16dc5d97891139da214bf286a90ba920af9 | Python | py | |
import ast
import functools
import inspect
import re
import sys
import textwrap
import numpy as np
import taichi.lang
from taichi._lib import core as _ti_core
from taichi.lang import impl, runtime_ops
from taichi.lang.ast import (ASTTransformerContext, KernelSimplicityASTChecker,
transform... | python/taichi/lang/kernel_impl.py | MIT | 36,142 | 7ccad655421ff7418d292989e0f81c2206d87929 | Python | py | |
import math
import torch
def cos_cdist(x1 : torch.Tensor, x2 : torch.Tensor, eps : float = 1e-8):
r'''
Computes pairwise cosine similarity between samples in `x1` and `x2`,
forcing each point l2-norm to be at least `eps`. This similarity between
`(n?, f?)` samples described in :math:`x1` and the `(m?,... | onlinehd/spatial.py | MIT | 1,248 | 3a250d285763a2cae973d76c2b86c30988ded80c | Python | py | |
import gym
import pybullet_envs
import torch
import pprint
import argparse
import numpy as np
from torch.utils.tensorboard import SummaryWriter
from tianshou.policy.modelbase.gp_mlp import GP_MLPPolicy
from tianshou.trainer import onpolicy_trainer
from tianshou.data import Collector, ReplayBuffer
from tianshou.env imp... | examples/InvertedPendulumBullet_v0_gpmlp.py | MIT | 4,345 | e660cae04e86fb2071989495479112b952f6fa3b | Python | py | |
from pytorch_lightning import callbacks
import yaml
import argparse
import numpy as np
import cv2
import matplotlib.pyplot as plt
from matplotlib.colors import LightSource
from models import *
from experiments.vae_experiment import VAEXperiment
from experiments.vae_pix2pix_exp import Pix2pixExperiment
from torch.utils... | load_render.py | MIT | 2,942 | 4b48f9745f6ee65e6f416628dcb5159f5819f5b3 | Python | py | |
import torch.nn as nn
import torch
from ..modeling.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
def init_params(models, mode='xv'):
assert mode in {'xv', 'net2net'}
if not isinstance(models, list):
models = [models]
for model in models:
for m in model.modules():
if isinstance(m, (nn.C... | third_party/rloss/pytorch_deeplab_v3_plus/utils/model_init.py | MIT | 1,098 | e9a2f154c7cc8df508f361e859e827738c4d7823 | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
r"""
This module provides similar functionality as ``torch.distributed.launch``,
with the... | torchelastic/distributed/launch.py | BSD-3-Clause | 17,069 | 3a2584867d73a39f9c49e7fc4b31381ed7a1f2c0 | Python | py | |
"""
Datasets
"""
import numpy as np
from PIL import Image
import torch
from torch.utils.data import Dataset
import utils
class FacialPartsDataset(Dataset):
"""
Facial Parts Dataset
"""
def __init__(self, data_frame, color, transform=None):
self.df = data_frame
self.transform = transfo... | datasets.py | MIT | 1,697 | 3a25a31cc62e814eb788654be5033a8c2c431bbd | Python | py | |
from torch.autograd import Variable
import numpy as np
import torch
from data_util import config
def get_input_from_batch(batch, use_cuda):
batch_size = len(batch.enc_lens)
enc_batch = Variable(torch.from_numpy(batch.enc_batch).long())
enc_padding_mask = Variable(torch.from_numpy(batch.enc_padding_mask)).float(... | training_ptr_gen/train_util.py | Apache-2.0 | 1,973 | 3a25bf5138cef506a4e0d5a8142fb5964ad35495 | Python | py | |
import os
import json
import revtok
import torch
import copy
import progressbar
from vocab import Vocab
from models.model.seq2seq import Module as model
from gen.utils.py_util import remove_spaces_and_lower
class Dataset(object):
def __init__(self, args, vocab=None):
self.args = args
self.dataset... | data/preprocess.py | MIT | 7,928 | 3a260c5c6969f4e0137fe58c8ef5bcec33169557 | Python | py | |
from pytorch_pretrained_bert import BertModel
from pytorch_pretrained_bert.modeling import BertConfig
import torch.nn as nn
import torch
from onmt.encoders.encoder import EncoderBase
class MyEncoderBertEmbeddings(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings.
"""
d... | onmt/encoders/bert_encoder.py | MIT | 4,530 | 3a2612ea5b9c8f68dcbfa1588b3160164e0ce61a | Python | py | |
from typing import Dict
from experiments.basic_func import Basic
import attr
import numpy as np
import torch
from fedrec.preprocessor import PreProcessor
from fedrec.utilities import registry
from fedrec.utilities import saver_utils as saver_mod
from fedrec.utilities.cuda_utils import map_to_cuda
from fedrec.utilities.... | experiments/regression/reg_trainer.py | Apache-2.0 | 2,668 | d70e8ffbc82fc00c68dfe4bf17c0e5121c70f41c | Python | py | |
#
# Copyright 2016 The BigDL Authors.
#
# 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 ... | python/chronos/test/bigdl/chronos/autots/test_autotsestimator.py | Apache-2.0 | 30,274 | 039dff206e28b1b597103c390591c4d779d49df1 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
# Inspired from maskrcnn_benchmark, fairseq
import logging
import os
import pickle
import socket
import subprocess
import warnings
import torch
from torch import distributed as dist
MAX_SIZE_LIMIT = 65533
BYTE_SIZE = 256
logger = logging.getLogger(__name__)
def sy... | mmf/utils/distributed.py | BSD-3-Clause | 8,055 | 104b52b8fc77028f2a7f8a28b77dc5c40566ac43 | Python | py | |
import torch
import torch.nn as nn
import os
import torch.nn.init as init
class BasicConv(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, relu=True, bn=True, bias=False):
super(BasicConv, self).__init__()
self.out_channels = out_planes... | models/RFB_Net_vgg.py | MIT | 18,314 | 3a26489c423492a608c8884fce21ed812e8be9d1 | Python | py | |
"""
This file is copied from https://github.com/pytorch/vision/blob/master/torchvision/models/mobilenet.py
and modified for this project needs.
The Licence of the torch vision project is shown in:https://github.com/pytorch/vision/blob/master/LICENSE
"""
from torch import nn
from torchvision.models.utils import loa... | HMQ/networks/mobilenet_v2.py | Apache-2.0 | 6,084 | 24e273a5dfc4b66236a2f9575445f0039a49987b | Python | py | |
#
# Copyright 2019 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | tools/RNN/rnn_quantizer/pytorch_binding/pytorch_nndct/parse/parser.py | Apache-2.0 | 9,747 | 6504f851f10977caf1f73785d09b29a8b214ecd7 | Python | py | |
from __future__ import division
import torch
import sys
import math
from PIL import Image, ImageOps, ImageEnhance, __version__ as PILLOW_VERSION
try:
import accimage
except ImportError:
accimage = None
import numpy as np
from numpy import sin, cos, tan
import numbers
import collections
import warnings
if sys.v... | torchvision/transforms/functional.py | BSD-3-Clause | 33,323 | 65207e830928784bec23735f28f306e67370836f | Python | py | |
#!/usr/bin/env python
# coding: utf-8
from __future__ import absolute_import, division, print_function
import json
import logging
import math
import os
import random
import warnings
from multiprocessing import cpu_count
import numpy as np
from scipy.stats import mode, pearsonr
from sklearn.metrics import (
conf... | simpletransformers/classification/multi_modal_classification_model.py | Apache-2.0 | 46,680 | 3a26d4abeacc71bc57f9678315f49ef52a16a499 | Python | py | |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
from typing import Any, Dict, Tuple
import torch
from fvcore.common.file_io import PathManager
from detectron2.data import MetadataCatalog
from detectron2.data import detection_utils as utils
from detectron2.dat... | projects/DensePose/densepose/data/dataset_mapper.py | Apache-2.0 | 6,563 | fce5e0d1401ffc32873e1d7b0c8aa2284751d3df | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import neural_dream.helper_layers as helper_layers
class ResNet_50_1by2_nsfw(nn.Module):
def __init__(self):
super(ResNet_50_1by2_nsfw, self).__init__()
self.conv_1 = nn.Conv2d(in_channels=3, out_channels=64, kernel_size=(7, 7), s... | neural_dream/models/resnet/resnet_50_1by2_nsfw.py | MIT | 38,827 | e959faed4f211be8b5665bbf99cd3316840d4ab6 | Python | py | |
#!/usr/bin/env python3
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Definitions of model layers/NN modules"""
import torch
import torch.nn as nn
import torch.nn.functional as ... | reader/docqa/layers.py | MIT | 21,141 | 3a272d6898b5d8a4a796b7c5d01857a8650fee8f | Python | py | |
import torch.nn as nn
import torch.autograd as ag
import torch
import os
import pdb
import math
import time
import torch.utils.model_zoo as model_zoo
from utils import BasicBlock, Bottleneck, BBoxTransform, ClipBoxes,calc_iou
from anchors import Anchors
from modules.ClassificationModel import ClassificationModel
from m... | model.py | Apache-2.0 | 12,623 | 3a2742cc77dd2f13cd167897476b4521e577290b | Python | py | |
import os
import time
import torch
import numpy as np
"""[ElegantRL.2021.10.10](https://github.com/AI4Finance-LLC/ElegantRL)"""
class Evaluator: # [ElegantRL.2021.10.13]
def __init__(self, cwd, agent_id, eval_env, eval_gap, eval_times1, eval_times2, target_return, if_overwrite):
self.recorder = list() ... | elegantrl/evaluator.py | Apache-2.0 | 8,432 | 3a27730cb65f1673310e3814e97db6814f5e851c | Python | py | |
import os
import numpy as np
import torch
import pandas as pd
from pathlib import Path
from argparse import ArgumentParser
from svd.eval import evaluate, load_labels
from svd.path_config import dataset_path
def opts_parser():
parser = ArgumentParser(description='Evaluates singing voice predictions against ground ... | svd/collect_eval.py | MIT | 4,265 | 3a27785d97ebda369f49ec9c4f6202d28c16b319 | Python | py | |
# Author: a101269
# Date : 2020/3/9
import torch
import torch.nn as nn
from utils.utils import logger, seed_everything
from model.criterion import criterion
from model.optimizer import get_optimizer
from torch.nn.utils import clip_grad_norm_
from modules.sdp_decoder import sdp_decoder, parse_semgraph
import mo... | model/trainer.py | MIT | 8,537 | 3a277a06e7d15dc1ef60df328abf4b3dccc23aeb | Python | py | |
import torch
import torch.nn as nn
import math
from random import randrange, shuffle
from copy import deepcopy
from .seq2seq_base import Seq2Seq
from seq2seq.tools.config import PAD, EOS
from .modules.state import State
from .modules.transformer_blocks import EncoderBlock, DecoderBlock, EncoderBlockPreNorm, DecoderBloc... | seq2seq/models/transformer.py | MIT | 15,218 | 5fb8614f2a5454c9727831f8ab0a6e525540c7d4 | Python | py | |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CON... | datasets/base_dataset.py | MIT | 3,802 | 345ab2bc60901d9e332f0578e39a87053a725465 | Python | py | |
from typing import Optional, Tuple, Union
import albumentations as A
import cv2
import numpy as np
import pandas as pd
import torch
from albumentations.pytorch import ToTensorV2
from PIL import Image, ImageFile
try:
import torch_xla.core.xla_model as xm
_xla_available = True
except ImportError:
_xla_avai... | wtfml/data_loaders/image/classification.py | MIT | 4,879 | 7c43eaa24cd41e54744d706da658aa232bf0437f | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import TYPE_CHECKING, Optional, Tuple
import torch
if TYPE_CHECKING:
from ..structures import ... | pytorch3d/ops/points_to_volumes.py | BSD-3-Clause | 20,899 | 3a27ebc0eb06590c74476945f73c3868942df2c0 | Python | py | |
import ClebschGordan
print(ClebschGordan.__file__)
import os
import sys
CUR_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(CUR_DIR, ".."))
sys.path.append(os.path.join(CUR_DIR, "../.."))
import torch
# Create the CG dicionary of matices, and making them Variables for pytorch
class Cle... | CGNet/ClebschGordan/test.py | Unlicense | 1,092 | 24a89734e85683a14aa23fb314d18225147a17e6 | Python | py | |
import warnings
warnings.simplefilter("ignore", UserWarning)
import argparse
import torch
from torch.utils import data
import torch.optim as optim
from tqdm import tqdm
from human_body_prior.tools.model_loader import load_vposer
import open3d as o3d
import smplx
from sklearn.neighbors import NearestNeighbors
import ch... | test_optimize.py | MIT | 23,631 | 42613ae2cee62c8f8f333511804db09fe589b454 | Python | py | |
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
from torch.distributions import constraints
from torch.distributions.transforms import PowerTransform
from pyro.distributions.torch import Gamma, TransformedDistribution
class InverseGamma(TransformedDistribution):
r"""
... | pyro/distributions/inverse_gamma.py | Apache-2.0 | 1,384 | 24dba5fa86e25fe96f263fd935b446e31e84e70d | Python | py | |
#!/usr/bin/env python
"""
Copyright 2018 Jesus Villalba (Johns Hopkins University)
Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""
from __future__ import absolute_import
from __future__ import print_function
import sys
import os
import argparse
import time
import logging
import numpy as np
from six.mo... | egs/sitw_noisy/v1.pyfb/steps_pyfe/pytorch-compute-fbank-feats-enh-fbank-can-small-logsigmask.py | Apache-2.0 | 5,827 | 5e82118277ee1175d556c9f824b898e8bf7539f1 | Python | py | |
import torch
from torch import nn as nn
from learning.inputs.common import empty_float_tensor, cuda_var
from learning.modules.map_transformer_base import MapTransformerBase
from learning.modules.dbg_writer import DebugWriter
from visualization import Presenter
from utils.simple_profiler import SimpleProfiler
PROFILE ... | learning/modules/map_to_map/leaky_integrator_w.py | BSD-2-Clause | 4,589 | 1ea6237c8a89185d5027793e86a0819ab3259293 | Python | py | |
import warnings
import torch
import torch.nn as nn
from torch import Tensor
from torchvision.utils import make_grid
import matplotlib.pyplot as plt
import numpy as np
import Levenshtein
from typing import Optional, List
from sklearn.metrics import ndcg_score, average_precision_score
class NestedTensor(object):
d... | utils.py | MIT | 6,900 | 7c375b8fa2f65f8939a01d7ad715637858b9afc7 | Python | py | |
import numpy as np
import torch
import os
from collections import OrderedDict
from torch.autograd import Variable
import itertools
import util.util as util
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
import sys
class recycleGANv2Model(BaseModel):
def name(self):
... | models/version_compare.py | MIT | 18,489 | e94400356a93d7a4fa134ad7089be38e06022b79 | Python | py | |
from torch.utils.data import Dataset as BaseDataset
import pyra_pytorch
import numpy as np
class Dataset(BaseDataset):
"""CamVid Dataset. Read images, apply augmentation and preprocessing transformations.
Args:
images_dir (str): path to images folder
masks_dir (str): path to segmentation ... | data/dataset.py | MIT | 2,830 | e9af3ad373b9d21676508f72ef35dd3815775a46 | Python | py | |
import random
import numpy as np
import torch
def fix_seed(seed=42):
# https://pytorch.org/docs/stable/notes/randomness.html
# Python
random.seed(seed)
# Numpy
np.random.seed(seed)
# PyTorch
torch.manual_seed(seed)
# TODO Enable full deterministic computation
# https://pytorch... | experiment/seed.py | MIT | 452 | 3a2851667cac99bc9cdc7c59af3948992828a95a | Python | py | |
"""
Once you've organized your PyTorch code into a LightningModule,
the Trainer automates everything else.
.. figure:: /_images/lightning_module/pt_trainer.png
:alt: Convert from PyTorch to Lightning
This abstraction achieves the following:
1. You maintain control over all aspects via PyTorch code without an ... | pytorch_lightning/trainer/__init__.py | Apache-2.0 | 25,660 | 3a2881fe75121125c9889692b646f656e0f8a7b0 | Python | py | |
import time
import torch
from transformer.transformer import Transformer
if __name__ == '__main__':
checkpoint = 'BEST_checkpoint.tar'
print('loading {}...'.format(checkpoint))
start = time.time()
checkpoint = torch.load(checkpoint)
print('elapsed {} sec'.format(time.time() - start))
model = ... | export.py | Apache-2.0 | 766 | 1e3c4517e9275b21821230cf9180df15c6f81a3a | Python | py | |
import numpy as np
import torch.nn as nn
class RealNVPLoss(nn.Module):
"""Get the NLL loss for a RealNVP model.
Args:
k (int or float): Number of discrete values in each input dimension.
E.g., `k` is 256 for natural images.
See Also:
Equation (3) in the RealNVP paper: https:/... | models/real_nvp/real_nvp_loss.py | MIT | 1,101 | 3a28ca5738d19968efba6983bcbee5c936cceb2d | Python | py | |
from torch.utils.tensorboard import SummaryWriter
import os, utils, glob, losses
import sys
from torch.utils.data import DataLoader
from data import datasets, trans
import numpy as np
import torch
from torchvision import transforms
from torch import optim
import torch.nn as nn
import matplotlib.pyplot as plt
... | IXI/Baseline_Transformers/train_PVT.py | MIT | 8,192 | 3a28dc7702fa915acbbe61717d46b2a0aa3a122a | Python | py | |
from torch import nn
import torch
from logger import get_logger, get_tensorboard_logger
from utils import var2num
class MSELoss(nn.Module):
"""MSE loss.
Calculates the l2 norm for the matrix target-input.
"""
def __init__(self, endpoint_name, target_name):
super().__init__()
self.mse_lo... | reid/scripts/triplet_reid/losses/regression.py | MIT | 3,907 | 3a28e2ab2ac45ee544a032313a3814346afa3156 | Python | py | |
import math
import os
import pickle as pkl
import gin
import numpy as np
import scipy.io
import torch
import torch.nn.functional as F
from skimage import io
from torch.utils.data import Dataset
import flowiz as fz
from . import image_utils
from . import transformations
import pandas as pd
import pickle
import glob
imp... | multiframe/data/youtube_mf_of.py | Apache-2.0 | 23,297 | 3a28ee9e71bb131558142650bb541462f68496b4 | Python | py | |
from __future__ import print_function
from matplotlib import pyplot as plt
import numpy as np
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from .self_attention import TransformerLayer, Normalize, gather_nodes, gather_edges
from .protein_features import PositionalEncodings
class Lan... | struct2seq/seq_model.py | MIT | 4,073 | 3a28ffe28114629990bc42012252d6d758113457 | Python | py | |
import torch
#agent parameters
BATCH_SIZE = 128
LEARNING_RATE = 0.001
TAU = 0.001
GAMMA = 0.99
#training parameters
#RAM_ENV_NAME = 'CartPole-v1'
RAM_ENV_NAME = 'LunarLander-v2'
VISUAL_ENV_NAME = 'Pong-v0'
CONSTANT = 90
#Training parameters
RAM_NUM_EPISODE = 1000
VISUAL_NUM_EPISODE = 3000
EPS_INIT = 1
EPS_DECAY = 0.... | dqn/dqn_torch/config.py | MIT | 366 | 52d99cd71b47540c33235cd889ff110025e9630c | Python | py | |
import torch
from torch import nn, optim
from torch.utils import data
import os
import numpy as np
import argparse
from trainer import UncertaintyTrainer
from module.config import checkOutputDirectoryAndCreate, loadConfig, dumpConfig, showConfig
from module.resnet import MyResNet
from tqdm import tqdm
try:
impo... | train_image_flow.py | MIT | 2,338 | 3a29aa20b4c6ecfc103a0d1d0d3dea207d317b10 | Python | py | |
from __future__ import absolute_import, division, print_function
import numpy as np
import pytest
import torch
from pyro.distributions.util import broadcast_shape, scale_tensor, sum_leftmost, sum_rightmost
INF = float('inf')
@pytest.mark.parametrize('shapes', [
([],),
([1],),
([2],),
([], []),
... | tests/distributions/test_util.py | MIT | 3,862 | f94fb97f6e5b1d1e08ceb6ea999da39b6c85bf9d | Python | py | |
import os, sys
sys.path.append(os.getcwd())
import random
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import sklearn.datasets
import tflib as lib
import tflib.plot
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
im... | gan_toy.py | MIT | 9,322 | 3a29cabc7fe4223b198f17c37c8d5eac1c8c10d1 | Python | py | |
import torch
from torch import nn
import os.path
import torchvision.transforms as transforms
from data.base_dataset import BaseDataset, get_transform
from data.image_folder import make_dataset, store_dataset
import random
from PIL import Image
import PIL
from pdb import set_trace as st
def pad_tensor(input):
... | data/unaligned_dataset.py | BSD-3-Clause | 5,463 | 03abf58a2978598e31b0b86f5f686d2ba634aed2 | Python | py | |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: Donny You
## Modified by: RainbowSecret, JingyiXie, LangHuang
## Microsoft Research
## yuyua@microsoft.com
## Copyright (c) 2020
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in the r... | main.py | MIT | 12,657 | 3a29d9fcaedcf379736ca6552d211c22ec14c1ef | Python | py | |
from __future__ import division
import os
import math
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from torch.autograd import Variable
from PIL import Image, ImageDraw, ImageFont
from torchvision.ops import nms
class DecodeBox(nn.Modu... | utils/utils.py | MIT | 12,618 | 3a29de405d12dc3c662816a168c8b2129b38d19f | Python | py | |
import logging
import time
from pathlib import Path
import hydra
import onnxruntime.quantization as ort_quant
import torch
from omegaconf import DictConfig
from src.models import SSTModel
from src.utils import utils
logging.basicConfig()
log = utils.get_logger(__name__)
log.setLevel(logging.INFO)
def convert_to_on... | src/convert.py | Unlicense,MIT | 1,867 | 4b4e933cfcf2da161280e8db8ef3487d4bf017b0 | Python | py | |
# Copyright 2020 Adap GmbH. 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 ag... | src/py/flwr_example/pytorch_imagenet/client.py | Apache-2.0 | 7,109 | 3a2a022b6b32891f6bc33256dc0d5cf4251abeff | Python | py | |
from collections import OrderedDict
from typing import Tuple, Union
from fvcore.common.registry import Registry
import copy
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from clip import LayerNorm
from .. import TextualTransformer
TEXT_HEADS_REGISTRY = Registry("TEXT_HEADS")
TE... | cvap/module/encoder/text_head.py | MIT | 4,658 | 3a2a08b222f1be6c15695bf47a60030fd307b5c6 | Python | py | |
from typing import Dict, Optional
import torch
from allennlp.common import Params
from allennlp.common.checks import check_dimensions_match
from allennlp.data import Vocabulary
from allennlp.models.model import Model
from allennlp.modules import FeedForward, MatrixAttention
from allennlp.modules import Seq2SeqEncoder... | allennlp/models/decomposable_attention.py | Apache-2.0 | 11,023 | 3a2a194313109e2770242d190876ad4e0bf52b2b | Python | py | |
import torch.nn as nn
class DepthwiseSeparableConv(nn.Module):
def __init__(self, in_channels, out_channels, stride=1, dilation=1):
super(DepthwiseSeparableConv, self).__init__()
self.depthwise = nn.Conv2d(in_channels, in_channels, 3,
stride=stride, padding=dila... | layers/xception.py | Apache-2.0 | 1,680 | 3a2a339aa74eb138f8ed357a30c95c3e8954bbdb | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
__all__ = ['densenet']
from torch.autograd import Variable
class Bottleneck(nn.Module):
def __init__(self, inplanes, expansion=4, growthRate=12, dropRate=0):
super(Bottleneck, self).__init__()
planes = expansion * gr... | pytorch-classification/models/cifar/densenet.py | Apache-2.0 | 6,478 | d7465c80863764a1a96adc3ae3c31350a4261de4 | Python | py | |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 20:50:10 2021
@author: Lishen Qiu
"""
#!/usr/bin/env python3
import numpy as np
import os
import sys
import wfdb
# from utils import qrs_detect, comp_cosEn, save_dict
# import matplotlib # 注意这个也要import一次
# import matplotlib.pyplot as plt
# from scor... | entry_2021_Q.py | MIT | 6,219 | 03d02304cf3003e6e0356e234c565c9025e7949e | Python | py | |
import torch
from scalenet import Model
class TransparentSeq(Model):
def __init__(self, stages):
super().__init__()
self.stages = torch.nn.ModuleList(stages)
self.inermediate = []
def forward(self, x, start_stage=None, end_stage=None):
self.intermediate = []
if start_st... | artificery/parsers/transparentseq/parse.py | Apache-2.0 | 814 | 3a2a4360e9355cc7d42d1231e0f5153501058442 | Python | py | |
import torch
from . import siml_module
class Contraction(siml_module.SimlModule):
"""Tensor contraction block."""
def __init__(self, block_setting):
super().__init__(block_setting, no_parameter=True)
return
def forward(self, *xs, supports=None, original_shapes=None):
"""Calcula... | siml/networks/tensor_operations.py | Apache-2.0 | 1,321 | 3a2a51dbaf44a453f6558c136822a535dbce133a | Python | py | |
"""The code is adapted from https://github.com/nikhilbarhate99/min-decision-transformer
"""
from typing import List, Dict, Any, Tuple, Union
from collections import namedtuple
from torch.distributions import Normal, Independent
from ding.torch_utils import Adam, to_device
from ditk import logging
from ding.rl_utils im... | ding/policy/decision_transformer.py | Apache-2.0 | 15,677 | 03d07c12ee5671d858b9db51a172d7ea276a3ceb | Python | py | |
from collections.abc import Sequence
import mmcv
import numpy as np
import torch
from mmcv.parallel import DataContainer as DC
from ..registry import PIPELINES
def to_tensor(data):
"""Convert objects of various python types to :obj:`torch.Tensor`.
Supported types are: :class:`numpy.ndarray`, :class:`torch.... | mmdet/datasets/pipelines/formating.py | BSD-2-Clause | 6,381 | fcf778f099d2252e1583e9ae0707200269e129ab | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.