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 |
|---|---|---|---|---|---|---|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
sys.path.append('/home/ark/local/trainningcode/PF-Net-Point-Fractal-Network-try602/')
# sys.path.append('/home/ark/local/trainningcode/PF-Net-Point-Fractal-Network-try302-0328/')
import numpy as np
import argparse
import random
import torch
import to... | CP-Net/show_recon.py | MIT | 10,155 | 4bb3dffd842c124df56e987529962810d48fbd5d | Python | py | |
import numpy as np
import os, datetime, pickle
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.optim as optim
import matplotlib.pyplot as plt
if not torch.cuda.is_available():
print ("Warning: I see no CUDA, this will be slow!")
class RFIDetect_each_epoch:
def __init__... | rfi_ml_new_train_each_epoch.py | MIT | 13,618 | 3a4caec706bd9f421d18afc362cd070fd4129701 | Python | py | |
from torch.onnx.symbolic_helper import _block_list_in_opset, parse_args
import torch.onnx.symbolic_helper as sym_help
import torch.onnx.symbolic_opset9 as sym_opset9
import warnings
# Note [ONNX operators that are added/updated from opset 7 to opset 8]
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | torch/onnx/symbolic_opset7.py | Intel | 2,577 | a94010ba2ac2a2bc22954c49b548de2f3d57568f | Python | py | |
import copy
import numpy as np
import torch
from torch import nn
import pytorch_lightning as pl
from lightning_baselines3.off_policy_models import SAC
from lightning_baselines3.common.distributions import SquashedMultivariateNormal
from lightning_baselines3.common.utils import polyak_update
class Model(SAC):
... | examples/sac/minimal_lunarlander.py | MIT | 3,387 | dff3606c30e137819f87787dc4e819eb7f99681b | Python | py | |
from __future__ import print_function, division
import torch
from torch.nn import Module
import numpy as np
from functools import reduce
class HandwritingLoss(Module):
def __init__(self, parameters):
super(HandwritingLoss, self).__init__()
self.params = parameters
def forward(self, mdn_parame... | src/loss.py | MIT | 1,304 | cc2392c52bc4f8d7c907d20f5e70677d93498da4 | Python | py | |
from __future__ import print_function
import pickle
import logging
import numpy as np
from torch.autograd import Variable
import torch.nn.functional as F
import torch
from laed import main as engine
from laed.enc2dec.decoders import GEN, DecoderRNN, TEACH_FORCE
from laed import utils
from laed.dataset.corpora import... | laed/dialog_utils.py | Apache-2.0 | 15,892 | 3a4cd8c40e49ea6b91ad431ca968181ff3f39b82 | Python | py | |
import logging
import torch
from transformers import BertModel
from experimenter.modeling import BaseModel
class SharedEncoder(BaseModel):
"""A model that takes a text sequence and a list of
(classes, sequences), creates a representation and
output a decoder for sequence and/or label per class"""
d... | experimenter/MultiTask/modeling.py | MIT | 17,108 | 3a4cda494168585b68f1b34e069993c8d15631e4 | Python | py | |
import torch
import torch.nn as nn
import math
from models.efficientnet import EfficientNet
from models.bifpn import BIFPN
from .retinahead import RetinaHead
from models.module import RegressionModel, ClassificationModel, Anchors, ClipBoxes, BBoxTransform
from torchvision.ops import nms
MODEL_MAP = {
'efficientde... | models/efficientdet.py | MIT | 3,772 | d7e85f6fe3b89361a2cc158dc3b51c6bfa8ecdab | Python | py | |
"""
note(jesse): this is a hack, meant to override DDP to provide support for broadcasting sparse tensors
"""
from contextlib import contextmanager
import copy
import itertools
import torch
import torch.cuda.comm
import torch.distributed as dist
if dist.is_available():
from torch.distributed.distributed_c10d imp... | python/ddp.py | Apache-2.0 | 26,451 | 3a4d0c1376d65f10b54ec73643b9f976ffca0e9e | Python | py | |
# Copyright (C) 2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | external/mmsegmentation/segmentation_tasks/apis/segmentation/train_task.py | Apache-2.0 | 7,891 | 129a4b27a646e5916dd7b1c5949a2b70a273ca2b | Python | py | |
from __future__ import print_function, absolute_import
import time
import torch
import torch.nn as nn
from torch.nn import functional as F
import torch.distributed as dist
from .utils.meters import AverageMeter
class Trainer(object):
#############################
# Training module for
# 1. "NetVLAD: CNN ... | ibl/trainers.py | MIT | 13,606 | 7ca628d96e22b219092c2fc353590364ad6c0bcd | Python | py | |
import numpy as np
import scipy.signal
import torch
import torch.nn as nn
def combined_shape(length, shape=None):
if shape is None:
return (length,)
return (length, shape) if np.isscalar(shape) else (length, *shape)
def mlp(sizes, activation, output_activation=nn.Identity, init=None):
layers = [... | spinup/algos/pytorch/ddpg/core.py | MIT | 2,159 | e64186e427af386c281addeb5098e43a9af68d20 | Python | py | |
from torch.optim.sgd import SGD
from torch.optim.optimizer import required
from torch.optim import Optimizer
import torch
import sklearn
import numpy as np
import scipy.sparse as sp
class PGD(Optimizer):
"""Proximal gradient descent.
Parameters
----------
params : iterable
iterable of paramete... | deeprobust/graph/defense/pgd.py | MIT | 7,514 | 3a4d85971279fddbd8664cf8aac08c98abf74694 | 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... | examples/segmentation_3d/unet_training_dict.py | Apache-2.0 | 7,609 | 42188356d0360f55e182b7984eee5864fafaf406 | Python | py | |
import socket
import multiprocessing
import threading
import sys
import select
import os
import queue
import time
import torch.nn as nn
import torch
import numpy as np
import pickle
SERVER_ADDRESS='./pip1.socketpipe'
MODE = 0 #1 for server and 0 for client
def recv_msg(udp_socket,que,stop):
while True:
... | Kernel communication/testing/gpu.py | MIT | 3,120 | 702638f5546c3e5e9486916ea5acd86de156a82f | Python | py | |
#!/bin/python3
"""GPT2 Language Modelling miner
This file demonstrates training the GPT2 neuron with language modelling.
Example:
$ python examples/gpt2-wiki.py
"""
import argparse
import math
import os
import time
import torch
import torch.nn.functional as F
import traceback
import time
import random
from ... | examples/gpt2-genesis.py | MIT | 10,932 | 12d0df101bf1350f2bce5967ab2dbe5c8254da1d | Python | py | |
# -*- coding: utf-8 -*-
"""
@author: Ardalan MEHRANI <Ardalan77400@gmail.com>
"""
# Source: https://github.com/ArdalanM/nlp-benchmarks/blob/master/src/vdcnn/net.py
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicConvResBlock(nn.Module):
def __init__(self, input_dim=128, n_filters=... | models/baselines/VDCNN.py | MIT | 4,952 | e91ab64639ebe0fee96019f475030016c7501403 | Python | py | |
# coding=utf-8
# Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. 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
#
# ... | relogic/logickit/tokenizer/tokenization_utils.py | MIT | 54,992 | 1ed46d0aab22d93c484589837d48129ceb4813f6 | Python | py | |
import pyrender
import os
import trimesh
import numpy as np
import cv2
import os
import torch
from scipy.spatial.transform import Rotation as R
os.environ['PYOPENGL_PLATFORM'] = 'egl'
def to_homo(rotation, translation):
transform = np.eye(4)
transform[:3, :3] = rotation
transform[:3, 3] = translation
... | render_swisscube.py | MIT | 8,167 | 3a4dc6e029a35e3d0c046bf603883d099d674367 | Python | py | |
from PIL import Image
import blobfile as bf
from mpi4py import MPI
import numpy as np
from torch.utils.data import DataLoader, Dataset
import pickle
import random
def load_data(
*, data_dir, batch_size, image_size, class_cond=False, deterministic=False
):
"""
For a dataset, create a generator over (images,... | improved_diffusion/image_datasets_hue.py | MIT | 5,458 | 3a4dcc5cfa70dfc73c86f9f86f4e90c3882f8d07 | Python | py | |
import yaml
import argparse
from tqdm import tqdm
import torch
import os
import torch.nn as nn
import torch.optim
import torch.utils.data
from collections import OrderedDict
from lit import LitTrainer, Section
from sentiment_datasets import *
import torchvision.transforms as transforms
import json
import vdcnn
from v... | vdcnn/trainlit.py | Apache-2.0 | 8,842 | 5f4f2d76de98763bc74e4fb6a1d3fb8ca19e798e | Python | py | |
import torch
import torch.nn as nn
from Layers import EncoderLayer, DecoderLayer
from Embed import Embedder, PositionalEncoder
from Sublayers import Norm
import copy
def get_clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
class Encoder(nn.Module):
def __init__(self, vocab_s... | Models.py | Apache-2.0 | 2,572 | f99c6bbc8f20dc344b359b3ad88ef8a01b6d40a5 | Python | py | |
from __future__ import absolute_import, division, print_function
import argparse
import logging
import torch
from torch.distributions import constraints, transforms
import pyro
import pyro.distributions as dist
from data import J, sigma, y
from pyro.infer import SVI, JitTrace_ELBO, Trace_ELBO
from pyro.optim import ... | examples/eight_schools/svi.py | MIT | 2,899 | d788c4e752b6caefcd7bbe4f7e539b183f4bfe16 | Python | py | |
# Transform for caption
from torch.nn.utils.rnn import pad_sequence
import torch
class Tokenizer:
def __init__(self, tokenizer):
self.tokenizer = tokenizer
def __call__(self, sentence):
return self.tokenizer.tokenize(sentence)
class VocabToIndex:
def __init__(self, vocabulary):
... | preprocess/transform.py | MIT | 843 | 7c1e34afffe5649e6ced3187663d7e2a882654b3 | Python | py | |
import os
import numpy as np
import torch
import torch.utils.data
from PIL import Image
import random
import torchvision.transforms.functional as TF
class Dataset(torch.utils.data.Dataset):
def __init__(self, img_dir_high=None, img_dir_medium=None, img_dir_low=None, img_dir_low2=None, slide_list_filename=None, tr... | gland_classification/four_resolutions_model/dataset.py | MIT | 6,596 | 7ccf2269c1112ee8a97e4a9cc366130b37e18ba6 | Python | py | |
import torch.nn as nn
import torch
class PathEmbedding(nn.Module):
def __init__(self, node2vec, dropout=0.1):
super().__init__()
self.path_embed = nn.Embedding.from_pretrained(node2vec)
# self.rt = nn.Embedding(21, 64) ##road type
# self.ow = nn.Embedding(2... | embed/embedding.py | MIT | 846 | 03a80458bc21c5c3ca2d44f7f95a371a0a28a1e6 | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import logging
import shutil
import tempfile
import numpy as np
import pytest
import torch
import torch.nn as nn
from mmcv.runner import build_runner
from mmcv.runner.hooks import Hook, IterTimerHook
from torch.utils.data import DataLoader
import mmcls.core # noqa: F40... | tests/test_runtime/test_hooks.py | Apache-2.0 | 4,838 | 70140d9e52bbd0e9d092e428dc497bc57e0b4f09 | Python | py | |
import os
import yaml
import torch
import argparse
import logging
import numpy as np
from tqdm import tqdm
from utils.logger import ColoredLogger
from datasets.celeba import CelebADataset
from datasets.cub200 import Cub200Dataset
from torch.utils.data import DataLoader
import torchvision.utils as tuitls
from models.VAE... | run.py | MIT | 10,622 | e934fd42639777686653ea187f3daf748e72c461 | Python | py | |
import torch
import csv
import shutil
import pathlib
from copy import deepcopy
from os import remove
from os.path import isfile
from collections import OrderedDict
from sklearn.metrics import f1_score
import models
def load_model(model, ckpt_file, main_gpu, use_cuda: bool=True, strict=True):
r"""Load model for... | utils.py | MIT | 8,495 | 6b23d3f806cd81169281f463e4fe3161f98545a9 | Python | py | |
import sys
import time
import torch
import random
import argparse
import numpy as np
import torch.nn as nn
import torchvision.transforms as transforms
from torchvision import datasets
from torch.utils.data import DataLoader
def printParaNum(model):
'''
function: print the number of total parameters and ... | src/train.py | MIT | 7,065 | 3a4e1ba54112edcd8040accdade100cace8abaac | Python | py | |
# -*- coding: utf-8 -*-
"""
Supplementary code for paper under review by the International Conference on Machine Learning (ICML).
Do not distribute.
"""
import numpy
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import ipdb
_NOISE_DIM = 128
_H_FILTERS = 64
cla... | models/dcgan28.py | MIT | 12,113 | 4294a5fffe899b7b5db14e8af88e3ccb70e5b87c | Python | py | |
# Copyright (c) 2019 Graphcore Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | applications/popart/bert/tests/unit/pytorch/pretraining_test.py | MIT | 7,928 | e9ddf840ab72ac06fefa19e9ba312658009cfb9e | Python | py | |
import numpy as np
from PIL import Image
import numbers
from collections.abc import Sequence
from typing import Tuple, List, Optional
import random
import torch
from torchvision import transforms as T
from torchvision.transforms import functional as F
def _check_sequence_input(x, name, req_sizes):
msg = req_size... | semseg/transforms.py | MIT | 8,420 | 3a4e30504b9edbb1dcbafa5a599b8663d30fca2d | Python | py | |
from pathlib import Path
import numpy as np
import torch
from torch_sparse import coalesce
from torch_geometric.data import (Data, InMemoryDataset, download_url,
extract_gz, extract_tar)
from torch_geometric.data.makedirs import makedirs
class EgoData(Data):
def __inc__(self, k... | torch_geometric/datasets/snap_dataset.py | MIT | 9,225 | 3a4e375ca66b588e3300385e8276697f802be18d | Python | py | |
import torch
import torch.nn as nn
from models.aspp import build_aspp
from models.backbone import build_backbone
from models.decoder import build_decoder
from models.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
class DeepLab(nn.Module):
def __init__(self, backbone='resnet', output_stride=16, num_class... | models/deeplab.py | MIT | 2,566 | 3a4e3d62d907e9b24f1ffe1f59b36438c063e776 | Python | py | |
import torch.nn as nn
from torchvision.models import ResNet
from .layer import MultiSpectralAttentionLayer
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
class FcaBottleneck(nn.Module):
expansion = 4
def __init__... | model/fcanet.py | Apache-2.0,MIT | 4,483 | 102fb218161de99d779a5a73235f2c4245d6b3c5 | Python | py | |
import face_model
import argparse
import cv2
import sys
import numpy as np
from mxnet2pytorch import *
from model_pytorch import *
import torch
parser = argparse.ArgumentParser(description='face model test')
# general
parser.add_argument('--image-size', default='112,112', help='')
parser.add_argument('--model', defaul... | deploy/test.py | MIT | 2,022 | 3a4e8ae9c65b7e8f99b42f8be774c03e26623d1d | Python | py | |
# -*- coding: utf-8 -*-
"""
"""
import argparse
import os
import sys
from pathlib import Path
try:
from bpdb import set_trace
except ImportError:
from pdb import set_trace
from fire.trainer import BaseTrainer
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transfor... | fire/train.py | Apache-2.0 | 978 | 4559d94f4e6aadc5fc0b312a5932ad57f2354369 | Python | py | |
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from .basemodel import EdgeSeqModel
from .container import *
# from ..utils.act import map_activation_str_to_layer
# from ..utils.init import init_weight, init_module
from utils.act import map_activation_str_to_layer
from utils.init import init_w... | SubgraphCountingMatching/models/cnn.py | MIT | 8,458 | 247dfe04f95b6beaff150bc251cda301fd9ca438 | Python | py | |
# Copyright 2021 MosaicML. All Rights Reserved.
import collections.abc
import os
import pathlib
from dataclasses import dataclass
from typing import Dict, List, Optional, Sequence, Union
import pytest
import torch
import torch.distributed
import yahp as hp
from _pytest.monkeypatch import MonkeyPatch
import composer.... | tests/trainer/test_ddp.py | Apache-2.0 | 9,806 | 1296c53763b54ce15dd90d3d1607688466c837ba | Python | py | |
import numpy as np
import torch
import gym
import argparse
import os
import utils
import TD3
import DDPG
from utils import Logger
from utils import create_folder
# Runs policy for X episodes and returns average reward
def evaluate_policy(policy, eval_episodes=10):
avg_reward = 0.
for _ in range(eval_episodes):
o... | DDPG/main.py | MIT | 5,955 | 037f09b30852ab4e05ee9c284c4763d425a947f8 | Python | py | |
import torch
from torch.autograd import Variable
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
from PIL import Image
import os
train_root = '/export/data/zqs/Data/HiFiMask-Challenge/phase1'
test_root = '/opt/cephfs_workspace/gpudisk/Qiusheng/Data/HiFiMask-Challenge/phase2'... | mydataset.py | MIT | 3,024 | 3a4eee9e5b8dcbf39268d9b11c04f3d9d647d133 | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# %%
import sys
import os
import multiprocessing
import numpy as np
import torch
from torch import nn, optim
from kbc.util import set_seed
from kbc.training.data import Data
from kbc.training.batcher import Batcher
from kbc.models import DistMult, ComplEx, TransE
im... | old/kbc-cli-toymeta_old.py | MIT | 12,986 | 424e0de32a28179608b20f44d886d6d5e9f4be22 | Python | py | |
import os
import numpy as np
import h5py
import json
import torch
# from scipy.misc import imread, imresize
from tqdm import tqdm
from collections import Counter
from random import seed, choice, sample
from PIL import Image
def create_input_files(
dataset,
karpathy_json_path,
image_folder,
captions_p... | utils.py | MIT | 11,031 | 12959b499d52de3b6a4f49fe0bd77239d901638a | Python | py | |
"""
File needed during race training. Mainly based on [GitHub repository](https://github.com/intersun/PKD-for-BERT-Model-Compression) for [Patient Knowledge Distillation for BERT Model Compression](https://arxiv.org/abs/1908.09355).
"""
import logging
import json
import string
import os
import torch
import pickle
impor... | src/utils/race_data_processing.py | MIT | 8,328 | d7e23751cd2ffd24b84e383bc1206302c0e3c13a | Python | py | |
import os
import torch
import dgl
import networkx as nx
from utils import load_data, load_emb, graph_completion, draw_networkx_edge_labels
from gcs_model import gcs_attention
def run_gcs(args, KG, feats_org, feats_klm):
# cpu for whole KG analysis
args.device = torch.device("cpu")
if KG.number_of_nodes()... | example/src/gcs_interpret.py | MIT | 4,373 | 3a4f391c562b6ee0e16136effeec9a46e7a08ed5 | Python | py | |
import torch.nn as nn
def replace_layer_recursive(model, old_layer, new_layer):
for name, layer in model._modules.items():
if layer == old_layer:
model._modules[name] = new_layer
return True
elif replace_layer_recursive(layer, old_layer, new_layer):
return True
... | tttcls_google_gpc/gradcam/utils/find_layers.py | MIT | 1,262 | 3a4f4781d7a1265a49019963a128b971f8856656 | Python | py | |
import torch
from torch.nn import functional as F
from math import log, pi
def gaussian_log_p(x, mean, log_sd):
return -0.5 * log(2 * pi) - log_sd - 0.5 * (x - mean) ** 2 / torch.exp(2 * log_sd)
def gaussian_sample(eps, mean, log_sd):
return mean + torch.exp(log_sd) * eps
def bipartize(x):
# bipartize th... | functions.py | BSD-3-Clause | 3,493 | d7f04a8bd7b40144ebe08340709e2305cec55ea0 | Python | py | |
import numpy as np
import torch
from torch import nn
import sys
import re
import struct,logging
import itertools
import torchvision
import pandas as pd
import json
import numpy as np
import sys
import re
import struct
import subprocess
from subprocess import Popen
def open_or_fd(file, mode='rb'):
""" fd = open_or_... | src/embedding_net/normalize.py | MIT | 7,902 | 3a4fbd77e6ec2c77653b48cc480073a0eda57bf9 | Python | py | |
from typing import Callable
import torch
import torch.nn.functional as F
from ..utils import common_functions as c_f
def mcd_loss(out1, out2, dist_fn):
return dist_fn(F.softmax(out1, dim=1), F.softmax(out2, dim=1))
class MCDLoss(torch.nn.Module):
"""
Implementation of the loss function used in
[Ma... | src/pytorch_adapt/layers/mcd_loss.py | MIT | 1,550 | 3a4fc0db1afc90c3bf0a7a4bb44ea88bb4c7aa91 | Python | py | |
import math
import torch
from torch import nn, cat
import torchvision
class ConvRelu(nn.Module):
def __init__(self, in_: int, out: int, activate=True):
super(ConvRelu, self).__init__()
self.activate = activate
self.conv = nn.Conv2d(in_, out, 3, padding=1)
self.activation = nn.ReLU(... | style_transfer/mobile_model.py | MIT | 12,445 | 52e81f04c25dead5f29f5d490bc7213ac47f9f3b | Python | py | |
#! /usr/bin/env python3
from .base_metric_loss_function import BaseMetricLossFunction
import torch
import torch.nn.functional as F
from ..utils import loss_and_miner_utils as lmu
from ..reducers import AvgNonZeroReducer
class TripletMarginLoss(BaseMetricLossFunction):
"""
Args:
margin: The desired di... | src/pytorch_metric_learning/losses/triplet_margin_loss.py | MIT | 2,646 | 103f010c91ee79ca1eab8c181ec829ec673cb4cb | Python | py | |
import torch
import numpy as np
def print_header(msg):
print('===>', msg)
def to_np(t):
if t is None:
return None
elif t.nelement() == 0:
return np.array([])
else:
return t.detach().cpu().numpy()
def bger(x, y):
return x.unsqueeze(2).bmm(y.unsqueeze(1))
def get_sizes(... | lcp_physics/lcp/util.py | Apache-2.0 | 2,602 | d7beaaf30c3c1c5ba1dca2aa9fe0f42740736a5b | Python | py | |
from typing import Union, Tuple, Optional
from torch_geometric.typing import (Adj, Size, OptTensor, PairTensor)
import torch
from torch import Tensor
import torch.nn.functional as F
from torch.nn import Parameter
from torch_sparse import SparseTensor, set_diag
from torch_geometric.nn.conv import MessagePassing
from to... | torch_geometric/nn/conv/gatv2_conv.py | MIT | 11,364 | 707093282c0970cd677f4736f11bda4615c23912 | Python | py | |
import torch
import torch.nn as nn
class GroupLinearLayer(nn.Module):
"""Container module with an encoder, a recurrent module, and a decoder."""
def __init__(self, din, dout, num_blocks):
super(GroupLinearLayer, self).__init__()
self.w = nn.Parameter(0.01 * torch.randn(num_blocks,din,dout))
... | GroupLinearLayer.py | Apache-2.0 | 613 | 3a5036b45ca5ead85ea78ee647b37d140cea304c | Python | py | |
# Copyright (C) 2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | mmdet/apis/ote/extension/utils/runner.py | Apache-2.0 | 2,505 | 3a5038df0490e891f21a9cf1f78d30df7c8796de | Python | py | |
"""
read saved box and feature pt file, parse to VQA dataset format
"""
import os
import csv
import json
import numpy as np
import pandas as pd
import zarr
import collections
from tqdm import tqdm
import torch
from PIL import Image
from spacy.tokenizer import Tokenizer
import spacy
import string
import pickle
nlp = sp... | nih/preprocess_nih.py | Apache-2.0 | 9,786 | ff9156a1037d5d0b4360540e6f22a4c0e68c74f5 | Python | py | |
# Copyright (c) 2021, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root
# or https://opensource.org/licenses/BSD-3-Clause
import itertools
import os
import random
from pathlib import Path
import numpy as np
import pycuda
... | ai_economist/real_business_cycle/rbc/cuda_manager.py | BSD-3-Clause | 74,777 | 52b4503e9b65d5bfcaf5744d5b9da4e173053293 | Python | py | |
import re
import torch
import torchtext
import torchtext.data
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from utils.model import CNN
from utils.data import DataIterator
from utils.utils import clean_text
from captum.attr import LayerIntegratedGradients, TokenReferenceBase
from captum.att... | server/model.py | MIT | 12,315 | 3a506b70555bbfd49a1633b8afb390dafd6d9593 | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import weight_reduce_loss
def cross_entropy(pred,
label,
weight=None,
reduction='mean',
a... | mmdet/models/losses/cross_entropy_loss.py | Apache-2.0 | 9,659 | 3a50830d561a1d0f6067e03cf28ea5da07d79e2f | Python | py | |
# reference: https://github.com/open-mmlab/mmselfsup/tree/master/mmselfsup/models/algorithms
# modified from mmselfsup simclr.py
import torch
from openmixup.utils import print_log
from ..classifiers import BaseModel
from .. import builder
from ..registry import MODELS
from ..utils import GatherLayer
@MODELS.registe... | openmixup/models/selfsup/simclr.py | Apache-2.0 | 3,590 | 3a50977ca868eab8a22a5873514fb4912b78d9f5 | Python | py | |
import torch
from lhotse.features.kaldi import (
Wav2FFT,
Wav2LogFilterBank,
Wav2LogSpec,
Wav2MFCC,
Wav2Spec,
Wav2Win,
)
def test_wav2win():
x = torch.randn(1, 16000, dtype=torch.float32)
t = Wav2Win()
y = t(x)
assert y.shape == torch.Size([1, 100, 400])
assert y.dtype == ... | test/features/test_kaldi_layers.py | Apache-2.0 | 1,306 | 52ce0d2ee84db70e06defb416eb506cfad391b65 | Python | py | |
import torch
import torch.nn as nn
from onmt.Models import EncoderBase, RNNDecoderBase, NMTModel
def multimodal_model_class_by_key(key):
d = {
'hsm': HiddenStateMergeLayerMMM,
'fvtl': FirstViewThenListenMMM,
'gm': GeneratorMergeMMM,
'fvtl+gm': FirstViewThenListenFinallyViewMMM
... | onmt/modules/MultiModalModel.py | MIT | 9,821 | 3a50b358f0c77faa0a7576159e9b18cfee372551 | Python | py | |
#!/usr/bin/python
"""This is a short description.
Replace this with a more detailed description of what this file contains.
"""
import argparse
import os.path as osp
import os
import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from ... | submissions/available/NNSlicer/finetune/knockoff/adversary/adaptive.py | MIT | 2,425 | e97b6c7862a6edce5bc851a0912be8379de6d979 | Python | py | |
import pytest
import torch
from ignite.distributed.comp_models.base import _SerialModel
def test_serial_model():
_SerialModel.create_from_backend()
model = _SerialModel.create_from_context()
assert model.get_local_rank() == 0
assert model.get_rank() == 0
assert model.get_world_size() == 1
as... | tests/ignite/distributed/comp_models/test_base.py | BSD-3-Clause | 911 | 3a50bad6ffcca8cb44983d048a2a695659055f9d | Python | py | |
from torch import nn
import torch.nn.functional as F
from .adaptive_avgmax_pool import adaptive_avgmax_pool2d
class TestTimePoolHead(nn.Module):
def __init__(self, base, original_pool=7):
super(TestTimePoolHead, self).__init__()
self.base = base
self.original_pool = original_pool
b... | Models/test_time_pool.py | Apache-2.0 | 1,651 | 4261fb941919231d5bb0bb7c0d993eaa50eb0453 | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 15 05:31:35 2019
@author: mimbres
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.optim.lr_scheduler import StepLR
from torch.backends import cudnn
import numpy as np
import argpa... | train_lastfm_top50_regressor_mse.py | Apache-2.0 | 5,141 | 3a50cb3163fb1c86ed4953e3057d06068619a2d9 | Python | py | |
"""
ResNet Architectures
====================
This code adapted from torchvision.
Changes:
+ Load pretrained model & adapt afterwards FC with num_classes
+ Include num_classes
+ Include num_channels
"""
import torch
import torch.nn as nn
import os
try:
from torch.hub import load_state_dict_from_url
except Im... | model/backbones/resnet.py | Apache-2.0 | 14,892 | 3a50dd5b12e51d76a87174fa826ecb3586996fc8 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class FocalLoss(nn.Module):
def __init__(self, focusing_param=2, balance_param=0.25):
super(FocalLoss, self).__init__()
self.focusing_param = focusing_param
self.balance_param = balan... | loss/FocalLoss.py | MIT | 998 | 7cd291db39027483cc22abbc5a857cdc670ccce7 | Python | py | |
import torch
import torch.nn as nn
from gpt2.utils.fusing import LayerNorm
from gpt2.modeling import (PadMasking, FutureMasking, AttentionLayer, Past,
PositionalEmbedding, TokenEmbedding,
PositionwiseFeedForward)
from typing import Optional, Tuple, List
class Tran... | src/gpt2/modeling/transformer.py | Apache-2.0 | 4,087 | 3a50f35a6084f91ca39589bc3f538e7b80d11a3b | Python | py | |
from torch.utils.data import Dataset, DataLoader
import torch
import torch.nn as nn
import numpy as np
from torchvision import transforms
from PIL import Image
import os
from torchvision.models import resnet18, resnet34, resnet50, vgg16
# 数据集类 ======================================
class LWFDataset(Dataset):
def ... | 03-17 bak/my_class.py | MIT | 15,070 | fdb3ba33f950caace93585f8ef1afb1d59d2be8d | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
import numpy as np
def conv3x3(in_planes, out_planes, stride=1, groups=1):
"""... | habitat_baselines/standalone/models/resnet_encoder_odometer.py | MIT | 11,245 | a979819a3506a88d6f562457c0901437a12552ad | Python | py | |
import logging
logging.disable(logging.CRITICAL)
import numpy as np
import scipy as sp
import scipy.sparse.linalg as spLA
import copy
import time as timer
import torch
import torch.nn as nn
from torch.autograd import Variable
import copy
# samplers
import mjrl.samplers.trajectory_sampler as trajectory_sampler
import m... | mjrl/algos/batch_reinforce_er.py | Apache-2.0 | 11,683 | 128f81536ca703add79dc6bb1388509a5dcb6679 | Python | py | |
import os
import random
import torch
from torch.utils.data import Dataset
from torch.utils.data.dataset import T_co
from weakvtg import iox, bbox, anchors
from weakvtg.bbox import get_boxes_class
from weakvtg.padder import get_phrases_tensor, get_padded_examples, get_number_examples, get_max_length_examples, \
ge... | weakvtg/dataset.py | RSA-MD,Info-ZIP | 14,909 | 1e25d4518647fca044688b41ee77d10370389264 | Python | py | |
"""Ray-Horovod Elastic training unit tests.
This is currently not run on the Ray CI.
"""
from contextlib import contextmanager
import psutil
import os
import socket
import mock
import pytest
import ray
from horovod.common.util import gloo_built
from horovod.runner.elastic.discovery import HostDiscovery
from horovod.... | test/single/test_ray_elastic.py | Apache-2.0 | 12,488 | 3a514ad2ede0f08f616eb40803d6ae30e361ae72 | Python | py | |
import random
import torch
from torch import optim, nn
from torch.nn import functional as F
from torch.utils.data import DataLoader, Subset
from tqdm import tqdm
import librosa.display
from dataset import MelInversionDataset
from melgan import Generator, MultiScaleDiscriminator
import matplotlib as mpl
mpl.use('Agg... | train_melgan.py | MIT | 4,372 | 0392a7c1de574b929da50005c0930ba29b08b093 | Python | py | |
from collections import defaultdict
import pytorch_lightning as pl
import torch
from ...containers import Optimizers
from .. import utils as f_utils
def set_adapter_optimizers_to_pl(adapter, pl_optimizers):
if isinstance(adapter.optimizers, Optimizers):
keys = adapter.optimizers.keys()
adapter.o... | src/pytorch_adapt/frameworks/lightning/lightning.py | MIT | 2,807 | 28de527f781f69cbd11fb7933c78652305174e51 | Python | py | |
from .AudioCommon import *
from .DataBlock import *
from .DataAugmentation import *
import mimetypes
from fastai.vision import *
from fastai.text import *
import torchaudio
from torchaudio import transforms
# for jupyter Display
from IPython.display import Audio
class AudioSequenceItem(ItemBase):
def __init__(s... | src/data/DataBlockSequence.py | FTL | 2,963 | 7c43c6d66734cd41fa4ab153f99f84d81c4f43ea | Python | py | |
# file to create custom early stopping
import numpy as np
import torch
class EarlyStopping:
"""
A class used to save the best model before the train stops
due to the early stopping
...
Attributes
----------
counter : int
number of epochs after the checkpoint
mode : str, optiona... | vae/earlystopping.py | MIT | 3,896 | 3a5183eb2c8782d7b89ff1674c83ed48055f817d | Python | py | |
"""
Renders mesh using pytorch-NMR for visualization.
Directly renders with the same (weird) orthographic proj of HMR
(no perspective).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import neural_renderer as nr
import numpy as np
import torch
from torc... | src/util/render/nmr_renderer.py | BSD-2-Clause | 21,277 | 5e8324be45cf3c70ac72c8b0ccef6f3fa4db2131 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from functools import partial
from pvt import ( Mlp, Attention, PatchEmbed, Block, DropPath, to_2tuple, trunc_normal_,register_model, _cfg)
import math
import matplotlib.pyplot as plt
vis = False
def gumble_top_k(x, k, dim, T=1, p_value=1e-6):
#... | my_pvt14_4.py | Apache-2.0 | 22,994 | 42a6e704d43e8c87c09bd98be2a5f73416d9d9ec | Python | py | |
import math
import torch
from torch import nn
import torch.nn.functional as F
from models.components.mask_proposer import MaskProposer
import einops
class SegmentationHead(nn.Module):
"""
Simple convolutional head, using group norm.
Upsampling is in the Feature Pyramids Network style.
"""
def __init__... | models/components/segmentation_head.py | Apache-2.0 | 3,403 | 5f4c5132a7be4035474ab837e8228ccd6db2ae50 | Python | py | |
"""
Compute the gradient with PyTorch and the KFRA approximation with BackPACK.
"""
from torch.nn import CrossEntropyLoss, Flatten, Linear, Sequential
from backpack import backpack, extend, extensions
from backpack.utils.examples import load_mnist_data
B = 4
X, y = load_mnist_data(B)
print("# Gradient with PyTorch,... | examples/example_kfra.py | MIT | 775 | 3a51ef55dc9264c4bf41c31efca59a61158ed146 | Python | py | |
"""
Copyright 2020- Kai.Lib
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, software
distri... | test.py | Apache-2.0 | 4,159 | 3a5201b848085a869de5ea3aa45176234043c402 | Python | py | |
from deep_nlp.utils.utils import load_checkpoint
from deep_nlp.cnncharclassifier import charToTensor
from deep_nlp.cnncharclassifier import CNNCharClassifier
import torch
from torch.utils.data import DataLoader
from torch import optim
from torch.autograd import Variable
import torch.nn.functional as F
# from pytorch_li... | src/deep_nlp/utils/test.py | MIT | 3,587 | 12a0282f37e02283823240910fb46f348ddb0a38 | Python | py | |
import argparse
import json
import os
import random
import time
import numpy as np
import torch.distributed as dist
import torch.utils.data.distributed
from apex.fp16_utils import FP16_Optimizer
from apex.parallel import DistributedDataParallel
from tqdm import tqdm
from warpctc_pytorch import CTCLoss
from data.data_... | debug.py | MIT | 13,123 | f9a5b8cbc0c8bd065ad9798d033ccea8116ff6c9 | Python | py | |
# Copyright (c) 2021 Johns Hopkins University (Piotr Żelasko)
# Apache 2.0
import argparse
import logging
from functools import lru_cache
from pathlib import Path
from typing import List, Union
from torch.utils.data import DataLoader
from lhotse import CutSet, Fbank, FbankConfig, load_manifest
from lhotse.dataset i... | egs/gigaspeech/asr/simple_v1/asr_datamodule.py | Apache-2.0 | 14,517 | 3a520af931fdb886d29171dad63e3a7fbe741a83 | Python | py | |
from pathlib import Path
from typing import Callable, Tuple
import torch
from torch.utils.data import Dataset, DataLoader
import torch.nn.functional as F
from PIL import Image
# import cv2
import os
import numpy as np
import json
class HVGDataset (Dataset):
def __init__ (self, captions_file : Path, word_to_index_f... | utils/dataset.py | MIT | 2,313 | 03bd047e62ddd13f3b6e3db3363b0d9591e44fae | Python | py | |
import os
#os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]='0'
import sys
import argparse
from utils import Timer
from utils import Logger
from utils import MixUp
import shutil
import torchvision.transforms as transforms
from tensorboardX import SummaryWriter
import time
import torch
pa... | src/train_i3d.py | Apache-2.0 | 16,178 | d76828bfbfd6d476b0d9315d504714da7ece252f | Python | py | |
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision.models as models
from torch.autograd import Variable
import numpy as np
from model.utils.config import cfg
from model.rpn.rpn import _RPN
from model.roi_layers import ROIAlign, ROIPoo... | FRcnn_pytorch/lib/model/faster_rcnn/faster_rcnn.py | BSD-3-Clause | 5,363 | fcb1442ca15eb4ae2dd741af44b9fb2a60ea4f0c | 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... | tuframework/training/network_training/nnUNet_variants/architectural_variants/nnUNetTrainerV2_noDeepSupervision.py | Apache-2.0 | 9,047 | 3a525406f150dc1f82e5808a3c5df994190f8c9a | Python | py | |
import torch.utils.data as data
from PIL import Image
import os
import os.path
import torch
import numpy as np
import torchvision.transforms as transforms
from libs.transformations import euler_matrix
import argparse
import time
import random
import numpy.ma as ma
import copy
import math
import scipy.misc
import scipy.... | dataset.py | MIT | 23,485 | 80520c435e829e03128c7637e1ea9fd4470b379d | Python | py | |
from torch.utils.data import Dataset, DataLoader
import numpy as np
import scipy.io as sio
from PIL import Image
import os
class KITTIdataset(Dataset):
"""KITTIdataset"""
def __init__(self, list_file='train.txt', data_root_path='/home/gaofeng/datasets/processed_data/kitti/', img_size=[128, 416], bundle_size=3... | final_project/LKVOLearner/src/KITTIdataset.py | MIT | 2,476 | 3a52ac8336f0f51a2734ae9ad9cecc9acb5600fe | Python | py | |
'''
Training script for CIFAR-10/100
Copyright (c) Wei YANG, 2017
'''
from __future__ import print_function
import argparse
import os
import shutil
import time
import random
import fcntl
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
impor... | cifar_imagenet/cifar_horesnet_for_short_training_temp.py | Apache-2.0 | 23,216 | cc1cf84fab67166973af7e2d3e292e2da1b6f4c8 | Python | py | |
import torch
from gtd.ml.torch.utils import GPUVariable
from torch.nn import Module
from gtd.ml.torch.utils import conditional
def tile_state(h, batch_size):
"""Tile a given hidden state batch_size times.
Args:
h (Variable): a single hidden state of shape (hidden_dim,)
batch_size (int)
... | third-party/gtd/gtd/ml/torch/recurrent.py | Apache-2.0 | 1,540 | 52faf466bc0de28cc04e07e79dc61586496ef4fe | Python | py | |
from __future__ import absolute_import
from torchvision.transforms import *
from PIL import Image
import random
import math
import pdb
import numpy as np
class RandomVerticalCrop(object):
def __init__(self, height,width):
self.height = height
self.width = width
def __call__(self, img):
... | reid/utils/data/transforms.py | BSD-2-Clause | 3,962 | 3a52c82f0907508ff35c3a3831b38100f6dcba85 | Python | py | |
import math
import numbers
import random
import numpy as np
import torchvision.transforms.functional as tf
from PIL import Image, ImageOps
class Compose(object):
def __init__(self, augmentations):
self.augmentations = augmentations
self.PIL2Numpy = False
def __call__(self, img, mask):
... | augmentations/augmentations.py | MIT | 8,733 | d708aebb24e0c536a2175b87a64bc9969479ca7c | Python | py | |
# Standard modules
from __future__ import print_function, division
import os
import pickle
import argparse
import pandas as pd
import numpy as np
# Pytorch for data set
import torch
from torch.utils.data import Dataset, DataLoader
# RDkit
from rdkit import Chem
# Molecules dataset definition
from molecules_dataset ... | process_aqsoldb_npz.py | MIT | 5,679 | 3a531aa3a6f61d1857f52ffad7e73c09598c34fe | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import copy
import logging
import ml.rl.types as rlt
import torch
import torch.nn.functional as F
from ml.rl.parameters import TD3ModelParameters
from ml.rl.tensorboardX import SummaryWriterContext
from ml.rl.torch_utils imp... | ml/rl/training/td3_trainer.py | BSD-3-Clause | 11,011 | 42470a8637aac14e822729011259617a390982e6 | Python | py | |
import torch
import einops
from torch import Tensor
from typing import Optional
class MaskedTensor(object):
def __init__(self, data:Tensor, mask:Optional[Tensor]=None):
self.data = data
self.shape = data.shape
self.mask = mask
def to(self, device):
return MaskedTensor(self.data.to(device), se... | utils/masked_tensor.py | Apache-2.0 | 993 | 3a533616747d45115c29d01376d5019e13e66109 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.