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 pytorch_lightning as pl
import torchmetrics
import torch
from torch import nn
import torch.nn.functional as F
import uvnet.encoders
class _NonLinearClassifier(nn.Module):
def __init__(self, input_dim, num_classes, dropout=0.3):
"""
A 3-layer MLP with linear outputs
Args:
... | uvnet/models.py | MIT | 13,679 | e9c78353b382c6ec345872df78b98c95c9c1791e | Python | py | |
from typing import List
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, Dataset, random_split
class SVHN:
def __init__(self, conf: dict) -> None:
self.conf = conf.dataset
self.model_params = conf.model.params
self.datase... | src/dataset.py | MIT | 1,393 | fde2fef8bdab505c1da60b58116e9cdfefb4737f | Python | py | |
import sys
import os
os.environ[
"CURL_CA_BUNDLE"] = "/etc/ssl/certs/ca-certificates.crt" # A workaround in case this happens: https://github.com/mapbox/rasterio/issues/1289
import time
import datetime
import argparse
import copy
import numpy as np
import pandas as pd
from dataloaders.StreamingDatasets import S... | train.py | Apache-2.0 | 9,866 | e9177832af31320c92f8a84fd5c794d409a2dad6 | Python | py | |
import torch
import torch.utils.data as data
from copy import deepcopy
from .dataset_utils import pil_loader
class MetaDataset(data.Dataset):
def __init__(self, metatask, transform, train):
self.metatask = deepcopy(metatask)
self.length = len(self.metatask)
self.train = train
self.transform = tra... | FPAIT/lib/datasets/metadataset.py | MIT | 1,462 | 3ab7093f97308c40bc4a066ef75b7ecbab629c01 | Python | py | |
import torch
import torch.nn as nn
import traceback
from Caffe import caffe_net
import torch.nn.functional as F
from torch.autograd import Variable
from Caffe import layer_param
from torch.nn.modules.utils import _pair
import numpy as np
"""
How to support a new layer type:
layer_name=log.add_layer(layer_type_name)
... | pytorch_to_caffe.py | MIT | 29,780 | 3ab7154d2b613f687bad7920877b7f91e5ec65dd | Python | py | |
from pathlib import Path
import torch
import torch.nn.functional as F
from torch.nn import Embedding, Linear, ModuleList, ReLU, Sequential
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch_geometric.datasets import ZINC
from torch_geometric.loader import DataLoader
from torch_geometric.nn import Batch... | examples/pna.py | MIT | 3,759 | 3ab716e9cc2718500ad8d92a42f9671732bf38ad | Python | py | |
from collections import OrderedDict
import einops
import torch
from torch import Tensor
from torch.nn import (
CrossEntropyLoss,
GRU,
Module,
Linear,
Sequential,
Tanh,
)
from torch.optim import Adam
from torch.optim.optimizer import Optimizer
from torchaudio.transforms import MelSpectrogram
c... | kespo/models/attention_spotter.py | MIT | 4,445 | 423a47c2b5c389098b4ba71df34f1bbea831ca2a | Python | py | |
import torch
import csv
import os
from tqdm import tqdm
from torch.utils.data import DataLoader
from transformers import BertTokenizer, BertModel
from core.data.dataset import Task71Dataset
from core.data.collators import Task71aCollatorTest
from core.models.modules.heads import BertClassificationHead
from core.utils.... | experiments/task71/test_bert.py | MIT | 2,504 | 3ab71ef55a2f28f7eaf60f2042d61690108eea00 | Python | py | |
import os
import time
import random
import pdb
import numpy as np
from torch.utils.tensorboard import SummaryWriter
from . import util
try:
from StringIO import StringIO # Python 2.7
except ImportError:
from io import BytesIO # Python 3.x
import matplotlib as mpl
import matplotlib.cm as cm
import matplotl... | util/visualizer.py | MIT | 5,808 | e90ef7e1e82d0ba3ef9518f46da5da1570b164cd | Python | py | |
from abc import ABC
from abc import abstractmethod
from typing import Optional
from typing import Tuple
import torch
class AbsExtractor(torch.nn.Module, ABC):
@abstractmethod
def output_size(self) -> int:
raise NotImplementedError
@abstractmethod
def forward(
self,
speech: to... | espnet2/sid/extractor/abs_extractor.py | Apache-2.0 | 638 | 03bc0bc7b299e182a5070250fc31e606741c3424 | Python | py | |
# Copyright 2020 MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, s... | tests/utils.py | Apache-2.0 | 17,832 | 3ab73a4fcdb30aebf3bfd140def2691f75d00c9a | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from SSD_pytorch.models import *
from SSD_pytorch.utils.config import opt
import os
class SSD(nn.Module):
"""Single Shot Multibox Architecture
The network is composed of a base VGG network followed by the
... | SSD_pytorch/models/ssd.py | MIT | 11,649 | 3ab7557e077fce73c67afe0e5a17a252b765889a | Python | py | |
'''
Description:
Version:
Author: Leidi
Date: 2021-04-30 11:03:41
LastEditors: Leidi
LastEditTime: 2021-05-11 10:10:23
'''
import sys
sys.path.append('.')
from projects.FastAttr.fastattr import *
from fastreid.utils import comm
from fastreid.data.transforms import build_transforms
from fastreid.data.build import _ro... | projects/FastAttr/detect_demo.py | Apache-2.0 | 5,728 | e9a6c419bde46fc0de8bafe8a2cba86bde281ec0 | Python | py | |
import argparse
import logging
import os
import cv2 as cv
import numpy as np
import torch
from config import MIN_MATCH_COUNT
# Initiate SIFT detector
sift = cv.xfeatures2d.SURF_create()
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)
flann = cv.Flann... | utils.py | MIT | 5,379 | 802c5b1fe0bc378bd983ddc4095f402e6e531426 | Python | py | |
import platform
import random
from functools import partial
import numpy as np
from mmcv.parallel import collate
from mmcv.runner import get_dist_info
from mmcv.utils import build_from_cfg
from torch.utils.data import DataLoader
from .dataset_wrappers import RepeatDataset
from .registry import DATASETS
from .samplers... | mmaction/datasets/builder.py | Apache-2.0 | 3,890 | 3ab799727bc21dd4342b10f1895b89f06fa1e297 | Python | py | |
# summarization.py
"""
Unsupervised summarization model
"""
import pdb
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.nn_utils import move_to_cuda, calc_clf_acc, convert_to_onehot, LabelSmoothing
from project_settings import PAD_ID, EDOC_ID
#defined only one Class here: ... | checkpoints/sum/train/hotel_mask_sing_asp/batch_size_12-notes_4gpu/code_snapshot/models/summarization.py | Apache-2.0 | 19,635 | 3ab7999f34c8d571080ec4e91cfff7ffc7ec6631 | Python | py | |
import numpy as np
import torch
import glob
import matplotlib.pyplot as plt
import sigpy as sp
from scipy import ndimage
from tqdm import tqdm
import os
"""
The aim of this notebook is to generate motion corrupt images from the single coil ground truth data created by the fastmri_convertor.py
"""
def motion_corrupt(... | data_preprocessing/motion_gen.py | MIT | 3,161 | 3ab79a7646c3658c4a11c1b49b5662f6369ed339 | Python | py | |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : WTM.py
@Time : 2020/10/06 17:13:43
@Author : Leilan Zhang
@Version : 1.0
@Contact : zhangleilan@gmail.com
@Desc : None
'''
import os
import re
import time
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
... | models/WTM.py | Apache-2.0 | 8,211 | 3ab79bd1f81127df4a178865250902d216261d3f | Python | py | |
import torch
from torch import nn
from catalyst.utils import outer_init
class TemporalLastPooling(nn.Module):
def forward(self, x: torch.Tensor, mask: torch.Tensor = None):
x_out = x[:, -1:, :]
return x_out
class TemporalAvgPooling(nn.Module):
def forward(self, x: torch.Tensor, mask: torch.... | catalyst/contrib/nn/modules/lama.py | Apache-2.0 | 4,967 | 3ab7a8317d8b7acd42bfa1032449dd2ccf8a643e | Python | py | |
# -*- coding: utf-8 -*-
import os
import shutil
import ipdb
import numpy as np
import string
from collections import Counter
import pandas as pd
from tqdm import tqdm
import random
import time
from functools import wraps
import collections
import sklearn
import utils
# from utils import log_time_delta
from tqdm import... | BMD_text/dataHelper.py | MIT | 14,235 | 3ab7af11b20c01bd65527dd2d560baef3ced4353 | Python | py | |
import os.path as op
import re
import torch
from glob import glob
from torch.nn import ConstantPad3d
from torch.utils.data import Dataset
def pad_to_multiple_of_16(img):
# required_padding = [16 - dim % 16 for dim in img.shape]
return ConstantPad3d(padding=(0, 0, 4, 3, 0, 0), value=0)(img)
def min_max_scal... | dataset.py | MIT | 10,390 | b29a4e9755c65e7dbee1f83c49ca3a382ea052b5 | Python | py | |
import torch
import torch.nn as nn
from .mol_tree import Vocab, MolTree, MolTreeNode
from .nnutils import create_var, GRU
from .chemutils import enum_assemble
import copy
MAX_NB = 8
MAX_DECODE_LEN = 100
class JTNNDecoder(nn.Module):
def __init__(self, vocab, hidden_size, latent_size, embedding=None):
sup... | jtnn/jtnn_dec.py | MIT | 12,432 | cc2b2fa6f700a317ef13c4b335081de4c58e22af | Python | py | |
import argparse
import os, sys
import os.path as osp
import torchvision
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import transforms
import network, loss
from torch.utils.data import DataLoader
import random, pdb, math, copy
from tqdm import tqdm
from scipy.spatia... | digit/uda_digit.py | MIT | 18,976 | 7cdf08b5a27c74b03f8c68575088937159be4e82 | Python | py | |
import torch
from torch import nn
from layers import *
config = {}
config['anchors'] = [ 10.0, 25.0, 40.0]
config['chanel'] = 2
config['crop_size'] = [64, 128, 128]
config['stride'] = [2,4,4]
config['max_stride'] = 16
config['num_neg'] = 10
config['th_neg'] = 0.2
config['th_pos'] = 0.5
config['num_hard'] = 1
config['b... | detector/res_pool.py | Apache-2.0 | 3,996 | 42001d695e2d0123a369da9e0738f80c34366a4e | Python | py | |
import torch
import os
from datetime import datetime
import numpy as np
from mpi4py import MPI
from models import open_loop_image_predictor
from utils import sync_networks, sync_grads
from open_loop_buffer import open_loop_buffer
from normalizer import normalizer
"""
ddpg with HER (MPI-version)
"""
class open_loop_ag... | open_loop_agent.py | MIT | 8,677 | e9befdec2763b88342abe396974d6210c01cdb5b | Python | py | |
"""Wrapper of AllenNLP model. Fixes errors based on model predictions"""
import logging
import os
import sys
from time import time
import torch
from allennlp.data.dataset import Batch
from allennlp.data.fields import TextField
from allennlp.data.instance import Instance
from allennlp.data.tokenizers import Token
from ... | gector/gec_model.py | Apache-2.0 | 12,138 | 7cc636b2bfa54e383a63421cec1d17b105fd9c56 | Python | py | |
import sys,time
import numpy as np
import torch
import utils
class Appr(object):
def __init__(self,model,nepochs=100,sbatch=64,lr=0.05,lr_min=1e-4,lr_factor=3,lr_patience=5,clipgrad=10000,args=None):
self.model=model
self.nepochs=nepochs
self.sbatch=sbatch
self.lr=lr
self... | src/approaches/progressive.py | MIT | 4,266 | 7cb4f7bc8cd4fb42cf2080c3f0a407aec245686d | Python | py | |
# Copyright (c) Alibaba Inc. All rights reserved.
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
import torch
from tqdm import tqdm_notebook as tqdm
#matplotlib inline
use_cuda = torch.cuda.is_available()
device = torch.device('cuda:0' if use_cuda else 'cpu')
# Add new methods here.
... | evaluate_mpn.py | MIT | 12,305 | 3ab824165e706b3dc4bf086a0051c75cedc24405 | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Video models."""
import torch
import torch.nn as nn
import slowfast.utils.weight_init_helper as init_helper
from slowfast.models.batchnorm_helper import get_norm
from . import head_helper, resnet_helper, stem_helper
fr... | slowfast/models/video_model_builder.py | Apache-2.0 | 22,377 | 70706df34f5f89c9ab7c526d2bd330670a6d0549 | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import os
import functools
from torch.autograd import Variable
try:
from util.image_pool import ImagePool
except ImportError:
from ..util.image_pool imp... | Global/models/NonLocal_feature_mapping_model.py | MIT | 6,487 | 3ab862fb4df9df4eafad51a99a988fc220815b47 | Python | py | |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import torchvision.models as models
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
import types
import re
#################################################################
# You can find the definitions ... | pretrainedmodels/models/torchvision_models.py | BSD-3-Clause | 20,596 | f93471619adbe8d833f3d42e8ea60cf24c7d3339 | Python | py | |
""" A background process that averages your tensors with peers """
from __future__ import annotations
import asyncio
import contextlib
import ctypes
import multiprocessing as mp
import os
import random
import threading
import weakref
from dataclasses import asdict
from typing import Any, AsyncIterator, Dict, Optional... | hivemind/averaging/averager.py | MIT | 39,419 | 28dd8aaca86ea9988b82144d7406397dfae26441 | Python | py | |
from collections import OrderedDict
import torch.nn as nn
model = nn.Sequential(OrderedDict([
('conv1', nn.Conv2d(1, 20, 5)),
('relu1', nn.ReLU()),
('conv2', nn.Conv2d(20, 64, 5)),
('relu2', nn.ReLU())
]))
print(model)
# Sequential (
# (conv1): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
# ... | ml/pytorch/model_printing_and_saving.py | Unlicense | 649 | 29f8fb45322fbd2f42734f21f558c48870a0b9b4 | Python | py | |
"""
Unit tests for XLNet classifiers.
"""
import unittest
import torch
from texar.torch.modules.classifiers.xlnet_classifier import *
from texar.torch.utils.test import pretrained_test
class XLNetClassifierTest(unittest.TestCase):
r"""Tests :class:`~texar.torch.modules.XLNetClassifier` class.
"""
def ... | texar/torch/modules/classifiers/xlnet_classifier_test.py | Apache-2.0 | 5,720 | 5fa33bef2b707674aad7f44d5467bbce5ef92128 | Python | py | |
# coding:utf-8
import os
import pickle
import torch
import random
import warnings
import numpy as np
import pandas as pd
from tqdm import tqdm
from typing import Dict
from collections import defaultdict
from torch.utils.data import Dataset
from transformers import (
BertTokenizer,
DataCollatorForLanguageMode... | pretrain_code/run_pretrain_bert.py | Unlicense | 6,975 | 45edb9a4e023a0d0ad53f43666b6dce11a305dcf | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
import numpy as np
from collections import deque, namedtuple
import os
import torch
import torch.nn.functional as F
import torch.optim as optim
import math
from itertools import count
import gc
from curious_agent.agents import Agent
from curious_agent.models.... | curious_agent/agents/open_ai_agents/sparse_dqn_agent.py | MIT | 12,809 | 3ab8bb931fa6ee8d55fa83798e225ff6bd0298f3 | Python | py | |
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import sys
import torch
import torchvision
import torch.nn as nn
from torch.autograd import Variable
import time
import yaml
import argparse
import numpy as np
from printer import Printer
from dataset import get_data_loader, get_inference_data_loader
from model import... | dvs/load_frame_sensor_data.py | Apache-2.0 | 5,356 | 1287469654b9021f3078d35f4b9427c48179ee11 | Python | py | |
import json
import os
import torch.utils.data as data
class TextLineByLineDataset(data.Dataset):
def __init__(self, fn):
super(TextLineByLineDataset, self).__init__()
with open(fn, 'r') as f:
self.data = f.read().strip().split('\n')
def __getitem__(self, index):
return sel... | src/dataload/datasets.py | Apache-2.0 | 2,392 | e92fc09d4453075ba43ffc25f1ed76049bc19bb0 | Python | py | |
from typing import Optional, Sequence, Tuple
import logging
import numpy as np
import torch
from torch import Tensor
from torch.nn import functional as F
logger = logging.getLogger(__name__)
def process_multiclass_components(
outputs: torch.Tensor,
targets: torch.Tensor,
argmax_dim: int = -1,
num_c... | catalyst/metrics/functional/_misc.py | Apache-2.0 | 13,633 | 5e76eb081e9fd49662f725c24ce8ad503e40a550 | Python | py | |
import os
import sys
import argparse
import ast
import cv2
import time
import torch
from vidgear.gears import CamGear
import numpy as np
sys.path.insert(1, os.getcwd())
from SimpleHigherHRNet import SimpleHigherHRNet
from misc.visualization import draw_points, draw_skeleton, draw_points_and_skeleton, joints_dict, chec... | model_zoo/higher_hrnet/scripts/live-demo.py | MIT | 7,529 | 45e70c62008a6197a80edf6c3566fd01a43d9f9b | Python | py | |
import torch
import superp
import math
############################################
# set default data type to double
############################################
torch.set_default_dtype(torch.float64)
torch.set_default_tensor_type(torch.DoubleTensor)
# torch.set_default_dtype(torch.float32)
# torch.set_default_tensor... | verify/duffing-done/prob.py | BSD-3-Clause | 3,054 | fcc98a72e123f9e5fe6c1c77d542cec92ed2683a | Python | py | |
r"""Importing this file includes common utility methods and base clases for
checking quantization api and properties of resulting modules.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.quantized as nnq
import torch.nn.quantized.dynamic as nnqd
from torch.nn.intrinsic import _Fu... | torch/testing/_internal/common_quantization.py | Intel | 75,429 | 2470b5392de11f17f6af1bcc075a0d1f80033976 | Python | py | |
import numpy as np
import torch
import argparse
from torch import Tensor
from torch import autograd
from torch.autograd import Variable
import sys
print(sys.executable)
print(torch.cuda.is_available())
# import airsim
# client = airsim.MultirotorClient()
# client.confirmConnection()
# client.enableApiControl(True, "Dr... | beta.py | MIT | 1,360 | 7c25f480a7e4db2b9fea4c8ef910e2b139377c72 | 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 torch
import torch.nn as nn
import torch.nn.functional as F
try:
from apex.normalization import FusedLayerNorm as _Fus... | edgelm/fairseq/modules/layer_norm.py | MIT | 1,550 | fcbe8688c3b7f8d2fae54a1526c5c23fb4f3e337 | Python | py | |
""" Code generation for PyTorch C++ dispatched operators. """
import copy
import dataclasses
import itertools
import logging
import operator
import os
from typing import List, Tuple, Callable, Optional, Dict, Union
import dace.library
import numpy as np
import torch
from dace import dtypes as dt, data
from dace.codege... | daceml/pytorch/module_codegen.py | BSD-3-Clause | 22,817 | 24d4eb4ee964be5b2b35555ef2b0497947967b5c | 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/plugins/training_type/tpu_spawn.py | Apache-2.0 | 15,365 | 3ab9a8171aac5b1fcb3009991a2cac071113c5e3 | Python | py | |
import torch
from torch.optim.optimizer import Optimizer
from .types import Betas2, OptFloat, OptLossClosure, Params
__all__ = ('NovoGrad',)
class NovoGrad(Optimizer):
r"""Implements Novograd optimization algorithm.
It has been proposed in `Stochastic Gradient Methods with Layer-wise
Adaptive Moments f... | torch_optimizer/novograd.py | Apache-2.0 | 5,682 | 7c1665bf55f0fe1c9a1262361076c15e61404413 | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: source/module/memory_helper.py
"""
import torch
import torch.nn as nn
class AttrProxy(object):
"""
Translates index lookups into attribute lookups.
To implement some trick which able to use list of nn.Module in a nn.Module
see http... | source/module/memory_helper_v3.py | MIT | 7,135 | e9d20049201efa7f760adc3bbac12f18cf954f57 | Python | py | |
from typing import Optional
import numpy as np
import torch
# ========================================================================= #
# Params #
# ========================================================================= #
def count_params(mode... | mtg_ml/util/pt/_util.py | MIT | 1,376 | 7c628930cd064a6680cdd08b06aa5f1bd74a2801 | Python | py | |
import torch
class TextTransform(torch.nn.Module):
def __init__(self, tokenizer, vocab, conf):
super(TextTransform, self).__init__()
self.tokenizer = tokenizer
self.vocab = vocab
self.SOS_IDX = conf["special_tokens"][conf["sos_token"]]
self.EOS_IDX = conf["special_tokens"]... | transform.py | Apache-2.0 | 616 | 4bc1c9d5cbdba602482416d0bf0a1465cbbf5910 | Python | py | |
from __future__ import print_function
from constant import *
from models import *
from dataset import *
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from pytorch_pretrained_bert.optimization import BertAdam
from sklearn.metrics import f1_sco... | NGS-DMBERT/trigger_bert.py | MIT | 5,541 | e93ed45ae407a71106937097c6de1183cf7470c8 | Python | py | |
import torch
from torch import nn
import torch.nn.functional as F
from tool.torch_utils import *
from tool.yolo_layer import YoloLayer
class Mish(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
x = x * (torch.tanh(torch.nn.functional.softplus(x)))
return... | models.py | Apache-2.0 | 17,061 | 458991587b2215a4415ef54d38faaf5ce743ecf5 | Python | py | |
import torch
from torch import nn
import torch.nn.functional as F
from torch.optim import Adam
from .ppo import PPO
from gail_airl_ppo.network import GAILDiscrim
class GAIL(PPO):
def __init__(
self,
buffer_exp,
state_shape,
action_shape,
device,
seed,
gamma... | gail_airl_ppo/algo/gail.py | MIT | 3,526 | 3aba882b0234314d457058996dbfac3a595f18e8 | Python | py | |
from .base_test_class import DartsBaseTestClass
from ..utils import timeseries_generation as tg
from ..metrics import mae
from ..logging import get_logger
logger = get_logger(__name__)
try:
import torch
from ..models.tcn_model import TCNModel
TORCH_AVAILABLE = True
except ImportError:
logger.warning('... | darts/tests/test_TCN.py | Apache-2.0 | 6,781 | 7c8b7ecc29183ff8a0d5823ceda3c0e891e72f9c | Python | py | |
import torch
import kornia as K
# expose functions to torch.jit
# TODO: find an automatic way to do this
grayscale_to_rgb = torch.jit.script(K.color.grayscale_to_rgb)
rgb_to_grayscale = torch.jit.script(K.color.rgb_to_grayscale)
bgr_to_grayscale = torch.jit.script(K.color.bgr_to_grayscale)
spatial_soft_argmax2d = to... | kornia/jit/__init__.py | ECL-2.0,Apache-2.0 | 658 | 52e992732319620d259103529433f58928f21f24 | Python | py | |
''' copy from princeton-vl/pytorch_stacked_hourglass '''
from torch import nn
Pool = nn.MaxPool2d
def batchnorm(x):
return nn.BatchNorm2d(x.size()[1])(x)
class Conv(nn.Module):
def __init__(self, inp_dim, out_dim, kernel_size=3, stride = 1, bn = False, relu = True):
super(Conv, self).__init__()
... | im2mesh/onet_depth/models/hourglass.py | MIT | 2,790 | 3abaa8e0490881afd8aaae1938ddff233a9dc3f0 | Python | py | |
# -*- coding: utf-8 -*-
"""
# @file name : model_trainer.py
# @author : JLChen
# @date : 2020-02-29
# @brief : 模型训练类
"""
import torch
import numpy as np
from collections import Counter
from tools.evalution_segmentaion import eval_semantic_segmentation
from torch.nn.utils import clip_grad_value_
class ... | Segmentation/tools/model_trainer.py | MIT | 3,895 | 3abab508919dbd837eff3d0fee323bf7c5b18bd5 | Python | py | |
import os
import sys
import random
from distutils.dir_util import copy_tree
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from models.fc_drn_model import DenseResNet
from utils import parser
from utils.logging import create_log, write_to_log, print_metrics
from utils.script... | run.py | MIT | 12,737 | 3ababce232f13481e1a52962cf8b0529f034217e | Python | py | |
from .unet import unet128, unet256, residual_unet128, residual_unet256
from .resnet import resnet
from .discriminator import patch_discriminator8
from ..utils import ImagePool
from torch import nn, optim
import torch
import itertools
def requires_grad(m, requires_grad=True):
for p in m.parameters():
p.r... | vision/nets/cycle_gan.py | BSD-3-Clause | 5,895 | 29f2f5eac9a5e5d57fd89918215d74ddc6198851 | Python | py | |
from typing import Dict
import torch
from torch import nn, Tensor
from .functional import bfgs_inv, lbfgs
from .. import properties as p
from .utils import set_hessian, dot, set_directional_hessian
class ExactBFGS(nn.Module):
def forward(self, mol: Dict[str, Tensor]):
mol = mol.copy()
if p.gen_hes... | torchfes/opt/bfgs.py | MIT | 5,111 | 3abaf83b58c96d4fa0d6907e62bbf89edd45ca93 | Python | py | |
from __future__ import print_function
import sys
if '/opt/ros/kinetic/lib/python2.7/dist-packages' in sys.path:
sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
import argparse
import os
os.environ['CUDA_VISIBLE_DEVICES']="0" # choose GPU
import torch
import cv2
import numpy as np
from utils import c... | codes/Test_AutoRefocus.py | MIT | 3,073 | 70015d815fa3d076ea46618d80562554ac9edc38 | Python | py | |
# http://stillbreeze.github.io/REINFORCE-vs-Reparameterization-trick/
import torch
from torch import distributions
idx = 1
for dist_str in dir(distributions):
if dist_str[0].isupper() and "Transform" not in dist_str and dist_str not in ["Distribution", "ExponentialFamily", "Independent", "MixtureSameFamily"]:
... | temp/torch_dist.py | MIT | 5,730 | 5e99002c72d4115c17d0871e639998cddc87e50a | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
class EmbeddingNet(nn.Module):
def __init__(self, ni=128, no=64):
super(EmbeddingNet, self).__init__()
self.convnet = nn.Sequential(nn.Conv3d(ni, 128, 2, padding=2), nn.PReLU(),
nn.MaxPool3d(2, stride=1),
... | models/embedding_learner.py | MIT | 1,183 | 652be6236409ee2b94f2985fd016d216879f52da | Python | py | |
import logging
import random
import numpy as np
import torch
import torchaudio
from torch import Tensor
from torch.utils.data import Dataset
from hw_asr.base.base_text_encoder import BaseTextEncoder
from hw_asr.utils.parse_config import ConfigParser
logger = logging.getLogger(__name__)
import string
class BaseData... | hw_asr/base/base_dataset.py | MIT | 5,193 | 3abb265e84d0d1792e92b2476f4e41a337eff6cd | Python | py | |
# Copyright (c) 2020, Soohwan Kim. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | tacotron2/modules.py | Apache-2.0 | 2,399 | f97593838a5eba298cea8a82331e220ebc06bcbb | Python | py | |
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
from abc import ABC, abstractmethod
import torch
import torch.nn
class ConditionalDistribution(ABC):
@abstractmethod
def condition(self, context):
""":rtype: torch.distributions.Distribution"""
raise NotI... | pyro/distributions/conditional.py | Apache-2.0 | 2,287 | 52d48effe62deeaa9d9d1cbc18dff5308bc0614d | Python | py | |
import os
import torch.nn as nn
from mmcv.cnn import constant_init, kaiming_init
from collections import OrderedDict
# from mmdet.models.utils import build_norm_layer
from mmcv.cnn import ConvModule,build_norm_layer
# from mmdet.models.registry import BACKBONES
from ..builder import BACKBONES
def common_conv2d(inplan... | mmdet/models/backbones/darknet_ttf.py | Apache-2.0 | 5,068 | 5e6df4b02a90e594b12ff67e389a8962e27c7d27 | Python | py | |
from __future__ import division
import time
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
import cv2
from util import *
from darknet import Darknet
from preprocess import prep_image, inp_to_image
import pandas as pd
import random
import argparse
import pickle as pkl
import r... | YOLO/.history/pytorch-yolo-v3/video_demo_v1_20201106013403.py | MIT | 15,661 | 3abb49a2034545471a7094683aaba67125addda2 | Python | py | |
import warnings
from typing import Any
import torch
import torch.nn as nn
from torch import Tensor
from torch.nn import functional as F
from torchvision.models.googlenet import GoogLeNetOutputs, BasicConv2d, Inception, InceptionAux, GoogLeNet, model_urls
from ..._internally_replaced_utils import load_state_dict_from_... | torchvision/models/quantization/googlenet.py | BSD-3-Clause | 6,004 | ff2352daa35760d94a41b0cfb6296d9fdc833a2b | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
from models.backbone import Backbone, Joiner
from models.detr import DETR, PostProcess
from models.position_encoding import PositionEmbeddingSine
from models.segmentation import DETRsegm, PostProcessPanoptic
from models.transformer imp... | hubconf.py | Apache-2.0 | 6,292 | 5e977cd3f74a813e014c44336b76e12d40790778 | Python | py | |
import torch
import nn
from utils import parameter_table
# Base class for different convolutions
class Compare(torch.nn.Module):
def __init__(self):
super(Compare, self).__init__()
@property
def count_parameters(self):
return sum(p.numel() for p in self.parameters() if p.requires_grad)
... | models/compare.py | MIT | 4,661 | 3abb90ea0a4e5064785128a5e1031b49d5d11b53 | Python | py | |
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from math import exp
def gaussian(window_size, sigma):
gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)])
return gauss/gauss.sum()
def create_window(window_size,... | models/SelectionGAN/person_transfer/losses/ssim.py | MIT | 2,680 | 10e6832169bf3a36090c56bc04d42e914e10ca07 | Python | py | |
#!/usr/bin/env python3
from __future__ import print_function
import unittest
from typing import Any, Tuple, Union
import torch
from captum._utils.typing import TensorOrTupleOfTensorsGeneric
from captum.attr._core.guided_backprop_deconvnet import Deconvolution
from captum.attr._core.neuron.neuron_guided_backprop_deco... | tests/attr/test_deconvolution.py | BSD-3-Clause | 5,028 | 340ca7105ce79b62cfb1694345930bb22e1705d0 | Python | py | |
import torch
from .layers import FactorizationMachine, FeaturesEmbedding, MultiLayerPerceptron, FeaturesLinear
class NeuralFactorizationMachineModel(torch.nn.Module):
"""
A pytorch implementation of Neural Factorization Machine.
Reference:
X He and TS Chua, Neural Factorization Machines for Spar... | automlkiller/models/recommendation/nfm.py | Apache-2.0 | 1,090 | 34150fc2cf02ce6c9e27177fc21abd959b2d65f8 | Python | py | |
# Tencent is pleased to support the open source community by making ncnn available.
#
# Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the... | tools/pnnx/tests/ncnn/test_nn_AlphaDropout.py | BSD-3-Clause | 2,001 | 03ff78bfff893d54463ed61fb0ad0ded1c4c74e3 | Python | py | |
import torch
import torch.nn as nn
from onmt.utils.misc import aeq
from onmt.utils.loss import CommonLossCompute
def collapse_copy_scores(scores, batch, tgt_vocab, src_vocabs=None,
batch_dim=1, batch_offset=None):
"""
Given scores from an expanded dictionary
corresponeding to a b... | onmt/modules/copy_generator.py | MIT | 10,660 | 7035f78bc8ca73cf9d9e5bc10446079ece2c2b9c | Python | py | |
import math
from unittest.mock import MagicMock
import pytest
import torch
from ignite.contrib.handlers.base_logger import BaseLogger, BaseOptimizerParamsHandler, BaseOutputHandler
from ignite.engine import Engine, Events, State
from tests.ignite.contrib.handlers import MockFP16DeepSpeedZeroOptimizer
class DummyOut... | tests/ignite/contrib/handlers/test_base_logger.py | BSD-3-Clause | 7,276 | 3abc162f693b5b94ff7ce780d090d4b9d5a58f31 | Python | py | |
import numpy as np
from PIL import Image
from tqdm import tqdm
import torch
from torch import nn, optim
from torch.autograd import Variable, grad
from torchvision import utils
from model import Generator, Discriminator
from datetime import datetime
import random
import copy
import os
import config
import utils
imp... | pioneer/src/train.py | MIT | 25,653 | 4ba441bdd0e1d023e19a19864acc0bb7403c5c94 | Python | py | |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# Modified by Dequan Wang and Xingyi Zhou
# ------------------------------------------------------------------------------
from __f... | src/lib/models/networks/resnet_fpn_dcn.py | MIT | 10,879 | 248c50be2863d17c4277bf9642ec5bac36294d3d | Python | py | |
from __future__ import division, print_function
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from sklearn.manifold import TSNE
import matplotlib
matplotlib.use('agg')
import seaborn as sns
from matplotlib import pyplot as plt
from scipy.o... | utils/fair_evals.py | MIT | 8,078 | 3abc52d42e2b953751586b6eb5fcdfa694dbe880 | Python | py | |
# coding: utf-8
"""
Training module
"""
import argparse
import time
import shutil
from typing import List
import os
from os.path import join
import queue
from functools import partial
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
from torch.utils.tensorboard import SummaryWriter
fr... | joeynmt/training.py | MIT | 27,061 | 3abc5431f14f2f10159fb95f65d084ba4720ced6 | Python | py | |
from typing import List
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from dglt.data.dataset.molecular import MoleculeDataset
from dglt.data.transformer.collator import MolCollator
from dglt.data.transformer.scaler import StandardScaler
def predict(model: nn.Module,
data: Mo... | dglt/train/prediction/predict.py | MIT | 3,019 | 6b02e76d814e6076e9abc947a271f2db44695834 | Python | py | |
#!/usr/bin/env python3
import torch
import unittest
from gpytorch.kernels import RBFKernel, GridKernel, GridInterpolationKernel
from gpytorch.lazy import KroneckerProductLazyTensor
cv = GridInterpolationKernel(RBFKernel(), grid_size=10, grid_bounds=[(0, 1), (0, 2)])
grid = cv.grid
grid_size = grid.size(-2)
grid_dim ... | test/kernels/test_grid_kernel.py | MIT | 1,948 | 42a97b62c0bdfc91f69dc49179c738cbdf4d47f7 | Python | py | |
#!/usr/bin/python
# from __future__ import print_function
import math
import copy
import sys
import os
import timeit
import csv
from tqdm import tqdm ## better progressbar
from math import exp
import numpy as np
import torch
from torch.autograd import Variable
import torch.nn.functional as Func
import torch.nn as nn
... | mnist_energy_exploration/output/.bak/model_zoo_bak.py | MIT | 1,914 | 101f413b2331925c478ec3fb95d85b9404ba1770 | Python | py | |
"""
Thought Vector Class
---------------------
"""
import functools
import torch
from textattack.shared import AbstractWordEmbedding, WordEmbedding, utils
from .sentence_encoder import SentenceEncoder
class ThoughtVector(SentenceEncoder):
"""A constraint on the distance between two sentences' thought vectors.... | textattack/constraints/semantics/sentence_encoders/thought_vector.py | MIT | 1,709 | b2715a0cfb638ab4b0c1016a08ddcc7ea26088d0 | Python | py | |
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... | nnunet/training/network_training/BTS_Netv4_4_TrainerV2.py | Apache-2.0 | 22,627 | fd8bd7bc3fc70a1735b351a1d2f682e7e094e5c0 | Python | py | |
# coding: utf-8
# Copyright (C) 2021, [Breezedeus](https://github.com/breezedeus).
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this f... | cnocr/lr_scheduler.py | Apache-2.0 | 7,545 | 10b6286206032aa3e753c5b4d606b9fab6db9f7a | 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/utilities/test_cli.py | Apache-2.0 | 37,765 | 3abd0cafcf9b8bc6bf76bb3fe7ba143cd25160ea | Python | py | |
import torch
import pandas as pd
import numpy as np
from typing import *
__all__ = ['normalization','standardization']
def normalization(x: Any, xmin: Any, xmax: Any) -> Any:
return (x - xmin) / (xmax - xmin)
def standardization(x: Any, mean: float, std: float) -> Any:
return (x - mean) / std
| torchwisdom/core/nn/functional.py | MIT | 313 | 28d9d928d0febca0f4ee2ae77c98b4b8a6aadc2a | Python | py | |
from collections.abc import Mapping
from functools import partial
import torch
import boardom as bd
from .util import (
StateUtils,
_create_state_dict_element,
_check_member_exists,
)
from ..config.common import DEVICE_KEYS
# ELEMENTS:
# self.models
# EVENTS ISSUED:
# None
# EVENTS LISTENED:
# ... | boardom/components/models.py | BSD-2-Clause | 1,312 | 3abd1f47b9a153dad7f314b40161c9fb9c18c743 | Python | py | |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import json
import os
import sys
import time
import warnings
warnings.filterwarnings('ignore')
import torchvision.utils
from torchvision import models
import torchattacks
from torchat... | cifar10_modelbb_defensebb_table1.py | MIT | 15,878 | 4277b0badc6ed89c5de8a8a7f5c2ab1176ff108b | Python | py | |
from abc import ABCMeta, abstractmethod
import mmcv
import numpy as np
import pycocotools.mask as maskUtils
import torch.nn as nn
from mmcv.visualization.image import imshow
from mmdet.core import auto_fp16, get_classes, tensor2imgs
class BaseDetector(nn.Module, metaclass=ABCMeta):
"""Base class for detectors"... | mmdet/models/detectors/base.py | Apache-2.0 | 8,825 | 3abd4cdf0271552d36232a94b2b50e04fcfc6808 | Python | py | |
import os
import torch
import numpy as np
import torchvision.datasets as datasets
import torchvision.transforms as transforms
DATA_BACKEND_CHOICES = ['pytorch']
try:
from nvidia.dali.plugin.pytorch import DALIClassificationIterator
from nvidia.dali.pipeline import Pipeline
import nvidia.dali.ops as ops
... | utils/dataloaders.py | Apache-2.0 | 10,424 | 3abd6121a2045489e599f3d8fb6fcb1e7db9ab8b | Python | py | |
from tools.surrdet.get_scene_flow_v2 import points_to_ann_cord
from IPython.terminal.embed import embed
from mmdet.datasets.builder import PIPELINES
from mmdet.datasets.pipelines import LoadAnnotations, LoadImageFromFile
from typing import Tuple, List, Union
import numpy as np
import torch
import mmcv
@PIPELINES.regis... | plugin/radar-v3/pipelines.py | Apache-2.0 | 9,154 | 706f1c0a59cb6ac3767fb8eb4f48d40ad5a3e1e8 | Python | py | |
import numpy as np
import torch
import random
import sys
import utils
import pdb
'''
Class for running Lloyd iterations for k-means and associated utility functions.
'''
chunk_size = 8192
num_iterations = 60
k = 10
device = utils.device
device_cpu = torch.device('cpu')
class FastKMeans:
def ... | kmeans.py | MIT | 6,368 | 3abd744c254f905903cea1a82df10e50f51b944f | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import json
import os
import unittest
import zipfile
from typing import Dict
from unittest.mock import patch
import reagent
import reagent.workflow.cli as cli
import torch
from click.testing import CliRunner
from reagent.pa... | reagent/test/workflow/test_oss_workflows.py | BSD-3-Clause | 4,214 | 3abd8001c165f4c5056afae22e229ce2c81e7624 | Python | py | |
from typing import *
import torch
from torch import nn
from transformers import PreTrainedModel
from .. import util
class LanguageModel:
def __init__(self, device, model: PreTrainedModel):
self.device = device
self.model = model
self.model.to(device)
@property
def dim(self):
... | soft_prompts/lm/language_model.py | Apache-2.0 | 5,843 | 3abd91192cef7dec41ed72ccdc7475c3a8a137ec | Python | py | |
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional
from torch.nn.parameter import Parameter
class ResnetGenerator(nn.Module):
def __init__(self, input_nc, output_nc, ngf=64, n_blocks=6, img_size=256, args=None):
assert (n_blocks >= 0)
super(ResnetGenerator, self... | networks.py | MIT | 16,350 | 3abdb31b5689245a3e38bde2bcb756f755cddc59 | Python | py | |
import torch
import numpy as np
import cv2 as cv
from data.complex_data_processing.map_elem_split import *
import math
def get_road_edge(cv_img):
cv_img = MapElemSplit.remove_bg(cv_img)
_, cv_img = cv.threshold(cv_img, 0, 255, cv.THRESH_OTSU)
cv_img = cv.GaussianBlur(cv_img, (3, 3), 0)
cv_img = cv.C... | data/complex_data_processing/road_processing.py | BSD-3-Clause | 6,117 | 24bf402bf3839305097678e4ab29a2d67029c7f3 | Python | py | |
import torch
from torch.autograd import Variable
from torchvision import models
import cv2
import sys
import numpy as np
def replace_layers(model, i, indexes, layers):
if i in indexes:
return layers[indexes.index(i)]
return model[i]
def prune_vgg16_conv_layer(model, layer_index, filter_index, use_cud... | prune.py | Unlicense | 5,263 | 3abdcc9c5a45e09ee0487debd8b7aabf4da141cf | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.