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 cv2
import torch
import argparse
from torch.nn import functional as F
from model.RIFE_HD import Model
import warnings
warnings.filterwarnings("ignore")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch.set_grad_enabled(False)
if torch.cuda.is_available():
torch.backends.c... | inference_img.py | MIT | 2,180 | 24a9ab0d3a52f5768f8d97b151228eec69e4bd0e | Python | py | |
from src.tiramisu.datasets import cilia, joint_transforms
from src.tiramisu.utils import training
from src.tiramisu.models import tiramisu
import adabound
import torch
from torchvision import transforms
from torch.utils import data
from imageio import imwrite, imread
from pathlib import Path
import os
import numpy as... | TrainTiramisu.py | MIT | 6,719 | 3a1bf3548f1d37a32efe434c16faef2623d8f717 | Python | py | |
# Copyright 2021 The BladeDISC 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 law or ... | pytorch_blade/tests/mlir/test_disc_reshape.py | Apache-2.0 | 6,808 | 3a1c024447afc064d1c2f77121c2f3e49fc4b90e | Python | py | |
import torch
def get_device():
is_cuda_available = torch.cuda.is_available()
if is_cuda_available:
print(f"Using GPU: {torch.cuda.get_device_name()}, using this!")
return torch.device("cuda:0" if is_cuda_available else "cpu") | torchwt/engine/utils/device.py | MIT | 253 | e97a94d5a9fae89a99458249c24a468ba8a400e7 | Python | py | |
import torch
import numpy as np
from data_utils import helper
from data_utils import pose_features
# Simply take the difference between all coordinate pairs of all joints.
# The result is of shape (N, J * D)
def coordinate_difference(poses, labels):
return (poses - labels).reshape(poses.shape[0], -1)
# The euc... | evaluation/errors.py | MIT | 2,369 | 3a1c0b442a32a4750fc3b191e1c2d0f9692c36db | Python | py | |
from typing import Any, Dict, Tuple, List, Callable, Optional, Union, Set
from collections import defaultdict
import copy
import torch
from torch.fx import (
GraphModule,
Proxy,
map_arg
)
from torch.fx.graph import (
Graph,
Node,
)
from torch.fx.node import Argument
from .quantization_types import P... | torch/ao/quantization/fx/convert.py | Intel | 30,460 | b27b68bed8b3970583c9bfaef096945af671749a | Python | py | |
import torch
import torch.nn as nn
from torch.optim import Adam
from torch.utils.data import DataLoader, TensorDataset
import numpy as np
from torch.utils.tensorboard import SummaryWriter
from utils import *
import os
from config import *
def get_network(in_dim, out_dim):
net = nn.Sequential(
nn.Linear(in... | model.py | MIT | 13,669 | 3a1c32bc4fa8806f662486944913f8448e87f6db | Python | py | |
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
from typing import Iterable, Optional
import torch
from jina import DocumentArray, Executor, requests
from jina_commons.batching import get_docs_batch_generator
from PIL import Image
from torchvision import tran... | jinahub/encoders/image/AudioCLIPImageEncoder/audioclip_image.py | Apache-2.0 | 5,497 | 3a1c4506ee5cef2352a85a2f084736bf87b27039 | 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/helpers/boring_model.py | Apache-2.0 | 5,760 | 3a1c4f30fe1f4dd134b87961e00c04e2f2025e71 | Python | py | |
from collections.abc import Sequence
import mmcv
import numpy as np
import torch
from mmcv.parallel import DataContainer as DC
from ..builder import PIPELINES
def to_tensor(data):
"""Convert objects of various python types to :obj:`torch.Tensor`.
Supported types are: :class:`numpy.ndarray`, :class:`torch.T... | mmseg/datasets/pipelines/formating.py | Apache-2.0 | 10,928 | 52f46674362d79c09132a96c7a43eada4c3e03fe | Python | py | |
import os
import time
import torch
from torch.backends import cudnn
def set_device(global_gpu_index, is_cpu=False, pci_device_order=True):
"""Set use GPU or CPU Device
set using GPU or CPU Device(instead of CUDA_VISIBLE_DEVICES).
set also CUDNN.
Args:
global_gpu_index (int): using gpu numbe... | kunai/torch_utils/cuda.py | MIT | 1,854 | 1ea62e7cb1addf2ba7d83a79bc2995be30994d30 | Python | py | |
import os.path as osp
import torch
import torch.nn.functional as F
from torch_geometric.datasets import Planetoid
import torch_geometric.transforms as T
from torch_geometric.nn import GATConv
import os
os.chdir('../../..')
dataset = 'Cora'
path = osp.join('data', dataset)
dataset = Planetoid(path, dataset, T.Normalize... | examples/gat.py | MIT | 2,102 | 42aa5a40307ffd635fcf3ad16798ff1aac5d0cc8 | Python | py | |
import torch
class UnifNegativeSampler():
def __init__(self, triples, entity_dict_len, relation_dict_len, node_lut=None, device=torch.device('cuda:0')):
# tensor(len,3)
self.triples = triples
self.entity_dict_len = entity_dict_len
self.relation_dict_len = relation_dict_len
... | cogkge/core/sampler.py | MIT | 8,519 | 5e69400cf6db85a0b97bfd5ed529481d1396c507 | Python | py | |
# Copyright (c) 2020 Horizon Robotics and ALF Contributors. 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... | alf/networks/projection_networks.py | Apache-2.0 | 26,539 | a9577ba34f3858f5a322e7fe8cca4ceed6c7daec | Python | py | |
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from math import sqrt, sin, cos
from torch.autograd import Variable
Tensor = torch.Tensor
class MultiHeadAttention(nn.Module):
"""
The nn.Module that implements the Multihead attention operation
For more infor... | src/sub_layers.py | MIT | 5,126 | e9852464c6aeab5fc4e7bf6d63aede2b42a97db1 | Python | py | |
"""Fourier transform, Wavelet transform, and related functions
Fourier transform
* fftnc
* ifftnc
Wavelet transform
* reformat_subband2array
* forward
* pyramid_backward
* add
* sub
* mul_subbandwise
* threshold_subbandwise
* add_... | util/transform.py | MIT | 9,950 | e97765d933e201e6a8e630c99e42d384e227d040 | Python | py | |
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# Copyright (c) 2021 scart97
from string import ascii_lowercase
from urllib.error import HTTPError
import pytorch_lightning as pl
import torch
import torchaudio
from torchaudio.datasets.utils i... | tests/quartznet/test_module_qn.py | MIT | 2,674 | f944ffd547be5e5a035902c163185a31ef5e5b4f | Python | py | |
import torch
import time
import sys
import torch
import torch.distributed as dist
from utils import AverageMeter, calculate_accuracy
def val_epoch(epoch,
data_loader,
model,
criterion,
device,
logger,
tb_writer=None,
d... | validation.py | MIT | 2,912 | b2a1a85ba1fcbba798619f94266a57b79af07a28 | Python | py | |
import numpy as np
import torch
import torch
import torch.nn as nn
import dgl
from model.global_model import ConvEncoder
from model.local_model import UtterEncoder
class Graph_DialogRe(nn.Module):
def __init__(self, config, vocab):
super().__init__()
self.config = config
self.vocab = voc... | model/model.py | MIT | 2,269 | d705a2caf115207f3c164095c0914fbbd4fa2243 | Python | py | |
import argparse
import os
import os.path as osp
import sys
from collections import OrderedDict
import pprint
import random
import pdb
import torch
from torch import nn
from torch.backends import cudnn
from torch.utils.data import DataLoader
import numpy as np
import time
from tensorboardX import SummaryWriter
import _... | tools/train_with_cpu.py | MIT | 8,447 | 3a1ce6efa2f81a824b291fd1c5ad3fbfdf335d4f | Python | py | |
import logging
import pickle
import torch
from pytorch_lightning.utilities.imports import _TORCH_GREATER_EQUAL_1_8
log = logging.getLogger(__name__)
if torch.distributed.is_available():
from torch.distributed import Backend, broadcast, get_backend, get_rank, GroupMember
# The code underneath is taken from PyTo... | pytorch_lightning/overrides/torch_distributed.py | Apache-2.0 | 3,709 | 3a1ceca7d951c6ac1d84ea5f4e2494d3935de419 | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
# -*- coding: utf-8 -*-
"""
# @Time : 2019/5/25
# @Author : Jiaqi&Zecheng
# @File : model.py
# @Software: PyCharm
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.utils
from torch.au... | src/models/model.py | MIT | 38,839 | 3a1cf1110d4a2c35f4e3418b611320f45b3b4e09 | Python | py | |
import math
import torch
import torch.nn as nn
from torch.nn import TransformerEncoder, TransformerEncoderLayer, Linear, TransformerDecoder, TransformerDecoderLayer
from torch.nn.modules.normalization import LayerNorm
# from torch.nn import xavier_uniform_
from quaesita.PositionalEncoding import PositionalEncoding
# s... | quaesita/model.py | MIT | 11,272 | 4560f6fc40e2ed688f579deea261cfcaf34723e9 | 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.
r"""Box decomposition container."""
from __future__ import annotations
from typing import List, Union
import torch
f... | botorch/utils/multi_objective/box_decompositions/box_decomposition_list.py | MIT | 4,477 | 52a408a948fccfc8bff5c2a325d2b7406dac148e | Python | py | |
# limit the number of cpus used by high performance libraries
import os
import warnings
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["VECLIB_MAXIMUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"]... | application/main/infrastructure/handlers/track.py | MIT | 16,489 | 5fa1160d2d161cad4ba5d314a7202b5577172a17 | Python | py | |
# Copyright 2018 The Google AI Language Team Authors and
# The HuggingFace Inc. team.
# 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 Lice... | nemo/collections/nlp/data/token_classification/token_classification_dataset.py | Apache-2.0 | 13,473 | 3a1d1f3c6df489f6514828bcfc920072968ed94c | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from ...ops.roiaware_pool3d import roiaware_pool3d_utils
from ...utils import common_utils, loss_utils
class PointHeadTemplate(nn.Module):
def __init__(self, model_cfg, num_class):
super().__init__()
self.model_cfg = model_cfg
... | pcdet/models/dense_heads/point_head_template.py | Apache-2.0 | 9,854 | 346d3353222b5ace8ab2fe3be48a4794d8795afb | Python | py | |
import argparse
import distutils
from typing import Any, List, Sequence, Tuple, Dict
import torch
import torch.nn as nn
import torch.nn.functional as F
from cassle.losses.dino import DINOLoss
from cassle.methods.base import BaseMomentumModel
from cassle.utils.momentum import initialize_momentum_params
from cassle.util... | cassle/methods/dino.py | MIT | 10,404 | 3a1d361d2bb26dfc58a015ad58b52274c61e5a1c | Python | py | |
"""
(선택) PyTorch 모델을 ONNX으로 변환하고 ONNX 런타임에서 실행하기
========================================================================
이 튜토리얼에서는 어떻게 PyTorch에서 정의된 모델을 ONNX 형식으로 변환하고 또 어떻게 그 변환된 모델을
ONNX 런타임에서 실행할 수 있는지에 대해 알아보도록 하겠습니다.
ONNX 런타임은 ONNX 모델을 위한 엔진으로서 성능에 초점을 맞추고 있고 여러 다양한 플랫폼과 하드웨어(윈도우,
리눅스, 맥을 비롯한 플랫폼 뿐만 아니라 CPU, GPU ... | advanced_source/super_resolution_with_onnxruntime.py | BSD-3-Clause | 10,074 | 7c2886342f52120ba012cfa0144457fb51d144b8 | Python | py | |
from math import pi
from typing import Optional, Union
import torch
from torch import Tensor
from torch.nn import Module, Parameter
from kornia.color import hsv_to_rgb, rgb_to_grayscale, rgb_to_hsv
from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_COLOR_OR_GRAY, KORNIA_CHECK_IS_TENSOR
from kornia.utils.helpers... | kornia/enhance/adjust.py | ECL-2.0,Apache-2.0 | 52,347 | 3a1d8df13f81f6c87dba92abdef73774e586b7c8 | Python | py | |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time, random, sys
import sklearn.metrics
from sklearn.model_selection import KFold
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim as optim
from torch.utils.data import DataLoader
sys.path.append('... | src/train_model1.py | MIT | 8,239 | 3a1d99aabe8e2f27dcb0e754bde092948ab63349 | Python | py | |
"""Run validation test for paragraph_text_recognizer module."""
import argparse
import time
import unittest
import pytorch_lightning as pl
import torch
from im2latex.data import Im2Latex100K
from im2latex.im2latex_inference import Im2LatexInference
_TEST_BLEU_SCORE = 0.5951
_TEST_CHARACTER_ERROR_RATE = 0.2506
_TEST_... | im2latex/evaluation/evaluate_im2latex_inference.py | MIT | 1,405 | e960628461b1234697587e790de2ba02a5292d2a | Python | py | |
from collections import namedtuple
import torch
torch.manual_seed(42)
Input = namedtuple("Input", ["preds", "target"])
NUM_BATCHES = 10
BATCH_SIZE = 16
NUM_CLASSES = 10
binary_prob_inputs = Input(
preds=torch.rand(NUM_BATCHES, BATCH_SIZE),
target=torch.randint(high=2, size=(NUM_BATCHES, BATCH_SIZE)),
)
bina... | tests/input_datas.py | MIT | 1,232 | 3a1da54b82078ffa238ef010b1ac64ed260f9e2a | Python | py | |
import configparser
import os
import numpy as np
import torch as th
class Config(object):
def __init__(self, file_path, model, dataset, task, gpu):
conf = configparser.ConfigParser()
data_path = os.getcwd()
if gpu == -1:
self.device = th.device('cpu')
elif gpu >= 0:
... | openhgnn/config.py | Apache-2.0 | 20,525 | d7f6078fc30e80433dfa22867d533485a59357d1 | Python | py | |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# ------------------------------------------------------------------------------
from __future__ import absolute_import
from __futu... | MULTITASK_FILES/KEYPOINTS_FILES/surgery-hand-detection-new/deep-high-resolution-net.pytorch/lib/core/loss.py | MIT | 6,573 | e9ca22c8f2cd8c78c4c8310ea1442a936e85c01e | Python | py | |
"""The data layer used during training to train a Fast R-CNN network.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch.utils.data as data
from PIL import Image
import torch
from model.utils.config import cfg
from roi_data_layer.minibatch i... | lib/roi_data_layer/roibatchLoader.py | MIT | 8,939 | d73c0ebad541f5fbd12e11aed87589e9f2beb5b4 | Python | py | |
"""
PyTorch interface for computing KID.
"""
import os
import random
import time
import numpy as np
import tensorflow as tf
import torch
from torch_mimicry.datasets.image_loader import get_dataset_images
from torch_mimicry.metrics.inception_model import inception_utils
from torch_mimicry.metrics.kid import kid_utils
... | torch_mimicry/metrics/compute_kid.py | MIT | 9,496 | 3a1df22b08aef2a84df29ccde9449dfb42a26c33 | Python | py | |
import torch
import src.utils.rotation_conversions as geometry
from .smpl import SMPL, JOINTSTYPE_ROOT
# from .get_model import JOINTSTYPES
JOINTSTYPES = ["a2m", "a2mpl", "smpl", "vibe", "vertices"]
class Rotation2xyz:
def __init__(self, device):
self.device = device
self.smpl_model = SMPL().eval... | src/models/rotation2xyz.py | MIT | 3,365 | 3a1dfd381a33fbcca6d8f8e6f6023ac9136e6cd4 | Python | py | |
import os
import torch
import joblib
from cdqa.reader import BertProcessor, BertQA
from cdqa.utils.download import download_squad
import time
start_time = time.time()
print(" \n\n Download SQuAD datasets")
download_squad(dir='./data')
print("--- %s seconds ---" % (time.time() - start_time))
print(" \n\n Preprocess S... | trainer_reader_on_irs_data.py | Apache-2.0 | 2,329 | 3a1e0f054c90a541e7a6e03a9b4da65bc4e04295 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
class QNet(nn.Module):
def __init__(self, num_outputs):
self.num_outputs = num_outputs
super(QNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=4,
out_channels=32,
... | 3-atari/1-dqn/model.py | MIT | 1,382 | 4243e6dc670429e81f5ec0a352ad6c14eeb24f21 | Python | py | |
# Owner(s): ["module: nestedtensor"]
import torch
import torch.nn
import unittest
from torch.testing._internal.common_device_type import (
dtypes,
dtypesIfCUDA,
instantiate_device_type_tests,
skipMeta,
)
from torch.testing._internal.common_utils import TestCase, IS_FBCODE, run_tests
from torch import n... | test/test_nestedtensor.py | Intel | 17,511 | 709577301345e54f52eb006e7655a0168016f5ec | Python | py | |
# Copyright (c) 2020 Mobvoi Inc (Binbin Zhang)
#
# 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... | wenet/transformer/cmvn.py | Apache-2.0 | 1,487 | 3a1e7457fd3788d9a7e031e96517505a65925102 | Python | py | |
import numpy as np
import torch
from torch.distributions import Dirichlet
from torch.distributions import Categorical
from torch.distributions import Bernoulli
from torch.distributions import Beta
from torch.distributions import Normal
from torch.distributions import Uniform
from torch.distributions import Gamma
from ... | sims/cb/cytofpy/attempt1/simdata.py | MIT | 2,195 | 3a1e8ac68ac85d5800dbd7bdcf78ac49a80b4047 | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
class Decoder(nn.Module):
def __init__(self, num_classes, backbone, BatchNorm):
super(Decoder, self).__init__()
if backbone == 'resnet' or backbone == 'drn':
... | modeling/decoder.py | MIT | 2,264 | 3a1e9390975bde66826e7738468ee60b3b8902f9 | Python | py | |
#!/usr/bin/env python3
import torchvision.models as models
import eagerpy as ep
from foolbox import PyTorchModel, accuracy, samples
import foolbox.attacks as fa
import numpy as np
if __name__ == "__main__":
# instantiate a model (could also be a TensorFlow or JAX model)
model = models.resnet18(pretrained=True... | Chapter2/attack_robustness/multiple_attacks_pytorch_resnet18.py | MIT | 2,310 | b2c2a2d213483db2fa849f055469f3dc1a9ba791 | Python | py | |
#!/usr/bin/env python3
# This file is covered by the LICENSE file in the root of this project.
import numpy as np
from scipy import signal
import torch
import torch.nn as nn
import torch.nn.functional as F
import __init__ as booger
class LocallyConnectedXYZLayer(nn.Module):
def __init__(self, h, w, sigma, nclass... | obstacle-detection/model/tasks/semantic/postproc/CRF.py | MIT | 5,183 | 3a1e9f661d46f64e869fbcedac7ab384d5a7f7bf | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 64, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(64, 32, kernel_size=3, padding=1)
self.conv3 = nn.Conv2d(32, 16, kernel_size=3, padding=1)
self.fc1 ... | net.py | MIT | 666 | 3a1ea0eb33733be6e81f363102b5ac95bcb0216f | Python | py | |
from __future__ import absolute_import, division, print_function
import random
import pandas as pd
from pytorch_pretrained_bert.tokenization import BertTokenizer
from torch.nn import MSELoss
from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,
TensorDataset)
from t... | finbert/finbert.py | Apache-2.0 | 25,043 | 3a1ea40446035ca958525cf293da0f48a7879cd1 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
# Copyright (c) 2020, Emanuele Bugliarello (@e-bug).
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import json
import random
import logging
import numpy as np
import tensorpack.d... | volta/datasets/concept_cap_dataset.py | MIT | 24,149 | 12c83024ad936562da395b979323b88f0ea2684f | Python | py | |
import numpy as np
import torch
from torchvision.utils import make_grid
from base import BaseTrainer
class Trainer(BaseTrainer):
"""
Trainer class
Note:
Inherited from BaseTrainer.
"""
def __init__(self, model, loss, metrics, optimizer, resume, config,
data_loader, valid_... | trainer/trainer.py | MIT | 4,720 | 28f2dc63fb394da6606f9911e68dd4c51cc79070 | Python | py | |
# encoding: utf-8
import argparse
import os
import logging
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
from torch.autograd import Variable
from torch.utils.data import DataLoader
import torchvision.transforms as trans
import utils.transform... | Initial_stage/predict.py | MIT | 4,819 | 4b03ac8a8676d0ad689b4b2398e7798355e13d8c | Python | py | |
# import
import torch.nn as nn
from functions import QuantisedImportanceMask
"""
ImportanceMap
Returns masked bitmap and soft importance map for Entropy loss
Args:
input_dim (int) : channel dimension of input feature map
n (int) : number of encoder output channels or bottlenec... | modules/importance_map/importance_map.py | CC0-1.0 | 1,843 | 3a1ee645186df5c7c1c3945110333f69e99214ca | Python | py | |
from ogb.graphproppred import PygGraphPropPredDataset
from torch_geometric.data import DataLoader
def fetch_dataset(config):
# automatic data loading and splitting
dataset = PygGraphPropPredDataset(name=config.dataset)
if config.feature == "full":
pass
elif config.feature == "simple":
... | neural-network/model/data_loader.py | MIT | 1,233 | 52c1705b1b175dfd3b7ea4afe0e5200f79e4dbb7 | 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 math
from collections import OrderedDict
import contextlib
import logging
import torch
import torch.nn.functional as F
from fairseq im... | fairseq/criterions/wav2vec_criterion_bimodal.py | MIT | 11,360 | 28b106de1f5eab6b8fb4df25a0e3bc027740da4d | Python | py | |
import gym
from gym import wrappers
import gym_ple
import numpy as np
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn.utils import clip_grad_norm_
from tensorboardX import SummaryWriter
from PIL import Image
import os
LOG_D... | catcher/DQN_torch.py | MIT | 14,941 | 3a1f1eccf2439cf9e0de824252a6c8a4adb6f1d9 | Python | py | |
from torchtext import data
TEXT = data.Field()
LABELS = data.Field()
train, val, test = data.TabularDataset.splits(
path='~/chainer-research/jmt-data/pos_wsj/pos_wsj', train='.train',
validation='.dev', test='.test', format='tsv',
fields=[('text', TEXT), ('labels', LABELS)])
print(train.fields)
print(le... | test/data.py | BSD-3-Clause | 694 | 105e697c40086d3518d2371456e5984e670425ce | Python | py | |
# Copyright (c) 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, so... | tests/test_global_mutual_information_loss.py | Apache-2.0 | 5,244 | a919396e3e497fe0e944e0bd1255f6da922b5751 | Python | py | |
#! /usr/bin/python3
import argparse
import logging
import os
import sys
import platform
from collections import namedtuple
import torch
from torch.utils.data import DataLoader, SequentialSampler
from tqdm import tqdm
from modeling_bertabs import BertAbs, build_predictor
from transformers import BertTokenizer
from ut... | summarization/bertabs/run_summarization.py | Apache-2.0 | 8,325 | 45748a3f65d47ed96b4d2e76efa1a91f1cd7037e | Python | py | |
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | nnutils/mesh_net.py | Apache-2.0 | 31,532 | 427ab0c18f77a439886477e8223bc5bec8da1deb | Python | py | |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
import torch
import torch.nn as nn
from yolox.utils.boxes import order_corners, minimum_outer_rect
class IOUloss(nn.Module):
def __init__(self, reduction="none", loss_type="iou"):
super(IOUloss, sel... | yolox/models/losses.py | Apache-2.0 | 1,750 | 3a1f5e7d8c555aa7832ccd649c846e087c3c1ebd | Python | py | |
from typing import Tuple
import torch
from .flow import Flow
from overrides import overrides
@Flow.register("nonauto-planar")
class NonAutoPlanarFlow(Flow):
def __init__(self, input_size: int) -> None:
super().__init__()
self._w = torch.nn.Parameter(torch.Tensor(input_size, 1).uniform_())
... | vae_lm/models/base/flows/planar_flow.py | Apache-2.0 | 2,571 | 3a1f66368871272ee1864c7633683e340ff3df3e | Python | py | |
# Owner(s): ["module: tests"]
import torch
import numpy as np
import math
from itertools import product, chain
from numbers import Number
import random
import unittest
from torch._six import inf, nan
from torch.testing._internal.common_utils import (
TestCase,
run_tests,
torch_to_numpy_dtype_dict,
nu... | test/test_unary_ufuncs.py | Intel | 63,743 | 3a1f77e37ca647385646fa55db137cdbae0f847d | Python | py | |
import torch
from torch._C import device
import torchvision
import torchvision.transforms as transforms
from torchvision import datasets, models
import matplotlib
import pickle
import matplotlib.pyplot as plt
import numpy as np
import os
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functio... | road.py | MIT | 7,176 | ff34a7f9fb6a83eb6813a0cccccb34e04890caff | Python | py | |
from ctranslate2.converters import utils
from ctranslate2.converters.converter import Converter
from ctranslate2.specs import common_spec
from ctranslate2.specs import transformer_spec
class OpenNMTPyConverter(Converter):
"""Converts models generated by OpenNMT-py."""
def __init__(self, model_path):
... | python/ctranslate2/converters/opennmt_py.py | MIT | 6,201 | 652562095b9f8180d56016cf96e94106f8d715c5 | Python | py | |
from contextlib import contextmanager
from datetime import timedelta
from enum import Enum
import faulthandler
from multiprocessing import Manager
from io import StringIO
import os
import sys
import tempfile
import threading
import time
import unittest
import logging
import traceback
import types
from typing import Na... | torch/testing/_internal/common_distributed.py | Intel | 23,169 | 458c8e63967a962d41e2cc86965bfb51afb41a28 | Python | py | |
""" RetinaNet / EfficientDet Anchor Gen
Adapted for PyTorch from Tensorflow impl at
https://github.com/google/automl/blob/6f6694cec1a48cdb33d5d1551a2d5db8ad227798/efficientdet/anchors.py
Hacked together by Ross Wightman, original copyright below
"""
# Copyright 2020 Google Research. All Rights Reserved.
#
# Licen... | effdet/anchors.py | Apache-2.0 | 17,812 | 3a1ff865ae37aa75198f3885e1941466a532c498 | Python | py | |
# ------------------------------------------------------------------------
# SeqFormer Sequence Segmentation.
# ------------------------------------------------------------------------
# Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR)
# Copyright (c) 2020 SenseTime. All Rights Reser... | models/segmentation.py | MIT | 32,774 | 28f3844227191103b00ef0a9eb290f05576a02ca | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
r"""Importing this file includes common utility methods and base clases for
checking quantization api and properties of resulting modules.
"""
import torch
import torch.... | pytorch-frontend/torch/testing/_internal/common_quantization.py | MIT | 47,976 | 3a20104e097d19e89ffeaf39d0ed47318adb12df | Python | py | |
import torch
import torch.nn as nn
LATENT_CODE_SIZE = 128 # size of the Z vector
SDF_NET_BREADTH = 256 # size of the w vector
amcm = 24 # Autoencoder Model Complexity Multiplier
class ModelE(nn.Module):
def __init__(self):
super(ModelE, self).__init__()
self.add_module('encoder', nn.Sequential(
... | modele.py | MIT | 995 | 3a201e64ee9b083ad2479611a5a273a2eec19d77 | Python | py | |
from __future__ import print_function
import sys
import h5py
import numpy as np
import cv2
import torch
import torch.utils.data as data
from utils import np_skew_symmetric
def collate_fn(batch):
batch_size = len(batch)
numkps = np.array([sample['xs'].shape[1] for sample in batch])
cur_num_kp = int(numkps.... | thirdparty/implementation/oanet/core/data.py | Apache-2.0 | 6,882 | ff7aa3f1200d85f031fba6ef7e57aa123119c82f | Python | py | |
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | xirl/train_policy.py | Apache-2.0 | 6,499 | e94236a137e5040c273a36f850fe52333dc18e27 | Python | py | |
import torch.nn as nn
# Number of channels in the training images. For color images this is 3
nc = 3
# Size of z latent vector (i.e. size of generator input)
nz = 100
# Size of feature maps in generator
ngf = 64
# Size of feature maps in discriminator
ndf = 64
# Generator Code
class Generator(nn.Module):
... | Homework3/-GAN_source_code/Model.py | MIT | 2,468 | b28904ef1a4250ee4106225436b0efe3c767a078 | Python | py | |
import torch
import torch.nn as nn
from torchvision.datasets.vision import VisionDataset
from PIL import Image
import os, sys, math
import os.path
import torch
import json
import torch.utils.model_zoo as model_zoo
from Yolo_v2_pytorch.src.utils import *
from Yolo_v2_pytorch.src.yolo_net import Yolo
from Yolo_v2_pytorc... | lib/place_model.py | MIT | 16,931 | 428eac96b1905cf94fc5b1f167e60c8c46762f48 | Python | py | |
import os, torch, random, re, sys, time
import numpy as np
import random
import pandas as pd
from typing import List, Tuple
from torch.nn.utils.rnn import pad_sequence
from utils.logger import LOGGER
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def get_device():
return device
def calc_... | utils/utils.py | MIT | 6,340 | 3a209b74af1c3ab9d5385bae24d50ade334ae7d2 | Python | py | |
import colossalai
import colossalai.nn as col_nn
import torch
from colossalai.context import ParallelMode
from colossalai.core import global_context as gpc
from colossalai.utils import get_current_device, print_rank_0
from colossalai.global_variables import tensor_parallel_env as tp_env
class MLP(torch.nn.Mo... | features/tensor_parallel/run.py | Apache-2.0 | 2,455 | 5fb9f87267ce78b43b28caa2148bf6981ddf5709 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from modules.networks import TriResNet
class ProbabilisticModel(nn.Module):
def __init__(self):
super(ProbabilisticModel, self).__init__()
self.dist = None
def _avg_gaussian_log_prob(self, xt, mu, sigma):
... | modules/models.py | MIT | 26,575 | 709dc1452040530611463df841e79dc700f17ffd | Python | py | |
# Copyright 2019 The FastEstimator 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 appl... | fastestimator/backend/load_model.py | Apache-2.0 | 3,572 | 7c0eda0014a395c8a8dc7c445ae88864b3c69cc0 | Python | py | |
import torch.nn as nn
from torchvision.models import resnet
from torchvision.models import vgg
from torchvision.models import mobilenet_v2
def build_resnet50(cfg):
backbone = resnet.resnet50(pretrained=True)
features = list(backbone.children())[:-2] # For ResNet-101 drop avg-pool and linear classifier
re... | lib/modeling/components/build_backbone.py | MIT | 1,201 | 42a3307e380a4ea7fa152b34105ee9421d4aa58a | Python | py | |
from typing import List, Type
from torch import Tensor, nn
class ResnetBlock(nn.Module):
"""Define a Resnet block."""
def __init__(
self,
dim: int,
padding_type: str,
norm_layer: Type[nn.Module],
use_dropout: bool,
use_bias: bool,
n_conv_layers: int = ... | simulation/utils/machine_learning/models/resnet_block.py | MIT | 2,610 | 3a20ca5d70c22b79894a841c3b3bb33d9c88db01 | Python | py | |
import torch
class Config:
####################################
# Data configurations
####################################
DATA_FILE = 'tomography' # root name of the data file (not including labels and file type)
NUM_INTERVENTIONS = 3 # number of total interventions
########################... | config.py | Apache-2.0 | 2,140 | 3a20d6b20cccf2551e68356f04170cf9c11371a8 | Python | py | |
# coding:utf-8
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.utils import clip_grad_norm_
from torch.utils.data import DataLoader
from tqdm import tqdm
import numpy as np
import math
import re
import sys
from Vocab import Vocab
from Dataset import Dataset
from RNN_RNN import RNN_R... | baselines/baseline_summarunner/main.py | MIT | 10,325 | 3a20f5e777be4409e899dec4e5460fecff5677e0 | Python | py | |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from compressai.entropy_models import EntropyBottleneck
from torch import Tensor
from neuralcompression.layers import AnalysisTransformatio... | tests/models/test_prior_autoencoder.py | MIT | 1,400 | d71bada75487b43801dc61ba4889951391f16ad6 | Python | py | |
"""Compare speed of different models with batch size 16"""
import torch
from torchvision.models import resnet, densenet, vgg, squeezenet,inception
from torch.autograd import Variable
from info_utils import print_info
import torch.nn as nn
import time
import pandas
import argparse
import os
from plot import *
print_inf... | benchmark_models.py | MIT | 4,943 | 03a8b396bdc3840474b1f26ece4b949c36dd237e | Python | py | |
__author__ = 'Maosen'
import torch
import torch.nn as nn
import torch.nn.functional as F
import utils
from utils import pos2id, ner2id
import sys
from tqdm import tqdm
class BGRU(nn.Module):
def __init__(self, args, rel2id, word_emb=None):
super(BGRU, self).__init__()
# arguments
hidden, vocab_size, emb_dim, po... | baselines/sentence-level-models/models/bgru.py | MIT | 3,757 | 3a2112daba4e1ffc8f0bbf80f066d7044d71189e | Python | py | |
import sys
from resilient_alexnet.alexnet_fashion import fashion_pytorch_alexnet, fashion_tensorflow_alexnet
from resilient_alexnet.alexnet_caltech import caltech_pytorch_alexnet, caltech_tensorflow_alexnet
from resilient_alexnet.alexnet_cinic import cinic_pytorch_alexnet, cinic_tensorflow_alexnet
from resilient_alexne... | resilient_alexnet/benchmark_tune.py | MIT | 16,202 | 24b482ceaef9e1094e2e5ae22fe8a691cfbb354b | Python | py | |
import torchvision.models
import torch
import torch.nn as nn
import numpy as np
class VGG16_pretrained(nn.Module):
def __init__(self, N_CLASSES, verbose):
super().__init__()
self.N_CLASSES = N_CLASSES
self.verbose = verbose
vgg16_pt = torchvision.models.vgg16(pretrained=Tru... | models.py | MIT | 2,581 | 3a211458aeed29d2a8ccd116f3aa9ff2ea1ed6c7 | Python | py | |
"""
---
title: Transformer Encoder and Decoder Models
summary: >
These are PyTorch implementations of Transformer based encoder and decoder models,
as well as other related modules.
---
# Transformer Encoder and Decoder Models
"""
import math
import torch
import torch.nn as nn
from labml_helpers.module import Mod... | labml_nn/transformers/models.py | MIT | 8,003 | a9848cffccc73c9c78827812a09c7dc35859088b | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
from fvcore.transforms import HFlipTransform
from detectron2.modeling.postprocessing import detector_postprocess
from detectron2.modeling.test_time_augmentation import GeneralizedRCNNWithTTA
class DensePoseGeneralizedRCNNWithTTA(Gene... | projects/DensePose/densepose/modeling/test_time_augmentation.py | Apache-2.0 | 3,630 | d7ca58134511fa6a746383bef2993e9b0fa529e5 | Python | py | |
import torch
import torch.nn as nn
import torchaudio
# from BaseSpeechModel import BaseSpeechModel
from .base_speech_model import BaseSpeechModel
device = 'cuda' if torch.cuda.is_available() else 'cpu'
class Tacotron2(BaseSpeechModel):
def __init__(self):
super(Tacotron2, self).__init__()
self.m... | tmh/speech/tacotron.py | MIT | 2,449 | 7cabca7bc991a2da5e321ed29e14f71b6eafa5da | Python | py | |
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from model.multimodal_context_net import WavEncoder, TextEncoderTCN
def reparameterize(mu, logvar):
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return mu + eps * std
def ConvNormRelu(in_channels, out_channel... | scripts/model/embedding_net.py | MIT | 10,527 | 3a214bc1879fef3bc0436c8f22d3c84bb2c794a2 | Python | py | |
import copy
import random
from functools import wraps
import torch
from torch import nn
import torch.nn.functional as F
from torchvision import transforms as T
from einops import rearrange
# augmentations
class RandomApply(nn.Module):
def __init__(self, fn, p):
super().__init__()
self.fn = fn
... | x_clip/visual_ssl.py | MIT | 8,517 | 3a217057ea6fd353b1a3701d638fa596a62f0d79 | Python | py | |
import pickle
import os
from typing import Set
import torch
import torch.nn
import numpy as np
# from numpy import random
import random
import scipy.signal
from collections import deque
import matplotlib.pyplot as plt
#from running_state import ZFilter
import math
import logging
def set_random_seed(seed: int, using_c... | utilities.py | MIT | 8,220 | 3a217a2d39fcc686532045a5912d4c68b7984cc5 | Python | py | |
"""
BSD 3-Clause License
Copyright (c) Soumith Chintala 2016,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of co... | src/adas/models/mobilenet.py | MIT | 8,676 | 3a219cf34ec26948a02aadccdda2ce0d31bf4574 | Python | py | |
import json
import os
import pickle
from PIL import Image
from collections import Counter
from torch.utils.data import Dataset
import utils
import torch
class ClevrDataset(Dataset):
def __init__(self, clevr_dir, train, dictionaries, transform=None):
"""
Args:
clevr_dir (string): Root ... | CLEVR/clevr_dataset_connector.py | MIT | 8,132 | 3a21cc944b42dfee94bbd41973e41d86d58985c5 | Python | py | |
# Copyright 2021 TUNiB Inc.
import torch
import torch.distributed as dist
from transformers import GPT2Tokenizer
from oslo.models.gpt_neo.modeling_gpt_neo import (
GPTNeoForCausalLM,
GPTNeoForSequenceClassification,
GPTNeoModel,
)
class TestTPInference:
def __init__(self, num_gpus):
self.num... | tests/gpt_neo/gpt_neo_test_tp_inference.py | Apache-2.0 | 4,822 | d7a8f7e976e3d0da36df80aee49ccb585c2ed462 | Python | py | |
from typing import Any, Union, List, Tuple, Dict, Callable, Optional
from multiprocessing import Pipe, connection, get_context, Array
from collections import namedtuple
import logging
import platform
import time
import copy
import traceback
import numpy as np
import torch
import ctypes
import pickle
import cloudpickle
... | ding/envs/env_manager/subprocess_env_manager.py | Apache-2.0 | 33,190 | 3a21f9b516b3324fc26e087200686a211be4a6e2 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
import numpy as np
import itertools
class Flatten(nn.Module):
def forward(self, input):
"""
Note that input.size(0) is usually the batch size.
So what it does is that given any input with input.... | foldingnet.py | Apache-2.0 | 15,450 | 3a22043f0e3592294e46cded57f13da818e3d855 | Python | py | |
import argparse
import datetime
import gym
import ra_gym
import numpy as np
import itertools
import torch
import time
from sac import SAC
from tensorboardX import SummaryWriter
from replay_memory import ReplayMemory
parser = argparse.ArgumentParser(description='PyTorch Soft Actor-Critic Args')
parser.add_argument('--e... | sac_modular.py | Apache-2.0 | 7,614 | 3a22291856598932d7947300295f9cd38a95b12d | Python | py | |
"""
ResNet, implemented in PyTorch.
Original paper: 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
"""
__all__ = ['ResNet', 'resnet10', 'resnet12', 'resnet14', 'resnet16', 'resnet18_wd4', 'resnet18_wd2', 'resnet18_w3d4',
'resnet18', 'resnet34', 'resnet50', 'resnet5... | pytorch/pytorchcv/models/resnet.py | MIT | 20,829 | 3a223327fa33d2c67bb729121959a5bb7783063d | Python | py | |
import re
import torch.nn as nn
from pretrainedmodels.models.torchvision_models import pretrained_settings
from torchvision.models.densenet import DenseNet
class DenseNetEncoder(DenseNet):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.pretrained = False
del self.classifie... | models/encoders/densenet.py | MIT | 3,242 | 12eb379af87f51a4e3b1415bf91f9fa6bb059397 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.