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 os
import re
import numpy as np
import torch
from torchtext.data import NestedField, Field, TabularDataset
from torchtext.data.iterator import BucketIterator
from torchtext.vocab import Vectors
from datasets.reuters import clean_string, split_sents
from models.oh_cnn_HAN.least_padding_iterator import Less_padd... | datasets/yelp2014.py | Apache-2.0 | 4,204 | fee095c1ed748e81ac170c5bea7284144228be41 | Python | py | |
import torch
from torch import nn
from reid import models
from reid.trainers import Trainer
from reid.evaluators import extract_features, Evaluator
from reid.dist_metric import DistanceMetric
import numpy as np
from collections import OrderedDict
import os.path as osp
import pickle
import copy, sys
from reid.utils.seri... | reid/bottom_up.py | MIT | 11,672 | fee0a5eddb367706946e97a6e2011b3266553b0a | 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 copy
from collections import OrderedDict
from typing import (
List,
Dict,... | torchrec/distributed/embeddingbag.py | BSD-3-Clause | 29,899 | 52e6d4b3eec1034f4b5ce594b721a552250e2f1b | Python | py | |
from collections.abc import Iterable
import numpy as np
import pytest
import torch
from mmcv.utils.parrots_wrapper import _BatchNorm
from mmedit.models.backbones import (VGG16, DepthwiseIndexBlock,
HolisticIndexBlock, IndexNetEncoder,
ResGCAEnc... | tests/test_encoders.py | Apache-2.0 | 20,997 | e9b62bc4928de10e3a37bf1178808052978fb069 | Python | py | |
from typing import Any, Dict, List, Optional, Tuple, Type, Union
import gym
import numpy as np
import torch as th
from torch.nn import functional as F
from stable_baselines3.common.buffers import ReplayBuffer
from stable_baselines3.common.noise import ActionNoise
from stable_baselines3.common.off_policy_algorithm imp... | stable_baselines3/bear/bear.py | MIT | 17,375 | fee0ea8fe94f82dfedeb7e2d562591a7a2b093f4 | Python | py | |
import torch
from torch import Tensor
import gpytorch
import numpy as np
import matplotlib.pyplot as plt
from botorch.acquisition.analytic import ExpectedImprovement
from botorch.models import SingleTaskGP
from rollout import rollout, rollout_quad
import warnings
import time
import pickle
warnings.filterwarnings("igno... | enbo/util/test_rollout_2d.py | MIT | 3,768 | fee0fd3e1d19ecc8017b881fa3e79d3d48dc900f | Python | py | |
import numpy as np
import torch.nn as nn
from skimage.measure import compare_ssim as SSIM
from util.metrics import PSNR
class DeblurModel(nn.Module):
def __init__(self):
super(DeblurModel, self).__init__()
def get_input(self, data):
amap_s1 = data['amap_s1']
blurred_s1 = data['blurre... | models/models.py | BSD-3-Clause | 1,866 | fee104d591e06e44861f2e0f2f365384be0dd61b | Python | py | |
import torch as th
import numpy as np
from types import SimpleNamespace as SN
class EpisodeBatch:
def __init__(self,
scheme,
groups,
batch_size,
max_seq_length,
data=None,
preprocess=None,
... | src/components/episode_buffer.py | Apache-2.0 | 11,209 | 4ba5887d6a88ad1c8d55686a6fdf59a46ae44347 | Python | py | |
from dataclasses import dataclass, fields
from datetime import timedelta
from enum import Enum
from operator import attrgetter
from typing import Any, Dict, Optional
import numpy as np
import torch
from torch import nn
from spread_classification.utils import get_datetime
from .nlp import get_tweet_content, get_user_b... | preprocessing/src/features.py | MIT | 4,347 | fd93289d70923909716b28cea3d7888e67381d79 | Python | py | |
import torch
import numpy as np
from .exp import VaeSmExperiment
import scanpy as sc
import pandas as pd
def define_exp(
x_fname, s_fname,
model_params = {
'x_dim': 100,
'z_dim': 10,
'enc_z_h_dim': 50, 'enc_d_h_dim': 50, 'dec_z_h_dim': 50,
'num_enc_z_lay... | src/deepcolor/commons.py | MIT | 6,682 | e60933095faf840520615581c860df9b3fa0d7fd | Python | py | |
from functools import partial
import os
import torch
from lbfgs import LBFGS
from model import RouteChoice, RouteChoiceEM, RouteChoiceMaxEnt
from data import DataLoader, DataLoaderEM, DataLoaderMaxEnt
from utils import generate_data, get_log_path, load_data
from pprint import pprint
from torch.utils.tensorboard import ... | trainer.py | MIT | 7,514 | d757d71b549d660a95aacf9fcc81f32b4245cc89 | Python | py | |
import logging
import os
import random
import shutil
import torch
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
def assert_params_exist(p, keys):
for k in keys:
if not k in p.__dict__.keys():
raise AttributeError("Necessary parameter {} is missing!"... | utils/lib.py | MIT | 7,605 | 6b000fb764fb118e3d45fab258638a03f6f4577f | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
class QNetwork(nn.Module):
'''
Actor (Policy) Model
'''
def __init__(self, state_size, action_size, seed, fc1_units=64, fc2_units=64):
super().__init__()
self.seed = torch.manual_seed(seed)
... | p1_navigation/agents/qnetwork.py | MIT | 650 | fee19272feb6a70ff334a16c0c283c0cd1b35d5c | Python | py | |
import os
import sys
BASE_DIR = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.dirname(
os.path.abspath(__file__)))))
sys.path.append(BASE_DIR)
from tools.path import ILSVRC2012_path
from simpleAICV.distillation.distillmodel import KDModel
from simpleAICV.distillation import losses
from simpleA... | distillation_training/imagenet/resnet_152_dkd_50/train_config.py | MIT | 3,520 | 5fb094c3039c5c5dfbdb3d5e8687302f9d725808 | Python | py | |
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from sqlnet.model.modules.word_embedding import WordEmbedding
from sqlnet.model.modules.aggregator_predict import AggPredictor
from sqlnet.model.modules.selection_predict import SelPredi... | sqlnet/model/seq2sql.py | BSD-3-Clause | 15,587 | 4281a78e18b12e032de18ecadee7c4fbdc6d2a34 | Python | py | |
from __future__ import print_function
import torch
import torch.nn as nn
from torch.nn.modules import transformer
from torch.nn.modules.activation import ReLU
import torch.nn.parallel
import torch.utils.data
import torch.nn.functional as F
from torch.autograd import Variable
import math
# from utils.model_utils import... | completion/models/model_embedding.py | Apache-2.0 | 4,489 | 5e37dcfa004a481a365aa31f49a17851a23481d7 | Python | py | |
import math
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
class AMDIMEncoder(nn.Module):
def __init__(self, dummy_batch, num_channels=3, encoder_feature_dim=64, embedding_fx_dim=512,
conv_block_depth=3, encoder_size=32, use_bn=False):
super().__init... | pl_bolts/models/self_supervised/amdim/networks.py | Apache-2.0 | 11,484 | fee1bc6e063d4d5837c6e0c916f7a3fb4ca17568 | Python | py | |
import os, sys
BASE_DIR = os.path.normpath(
os.path.join(os.path.dirname(os.path.abspath(__file__))))
import argparse
import numpy as np
import json
import datetime
import time
from collections import defaultdict
from data_utils import *
import torch
import torch.nn as nn
import torch.nn.functional as ... | joint_icp_images.py | MIT | 50,775 | fee1dd5859b61d5708a921ffe3e33a35661c3ba3 | Python | py | |
from itertools import product
import os
import os.path as osp
import json
import torch
import numpy as np
from torch_geometric.data import (InMemoryDataset, Data, download_url,
extract_zip)
from torch_geometric.utils import remove_self_loops
class PPI(InMemoryDataset):
r"""The p... | torch_geometric/datasets/ppi.py | MIT | 4,414 | fee1f374fe9814e8bf856e5db50e94822ec86613 | Python | py | |
from functools import partial
from typing import Tuple, Optional, Union
from torch import nn as nn
from torch.autograd.graph import saved_tensors_hooks
from transformers import PreTrainedModel
from transformers.modeling_outputs import BaseModelOutput
from lean_transformer import LeanFFN, LeanSelfAttention
from lean_t... | lean_transformer/transformer.py | MIT | 9,671 | fd6630221aa056523d023743ac66ab327836eb4a | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import numpy as np
from maskrcnn_benchmark.structures.keypoint import PersonKeypoints
import matplotlib.pyplot as plt
import cv2
import torch
from torchvision import transforms as T
from torchvision.transforms import functional as F
from maskrcnn_b... | demo/predictor.py | MIT | 15,085 | e94a159bafaa4fd34de1575b0e3d0318ce13a014 | Python | py | |
'''
visual prefix version 3
prefix-tuning + visual-prefix
'''
import torch
import torch.nn as nn
import thumt.modules as modules
from .prefix import _split_heads
from .transformer import Transformer
from torch.nn import functional as nnf
from thumt.models.prefix import PrefixModel
from thumt.models.visual_prefix imp... | thumt/models/visual_prefix_v3.py | BSD-3-Clause | 6,341 | d7603cc09259e1608b6ae0fa9966618b546ea19d | Python | py | |
from typing import Type
import torch
import os
import unittest
import heat as ht
import numpy as np
from ...tests.test_suites.basic_test import TestCase
class TestLinalgBasics(TestCase):
def test_cross(self):
a = ht.eye(3)
b = ht.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])
# different types... | heat/core/linalg/tests/test_basics.py | MIT | 80,277 | ff034da3afa6e5031147aaf09b143db36c5e638a | Python | py | |
# Copyright (c) 2020, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | sample/pytorch/decoder_sample.py | Apache-2.0 | 6,297 | 52d6d1daf33b1c688b3731a3e41796884525b7f0 | Python | py | |
import logging
import pytorch_lightning as pl
from clearml import StorageManager, Task
from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint
from argument_parser import parse_args
from model.mimo_lightning_module import MIMOUnetModule
def _train(args, pl_module, checkpoint, no_test=False):
... | train.py | Apache-2.0 | 2,828 | b2585af98333aa64e5473d4a259a46a6263fcded | Python | py | |
import argparse
import torch
from torchbenchmark.util.model import BenchmarkModel
from typing import List, Dict, Tuple
def add_bool_arg(parser: argparse.ArgumentParser, name: str, default_value: bool=True):
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('--' + name, dest=name, a... | torchbenchmark/util/framework/huggingface/args.py | BSD-3-Clause | 1,330 | fee27055a95e549c3455108a59e42c957189b345 | Python | py | |
from torch_geometric.nn import GCNConv
from torch_geometric.nn.pool.topk_pool import topk,filter_adj
import torch
import numpy as np
class KGPool(torch.nn.Module):
def __init__(self,in_channels,ratio=1.0,Conv=GCNConv,non_linearity=torch.tanh,dynamic_pooling=True):
super(KGPool,self).__init__()
self... | KGPool/layers.py | MIT | 3,951 | ff13f269f0965dac91ba37c92ccafa14c810ebce | 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/models/test_onnx.py | Apache-2.0 | 5,325 | fcce3d4bc86b7eac4fdc9aabb5a85505fc5adb49 | Python | py | |
# coding=utf-8
import logging
import datetime
import numpy as np
import torch
import os, random
from omniglot_dataset import OmniglotDataset
from cub_dataset import CUBDataset
from fc100_dataset import FC100Dataset
from car_dataset import StanfordCarDataset
from dog_dataset import StanfordDogDataset
from mini_imagenet_... | src/initializer.py | Apache-2.0 | 5,902 | 28f7681a4ffa6d847fd6bd3e0f3450e1473a4e3b | Python | py | |
import onnx
import torch
from onnx_pytorch.op_code_generators import OpCodeGenerator
class MulOpCodeGenerator(OpCodeGenerator):
def __init__(self,
onnx_ver=onnx.defs.onnx_opset_version(),
torch_ver=torch.__version__):
super(MulOpCodeGenerator, self).__init__(onnx_ver, torch_ver)
... | onnx_pytorch/op_code_generators/Mul.py | Apache-2.0 | 670 | fee295f6430d036e8a774e8308965df9b5da7082 | Python | py | |
# Copyright (c) 2020, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | nemo/collections/nlp/models/machine_translation/mt_enc_dec_bottleneck_model.py | Apache-2.0 | 18,488 | 1e7b89949ba74558374e784cf8830c646c916aaa | Python | py | |
""" Reimplement of Publicated Model Archiectures applicable in NvTK.
This module provides
1. `NINCNN` - Network in Network CNN model Archiecture
2. `DeepSEA` - DeepSEA architecture (Zhou & Troyanskaya, 2015).
3. `Beluga` - DeepSEA architecture used in Expecto (Zhou & Troyanskaya, 2019).
4. `DanQ` - DanQ architect... | NvTK/Model/Publications.py | BSD-3-Clause | 11,304 | 80408d91490e6ee15bf26844c6fd43105afc77b0 | Python | py | |
# Copyright 2019 The Texar Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | tests/modules/classifiers/roberta_classifier_test.py | Apache-2.0 | 6,591 | 429df38bb2950ca9dfbbcc4f2540e0e840e679cf | Python | py | |
import torch.nn as nn
class ASPP_plus(nn.Module):
def __init__(self, params):
super(ASPP_plus, self).__init__()
self.conv11 = nn.Sequential(nn.Conv2d(params.c[-1], 256, 1, bias=False),
nn.BatchNorm2d(256))
self.conv33_1 = nn.Sequential(nn.Conv2d(params.... | lib/head/aspp.py | MIT | 1,810 | 10634e3270c617c8d33daf4f2df34ba8c098ad09 | Python | py | |
import torch
def test_saveable_dataloader(tmpdir):
from speechbrain.dataio.dataloader import SaveableDataLoader
save_file = tmpdir + "/dataloader.ckpt"
dataset = torch.randn(10, 1)
dataloader = SaveableDataLoader(dataset, collate_fn=None)
data_iterator = iter(dataloader)
first_item = next(dat... | tests/unittests/test_dataloader.py | Apache-2.0 | 2,150 | 52a26c4220d54bf45484cf7fb76e5b51f6efe43b | Python | py | |
from torchvision.transforms import transforms
from data_aug.gaussian_blur import GaussianBlur
from torchvision import transforms, datasets
from data_aug.view_generator import ContrastiveLearningViewGenerator
from exceptions.exceptions import InvalidDatasetSelection
from torch.utils.data import Dataset
class Contrasti... | data_aug/contrastive_learning_dataset.py | MIT | 4,257 | fee2d2252fe9f8ab3fcbb8f449717a9bb497bed1 | Python | py | |
import numpy as np
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
from torch.nn.init import xavier_uniform_, constant_
zeros_initializer = partial(constant_, val=0.)
def gaussian_smearing(distances, offset, widths, centered=False):
... | nff/nn/layers.py | MIT | 4,305 | b2cfbfe53c9e896ca85feadd4ce4850428ed3405 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
from typing import List
import fvcore.nn.weight_init as weight_init
import torch
from torch import nn
from detectron2.config import configurable
from detectron2.layers import Conv2d, Linear, ShapeSpec, get_norm
from detectron2.utils.registry import ... | detectron2/modeling/roi_heads/box_head.py | Apache-2.0 | 4,082 | fccf3ceb51d050a348e44dfc7fa1b8e7539c797b | Python | py | |
"""
AC-GAN Implementaion inspired by @eriklindernoren
Reference:
https://github.com/eriklindernoren/PyTorch-GAN/blob/master/implementations/acgan/acgan.py
"""
import torch
import torch.nn as nn
class Generator(nn.Module):
def __init__(
self,
latent_dim: int,
n_classes: int,
... | GAN/AC-BIGGAN-with-CIFAR10/models/acgan.py | MIT | 2,928 | 651960df87a6757a2e151fae86c72a598ae74784 | Python | py | |
"""
Naive forward integration methods.
"""
import torch
import torch.nn as nn
import numpy as np
from arnoldi import arnoldi_iteration
from components import replicator
class phi(nn.Module):
"""Exponential integrator based on Arnoldi iteration."""
def __init__(self, fitness, krylov_dim, t):
super(phi, ... | odeint.py | MIT | 1,480 | fee3057fc75f05d0461ae39b09b1948889afe069 | Python | py | |
#!/usr/bin/env python
# This script extracts fp32 consolidated weights from a zero 2 and 3 DeepSpeed checkpoints. It gets
# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
# the future. Once extracted, the weights don't require DeepSpeed and can be used in any
# appli... | deepspeed/utils/zero_to_fp32.py | MIT | 18,503 | 7c229518e0bca2e6cca165e0e8031b339a32378a | Python | py | |
import logging
from setuptools import setup, find_packages
tutor_deps = [
"pillow",
"tqdm",
"ipython"
]
test_deps = [
'pytest>=4',
'pytest-cov>=2.6.0',
'pytest-flake8',
]
docs_deps = [
'sphinx',
'sphinx_rtd_theme',
'sphinx_toggleprompt',
'sphinx-gallery>=0.6',
'nbsphinx',
... | setup.py | Apache-2.0 | 1,834 | fee3340a286b36ced324ecf2b3cbbb44066678f1 | Python | py | |
import transformers
import torch
from meercat.models import RelicModel, RelicConfig
tokenizer = transformers.AutoTokenizer.from_pretrained('bert-base-cased')
config = RelicConfig(vocab_size=28996)
model = RelicModel.from_pretrained('bert-base-cased', config=config)
model_inputs = tokenizer(
['I am a banana', 'M... | tests/relic_test.py | Apache-2.0 | 487 | 1ee15331b56ade7963156ccd23e509640dff7520 | Python | py | |
"""
:type: tuple
:Size: 54.854MB
:Package Requirements:
* **pytorch**
Pretrained GAN model on SST-2 dataset used in :py:class:`.GANAttacker`. See :py:class:`.GANAttacker` for detail.
"""
from OpenAttack.utils import make_zip_downloader
NAME = "AttackAssist.SGAN"
URL = "https://cdn.data.thunlp.org/TAADToolbox/SGN... | OpenAttack/data/sgan.py | MIT | 25,851 | ff01422d72a84c86417b5ca0adc6f443aac5dcd7 | Python | py | |
# -*- coding: utf-8 -*-
import os
import torch
from torch import nn
import itertools
class Common(nn.Module):
def __init__(self):
super(Common, self).__init__()
self.conv1 = nn.Conv2d(in_channels=4, out_channels=16,
kernel_size=(8, 8), stride=(4, 4))
self.act... | utils_tools/net.py | MIT | 4,242 | 456a4213a82f570c108dbb422115333009eea180 | Python | py | |
"""Utilities for convolutions."""
import numpy as np
import torch
import math
from torch import nn
from torch.nn import functional
from agent import util
def get_parity_matrix(size: int, center_even=False):
# Note: assumed to be square.
parities = torch.tensor(np.mod(np.tile(np.linspace(0, size - 1, size), (... | model/utilities/hex_conv.py | MIT | 5,204 | fee35c3c347485b2c5a1d2a16ad4c0384cadf9cd | Python | py | |
from environments.isc_environments.SimpleISC import SimpleISC
from utilities.data_structures.Config import Config
from agents.Trainer import Trainer
from agents.DQN_agents import DQN, DDQN, Dueling_DDQN, DDQN_With_Prioritised_Experience_Replay, DRQN
import wandb
from gym.core import Wrapper
from torch.cuda import is_... | DeepRL/ISC_Discrete_Trainer.py | MIT | 1,750 | 5e02bea9910772e240e61a7ec00625d1c83b60cb | Python | py | |
import torch
import torch.nn as nn
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.model_zoo import load_url as load_state_dict_from_url
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
... | resnet.py | MIT | 14,496 | 70138c7a49165bc8e26c4435a451b6669a90f0fc | Python | py | |
"""
AdelaiDet for non-commercial purposes
(For commercial use, contact chhshen@gmail.com for obtaining a commerical license.)
Copyright (c) 2019 the authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are me... | detectron2/modeling/solov2/loss.py | Apache-2.0 | 5,861 | b2e04589c89464821c4779e8de448584bd7fac85 | Python | py | |
# This code is modified from https://github.com/facebookresearch/low-shot-shrink-hallucinate
import torch
from PIL import Image
import numpy as np
import pandas as pd
import torchvision.transforms as transforms
import datasets.additional_transforms as add_transforms
from torch.utils.data import Dataset, DataLoader
fro... | teacher_miniImageNet/datasets/DTD_few_shot.py | MIT | 6,274 | 70805fd59b962659e12e6da98b20845e640dae33 | Python | py | |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn.parameter import Parameter
from torch.nn.init import xavier_normal
from IPython import embed
from functools import partial
from einops import rearrange, repeat
im... | model_performer_multihead.py | MIT | 23,968 | 45ac6c68197adb446b730f6db703c4446adb643a | Python | py | |
import rdkit
import rdkit.Chem as Chem
import copy
import torch
class Vocab(object):
def __init__(self, smiles_list):
self.vocab = [x for x in smiles_list] #copy
self.vmap = {x:i for i,x in enumerate(self.vocab)}
def __getitem__(self, smiles):
return self.vmap[smiles]
def... | polymers/poly_hgraph/vocab.py | MIT | 2,246 | cc063d1f071d4ab9b5190e4db086faa8f4c00034 | Python | py | |
# Copyright 2020 The universal_double_descent Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | computation.py | Apache-2.0 | 16,572 | 704c04cee59f31d53a5e3cd7212f81bcdf797ccd | Python | py | |
#!/bin/env python
# -*- coding: utf-8 -*-
#
# Created on 4/11/19
#
# Created for py_bacy
#
# @author: Tobias Sebastian Finn, tobias.sebastian.finn@uni-hamburg.de
#
# Copyright (C) {2019} {Tobias Sebastian Finn}
#
# System modules
import pickle as pk
import os
import glob
from shutil import copyfile
# External mod... | py_bacy/pytassim_simplified.py | MIT | 23,184 | fee40a677c5e2908d6cc4a09664056b87db97e57 | Python | py | |
import torch
import torch.nn as nn
from mmcv.cnn import normal_init
from torch.autograd import Function
import numpy as np
from ..builder import HEADS, build_loss
from ...core import top_k_accuracy
from .base import AvgConsensus, BaseHead
from itertools import chain
class GradReverse(Function):
@staticmethod
... | mmaction/models/heads/dann_tsm_head.py | Apache-2.0 | 6,308 | fee4143cea0bdfadd426b9831276c71e55384043 | Python | py | |
# conv.py
"""
Created on Sun Jun 10 22:43:32 2018
@author: Wentao Huang
"""
#import ipdb
import math
from copy import deepcopy
from collections import OrderedDict, Iterable
import torch as tc
import torch.nn.functional as F
from .linear import Linear
from .. import utils
from ..utils.data import OrderedDataset
from ..... | code/nn/conv.py | BSD-3-Clause | 24,648 | 344a6fa6492dca07fca7f70d8a7f1949f10942ea | Python | py | |
import torch
from torch import nn
from pytest import approx
class TestSoftmax:
def test(self):
# ソフトマックスの方向がよくわからなくなった
# ソフトマックスする直前の状態が以下とする
# 4次元配列であってサイズが [バッチサイズ, ヘッド数, 文章長さ, 文章長さ] である
attention_scores = torch.Tensor(
[[[
[1.0, 2.0, 1.0],
... | tests/torch/test_nn_softmax.py | MIT | 1,384 | 1e4da39401ac03b9027123ad2184cb8dab967d8b | Python | py | |
from . import assert_match, ntorch, NamedTensor
import numpy as np
import torch
from collections import OrderedDict
import pytest
import torch.nn.functional as F
def make_tensors(sizes):
return [ntorch.randn(sizes)]
def test_shift():
for ntensor in make_tensors(OrderedDict(alpha=10, beta=2, gamma=50)):
... | namedtensor/test_core.py | MIT | 7,187 | 5e6d638d0125b2c7cd7f60cc451cd5ea0cc94164 | Python | py | |
"""Base class for encoders and generic multi encoders."""
import torch.nn as nn
from onmt.utils.misc import aeq
class EncoderBase(nn.Module):
"""
Base encoder class. Specifies the interface used by different encoder types
and required by :obj:`onmt.Models.NMTModel`.
.. mermaid::
graph BT
... | onmt/encoders/encoder.py | MIT | 1,331 | fee48503f4c56c1ae4702caba7f2a10fee74692b | Python | py | |
import os, argparse
import numpy as np
import torch
from tqdm import tqdm
from torchvision import transforms
from models.model import Generator, Discriminator
import config as cf
from utils import *
parser = argparse.ArgumentParser()
parser.add_argument('--batch-size', type=int, default=1,
help='tr... | image2image_translation/main.py | MIT | 12,519 | fee4869071c9790761317393c4b0f2a4918c4ffa | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def split_dim(x, dim, n_chunks):
shape = x.shape
assert shape[dim] % n_chunks == 0
return x.view(*shape[:dim], n_chunks, shape[dim] // n_chunks, *shape[dim+1:])
def weights_init(init_type='default'):
""" Adopted fr... | models/modules/modules.py | MIT | 1,470 | fee488e68853fca25008558e543d0fcdaf832f67 | Python | py | |
from transformers import CamembertTokenizer, CamembertModel
import torch
from sklearn.metrics.pairwise import cosine_similarity as cosine
if __name__ == '__main__':
cos = torch.nn.CosineSimilarity(dim=1, eps=1e-6)
tokenizer = CamembertTokenizer.from_pretrained("camembert-base")
camembert = CamembertModel.f... | code/BERT/camemBERTPractice.py | Apache-2.0 | 996 | fee496f4c6a9857a29bca2aab1276ac0a44c65ec | Python | py | |
"""Implements dataset for Image segmentation tasks."""
from __future__ import annotations
import os
from typing import List, Optional, Tuple, Union
import albumentations as A
import pandas as pd
import torchvision
from torch.utils.data import Dataset
from torchflare.datasets.utils import apply_image_transforms, appl... | torchflare/datasets/segmentation.py | Apache-2.0 | 7,044 | 12dbd42527f086ee36a406a6c37645f0e38d745b | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Nagoya University (Tomoki Hayashi)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Tacotron2 encoder related modules."""
import six
import torch
from torch.nn.utils.rnn import pack_padded_sequence
from torch.nn.utils.rnn import pad_pack... | espnet/nets/pytorch_backend/tacotron2/encoder.py | Apache-2.0 | 6,320 | fee4b1c555205ba7ef0176cc033743d9a360bafa | Python | py | |
from __future__ import print_function, division
import os
import torch
from torch.autograd import Variable
from skimage import io
import pandas as pd
import numpy as np
from torch.utils.data import Dataset
from lib.transformation import AffineTnf
class PFPascalDataset(Dataset):
"""
Proposal Flow ... | lib/pf_dataset.py | MIT | 4,884 | fee4c41e85568086fd8176ce89e3328b4ba1158a | Python | py | |
import models
import torch
import torchvision.transforms as transforms
from torchvision.datasets import CIFAR10
from torch.utils.data import DataLoader
from config.resnet_cifar10_config import ResNetConf
from models.backbone.resnet import ResidualBlock
import train_and_test.train_and_valid as train
import train_and_tes... | main/main_resnet_cifar-10.py | MIT | 2,681 | e9d00e06c81dcdf536fe5ef6ba8fe584dd7d98fc | Python | py | |
import brevitas.nn as qnn
import torch.nn.utils.prune as prune
from torch import nn
import torch
from tqdm import tqdm
from sklearn.metrics import accuracy_score
import numpy as np
from train import *
from utils import logger, save_checkpoint
import os
def prune_api(model, th):
parameters_to_prune = []
for m i... | prune.py | MIT | 1,851 | e9691b62597da456419ee90260f2fdfe30a8c317 | Python | py | |
"""Module for testing MTSAC."""
import numpy as np
import pytest
import torch
from torch.nn import functional as F
from garage.envs import GarageEnv, MultiEnvWrapper
from garage.envs.multi_env_wrapper import round_robin_strategy
from garage.experiment import deterministic, LocalRunner
from garage.replay_buffer import ... | tests/garage/torch/algos/test_mtsac.py | MIT | 8,925 | 7069fec44787d849e20ac1d67aaf01ea4574a8fa | Python | py | |
# !/usr/bin python3
# encoding : utf-8 -*-
# @author : Zijiang Yang
# @file : Burgers_equation_pinn.py
# @Time : 2021/12/6 22:04
import os
import sys
sys.path.append(os.curdir)
import time
import yaml
imp... | PINN/Burgers_equation_pinn.py | MIT | 10,756 | fee4d9f3fde270a9b03eebc3f2cc9e3fb3e1cb88 | Python | py | |
import torch as th
from torch import nn
from torch.utils.data import BatchSampler, RandomSampler, SequentialSampler
from syft.generic import ObjectStorage
from syft.federated.train_config import TrainConfig
class FederatedClient(ObjectStorage):
"""A Client able to execute federated learning in local datasets."""... | syft/federated/federated_client.py | Apache-2.0 | 3,095 | e972753c96407e6760e1b4a52cbac8da7dc7b322 | Python | py | |
#!/usr/bin/env python3
import math
from itertools import chain
from collections.abc import MutableMapping
from copy import deepcopy
import numpy as np
import torch
from espnet.nets.pytorch_backend.transformer.mask import target_mask
import lattice
from utils import sym2idx
class Cache(dict):
"""A customised dic... | lattice_rescore.py | MIT | 25,340 | fee4ee868e18ab12211eba35ed4f2a8ede92b4f8 | Python | py | |
import os
import torch.nn as nn
import torch.utils.tensorboard
import tqdm
from easydict import EasyDict
from torch.utils.data import DataLoader
from datasets.qm9_property import TARGET_NAMES
from utils import misc as utils_misc
from utils.parsing_args import get_prop_pred_args
from utils.transforms import get_edge_t... | train_prop.py | MIT | 10,018 | fee4f65c440bc4643a4791afb5d574aa683b5d30 | Python | py | |
import torch
import torch.nn as nn
class Matcher:
def __init__(self, how='gram_matrix', loss='mse', map_index=933):
self.mode = 'store'
self.stored = {}
self.losses = {}
if how in all_features.keys():
self.get_statistics = all_features[how]
else:
as... | utils/perceptual_loss/matcher.py | MIT | 2,176 | fee5193ec578c27f2269efd712295f99c0791605 | Python | py | |
import typing as tp
import pandas as pd
import numpy as np
import torch
from torch.utils.data import Dataset
class MTDataset(Dataset):
def __init__(self, filename: str):
self.data_array = pd.read_csv(filename).values
def format_row(
self, row: np.ndarray
) -> tp.Tuple[tp.Tuple[np.nda... | mt_grad/data/dataset.py | MIT | 1,206 | 24df5575306c12630d871e459b3e3b6b7fbc9102 | Python | py | |
#
# Adpated from https://github.com/eclique/RISE/blob/master/explanations.py
#
import os
import numpy as np
import torch
from skimage.transform import resize
from torch import nn as nn
from tqdm import tqdm
from interpretability.explanation_methods.utils import ExplainerBase, limit_n_images
from project_config im... | interpretability/explanation_methods/explainers/rise.py | BSD-2-Clause,0BSD | 3,724 | 706a70d7596e9d2f6bc275e3361f5362b4227aaa | Python | py | |
from torch.utils.data import Dataset
import h5py
import numpy as np
import json
import torch
from pathlib import Path
import random
from torchvision.transforms import transforms as T
__CLASS_MAPPING__ = {
0: 5, # None
1: 5, # Buildings
2: 5, # Fences
3: 5, # Other
4: 6, # Pedestrians
5: 5,... | models/carlaDatasetTransform.py | MIT | 9,579 | fee54f8c77c17644a3e2bd35234274bfa4c1ed47 | Python | py | |
""" Implementations of Lottery Ticket Pruner.
Modified scripts from https://github.com/microsoft/nni
"""
import copy
import logging
import torch
from schema import And, Optional
from moegplib.lightnni.utils.config_validation import CompressorSchema
from moegplib.lightnni.compressor import Pruner
from moegplib.lightn... | src/moegplib/lightnni/algorithms/lottery_ticket.py | MIT | 5,616 | 5f59d665ac84d68b8578bc8880b8979ceff8f620 | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
from mmdet.core.bbox import BaseBBoxCoder
from mmdet.core.bbox.builder import BBOX_CODERS
from ..structures import limit_period
@BBOX_CODERS.register_module()
class FCOS3DBBoxCoder(BaseBBoxCoder):
"""Bounding box coder for FCOS3D.
... | mmdet3d/core/bbox/coders/fcos3d_bbox_coder.py | Apache-2.0 | 5,133 | 7cb6b1a333d301e3d299d2afd3086bbac0f3ff2b | Python | py | |
from contextlib import contextmanager
import os
import logging.config
import numpy as np
import torch
from torch.nn.utils.rnn import pack_padded_sequence
from .data import config
def barrier():
""" Calls all_reduce on dummy tensor."""
if torch.distributed.is_initialized():
torch.distributed.all_redu... | milarun/models/seq2seq/utils.py | MIT | 3,179 | fee578d3474a034098861c07e86f0c42992d2d8a | Python | py | |
import torch
import random
from .utils import get_conf, encode_conf
class Mutations():
def __init__(self, search_space, prob_mutation=0.8, prob_resize=0.05, prob_swap=0.04, exploration_vs_exploitation=0.5):
n = len(search_space)
# general vars
self.exploration_vs_exploitation = exploration_... | src/fne/evolution/mutations.py | MIT | 6,673 | fee581edb98dbc9dd10ef107929043f597f52a70 | Python | py | |
import os
import random
import numpy as np
import torch
import torch.nn.functional as F
from apex import amp
from tensorboardX import SummaryWriter
from torch.utils import data
from tqdm import tqdm
from transformers import AdamW, get_linear_schedule_with_warmup
from snippext.dataset import *
from snippext.train_util... | rotom/auto_filter_weight.py | BSD-3-Clause | 24,036 | 107c66a050e095d82f0e8689b1e33759bec964de | Python | py | |
import torch
import numpy as np
import collections
from torch._six import string_classes, int_classes
""" Custom collate function """
def collate_custom(batch):
if isinstance(batch[0], np.int64):
return np.stack(batch, 0)
if isinstance(batch[0], torch.Tensor):
return torch.stack(batch, 0)
... | utils/collate.py | MIT | 1,039 | fee5b598dca88f939fbabf7b50c6dc9e4e9104fa | Python | py | |
import torch.nn as nn
import torchvision
class VGG11(nn.Module):
def __init__(self, num_classes=14, pretrained=True):
super(VGG11, self).__init__()
self.vgg11 = torchvision.models.vgg11(pretrained=pretrained)
num_kernel = self.vgg11.classifier[-1].in_features
self.vgg11.classifier[... | classifier/networks/vgg.py | MIT | 3,133 | e93201b3052b6a91819ec0f30d3bea32846710a1 | Python | py | |
import torch
from torch.nn.functional import normalize
def dist_cond(x: torch.Tensor, c: torch.Tensor, **kwargs):
"""
:param x: the feature vector of the Unet. shape (N,F,H,W)
:param c: the external condition feature vectors. shape (C,N,F)
:return: (C,N,F,H,W)
"""
x_orig = x
# x = normali... | conditions.py | Apache-2.0 | 2,528 | fee5c8f9627b28663b6d1aba0f8628df9be8ec42 | Python | py | |
import sys
sys.path.append('..')
import copy
import torch
import torch.optim as optim
import os
import os.path as osp
import numpy as np
from collections import OrderedDict
from torch.nn import functional as F
from lreid.models import LwFNet, MetaGraph_fd
from lreid.losses import CrossEntropyLabelSmooth, PlasticityLoss... | lreid/core/base_metagraph_p_s.py | MIT | 27,403 | fee5dcd1117bf823641d57de63bf3fd0d602f3a9 | Python | py | |
import torch.nn as nn
class LSTMClassifier(nn.Module):
""" LSTMClassifier class for initializing the layers for the simple
recurrent neural network model (RNN) used for Sentiment Analysis of
IMDB reviews.
Attributes:
embedding_dim (int) dimensionality of the embedding layer
hidden_di... | train/model.py | MIT | 1,500 | fee5e631a6f40f59a0dc3ae33c2911baad5cf5d0 | Python | py | |
"""Module containing operators to work on RGB-Depth images."""
from typing import Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from kornia.geometry.linalg import (
transform_points, inverse_transformation, compose_transformations, convert_points_to_homogeneous
)
from kornia.geometry.co... | kornia/geometry/depth.py | ECL-2.0,Apache-2.0 | 17,116 | 5e9ab3df747ee5f66ad80e95ab3d83e03da09901 | Python | py | |
import logging
import time
import sys
import torch
from torchvision import datasets, models, transforms
import torch.nn as nn
import torch.optim as optim
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def initialize_model(model_name, num_classes,use_pretrained=True):
# Initialize these ... | code/scripts/train_model.py | BSD-3-Clause | 13,700 | e65b6f601e7b3f0e2d271f1e78d0985e53dc1344 | Python | py | |
""" Uncertainty modules
Reference code:
PIENet in
https://github.com/yalesong/pvse/blob/master/model.py
"""
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from models.pie_model import MultiHeadSelfAttention
class UncertaintyModuleImage(nn.Module):
... | models/uncertainty_module.py | MIT | 2,246 | fee63585519ed6ec1f387bb995d91f796257f31f | Python | py | |
from __future__ import division
from collections import defaultdict
from datetime import datetime
import inspect
import itertools
import os
import sys
import warnings
from jinja2 import Environment, FileSystemLoader, Template
import numpy as np
import sklearn
from sklearn import cluster, preprocessing, manifold, deco... | app/kmapper.py | MIT | 45,023 | fee63e4f43d3cd353087fc7ec048af53a2d41dbb | Python | py | |
################################################################################
# Copyright (c) 2021 ContinualAI. #
# Copyrights licensed under the MIT License. #
# See the accompanying LICENSE file for terms. ... | avalanche/benchmarks/utils/data_loader.py | MIT | 16,188 | fee647161e9edfa6c2bef410c13b4729ec33a8be | Python | py | |
import logging
import numpy as np
from mjrl.utils.gym_env import GymEnv
from mjrl.utils import tensor_utils
logging.disable(logging.CRITICAL)
import multiprocessing as mp
import time as timer
import torch
logging.disable(logging.CRITICAL)
# ===========================================================
# Rollout paramet... | mjrl/algos/mbrl/sampling.py | Apache-2.0 | 10,485 | a95d3682f097e9fbbfcd38cc95ac24d3e77942dc | Python | py | |
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/res... | model/resnet.py | Apache-2.0 | 7,320 | d7e9083102dd1d23dc5c809c93cb28a8b9d2dbf4 | Python | py | |
import torch
from unittest import TestCase, main
import gpytorch
import numpy as np
import torch
from gpytorch.distributions import MultivariateNormal
from gpytorch.kernels import GridInterpolationKernel, RBFKernel
from gpytorch.likelihoods import GaussianLikelihood
from online_gp.models.sherman_morrison_prediction_s... | tests/models/test_sherman_morrison_prediction_strategy.py | Apache-2.0 | 9,094 | dfcfe1028e44c0ad3d3cf1a476b77c7c434ea108 | Python | py | |
import torch
from torchaudio.models import Wav2Letter, _MelResNet
from . import common_utils
class TestWav2Letter(common_utils.TorchaudioTestCase):
def test_waveform(self):
batch_size = 2
num_features = 1
num_classes = 40
input_length = 320
model = Wav2Letter(num_classes... | test/test_models.py | BSD-2-Clause | 1,428 | 109112ee15e9a4848d801912e9894816a5327bde | Python | py | |
from __future__ import division
import torch
from ignite.exceptions import NotComputableError
from ignite.contrib.metrics.regression._base import _BaseRegression
class FractionalAbsoluteError(_BaseRegression):
r"""
Calculates the Fractional Absolute Error.
:math:`\text{FAE} = \frac{1}{n}\sum_{j=1}^n\fr... | ignite/contrib/metrics/regression/fractional_absolute_error.py | BSD-3-Clause | 1,336 | 5fbea356b11952f92afbe3361787a4cb92c7a550 | Python | py | |
import torch as tc
from torch import nn
from config import Config
leaky_relu = nn.LeakyReLU(negative_slope=0.2) # TF default apparently
class Encoder(nn.Module):
def __init__(self, cfg):
super(Encoder, self).__init__()
# padding = VALID??
tf1, tf2, tf3, tf4 = cfg.total_filters, cfg.to... | cnns.py | MIT | 7,840 | 45f7fb8b37131103f3b8c148259dea2f6afda963 | Python | py | |
import torch.nn as nn
import torch
import os
import math
from lib.utils.quantize_utils import QConv2d, QLinear
__all__ = ['MobileNetV2', 'mobilenetv2', 'qmobilenetv2']
def conv_bn(inp, oup, stride, conv_layer=nn.Conv2d, half_wave=True):
if conv_layer == nn.Conv2d:
return nn.Sequential(
conv_l... | lib/models/mobilenetv2.py | MIT | 7,388 | fee6ed04c090dc2319a3785f6499dd3aff0f490d | Python | py | |
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. 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 requ... | nemo/collections/tts/torch/data.py | Apache-2.0 | 38,933 | 248fd355fbbb2df2567267c15864a8e1fed5b229 | 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 threading
import weakref
from concurrent.futures.thread import ThreadPoolExecutor
from typing import Sequence, Optional, Tuple, Any, ... | hivemind/client/averaging/__init__.py | MIT | 25,887 | fee6fb95a721141558ef67923be511bc52d50403 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.