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 random
from collections import deque
import dill as pickle
import numpy as np
from tqdm import tqdm
import spacy
import torch
import torch.nn as nn
from models import BinaryClassifier, RNNEncoder, RNNDecoder, RLSeq
from test import test
from utils import constant
from utils.utils import load_model
class Sin... | interact.py | MIT | 2,838 | 52ed149e379d15b228e1c40d791464b3dfeff7f2 | Python | py | |
"""
for reference (not used anywhere): https://www.pettingzoo.ml/classic
torch is only used for neural network, the output values are converted to numpy
and all the operations are then used for
"""
import json
import chess
import chess.pgn
import numpy as np
from time import time
from tqdm import trange
from types imp... | game.py | MIT | 31,405 | dffcd10e3d7803503b32b7a590b7354dddb5854f | Python | py | |
#####################################################
# Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2021.03 #
#####################################################
from __future__ import division
from __future__ import print_function
import math
from functools import partial
from typing import Optional, Text
import tor... | lib/xlayers/super_trade_stem.py | MIT | 2,355 | 802bff7b7da217dbefec47964dd3d3215f970365 | Python | py | |
from torch.autograd import Variable
import torch
from .module import Module
from .container import Sequential
from .activation import LogSoftmax
from .. import functional as F
def _assert_no_grad(variable):
assert not variable.requires_grad, \
"nn criterions don't compute the gradient w.r.t. targets - ple... | torch/nn/modules/loss.py | BSD-3-Clause,BSD-2-Clause,MIT | 25,211 | 29c1f624df4b98eb65faeb5f0c02094933c30648 | Python | py | |
import torch
import sys
from torch.utils import data
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.tensorboard import SummaryWriter
from torch.cuda.amp import autocast,GradScaler
import torchvision as tv
import torch.nn as nn
import matplotlib.pyplot as plt
import subprocess
import os
import... | mainTrainXLFMNet.py | MIT | 23,625 | fd7fa87bb8f7abfee657695cde85006e067f0ac3 | Python | py | |
"""
Runs a model on a single node on CPU only..
"""
import os
import numpy as np
import torch
from test_tube import HyperOptArgumentParser, Experiment
from pytorch_lightning.models.trainer import Trainer
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
SEED = 2334
torch.manual_seed(SEED)
np.rand... | examples/new_project_templates/single_cpu_template.py | Apache-2.0 | 2,992 | 29c255981627aaf6568e2e1b8937d81f8f93b9ce | Python | py | |
#!/usr/bin/env python3
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
class RNNVAE(nn.Module):
def __init__(self, vocab_size=10000,
enc_word_dim = 512,
enc_h_dim = 1024,
enc_nu... | models_text_skip.py | MIT | 4,902 | 104d5e210aaef8913decc8e02b14bb90dff5220d | Python | py | |
# coding=utf-8
# Copyright 2020 The HuggingFace Team. 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 requir... | tests/models/big_bird/test_tokenization_big_bird.py | Apache-2.0 | 10,653 | 29c28d5877d2ba55c0082a95409e2f6aa87e57d6 | Python | py | |
from torch.utils.data import DataLoader, random_split
from torchvision.datasets import MNIST
import os
from torchvision import datasets, transforms
from pytorch_lightning import LightningDataModule
from pytorch_lightning.core.lightning import LightningModule
import src.datamodules.get_data as get_data
from src.utils.ut... | src/datamodules/Datamodules.py | Apache-2.0 | 10,220 | 529dc39ff5ea74fc98259984a9e101eb8acfbb0f | Python | py | |
import gc
import os
import math
import random
import warnings
import albumentations as A
import cv2
import numpy as np
import pandas as pd
import timm
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as torchdata
from pathlib import Path
from typin... | exp/exp026_larger_image_size2.py | MIT | 39,099 | 70aa897e73b90e93de90ff49f226b60b144142cc | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import distutils.command.clean
import shutil
import glob
import os
import subprocess
from setuptools import setup... | setup.py | BSD-3-Clause | 4,299 | e64222cb99d6cf6b2fb0e10e0daeda460491a53f | Python | py | |
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.functional as f
import numpy as np
class DICELossMultiClass(nn.Module):
def __init__(self):
super(DICELossMultiClass, self).__init__()
def forward(self, output, input_mask):
num_classes = output.size(1)-1
dice_es... | multiclass-implementation/losses.py | MIT | 1,960 | 651c2d9c379fa09161232a140345a4c501372c6c | Python | py | |
from typing import List, Tuple, Union, Dict, Any, Set
from dataclasses import dataclass
import torch
import torch.fx
from torch.fx.node import _get_qualified_name
from torch.fx._compatibility import compatibility
Tensors = Union[Tuple[torch.Tensor], List[torch.Tensor]]
TensorOrTensors = Union[torch.Tensor, Tensors]
... | torch/fx/passes/tools_common.py | Intel | 7,085 | fd978ba7406df8be33a69e65486ecd83aa34ac36 | Python | py | |
from __future__ import absolute_import
import torch.nn as nn
from models.sem_graph_conv import SemGraphConv
from models.graph_non_local import GraphNonLocal
class _GraphConv(nn.Module):
def __init__(self, adj, input_dim, output_dim, p_dropout=None):
super(_GraphConv, self).__init__()
self.gconv ... | models/SpinModel.py | Apache-2.0 | 3,532 | 52d1f0126b852946fe17c3141abf6dc9e8bbd2c5 | Python | py | |
from torch.utils.data import DataLoader
from torchvision.datasets import CIFAR10
import torchvision.transforms as transforms
BATCH_SIZE=64
train_dataset = CIFAR10("/workspace/data", train=True, transform=transforms.Compose([transforms.PILToTensor()]))
train_dataloader = DataLoader(train_dataset, batch_size=BATCH_SIZ... | src/vqvae/train.py | Apache-2.0 | 446 | 29c3214509d548aac62bf69b75241b264fedddb0 | Python | py | |
import os
import math
import torch
import torchaudio
import numpy as np
import IPython.display as ipd
import matplotlib.pyplot as plt
from scipy.fftpack import fft
from matplotlib.offsetbox import AnchoredText
from djtransgan.config import settings
from djtransgan.utils.utils import squeeze_dim
... | djtransgan/utils/visualize.py | MIT | 1,946 | 1e8687eaa56a002543b554d0a63de8a1ad14deea | Python | py | |
from copy import deepcopy
import torch
class Metrics():
def __init__(self):
pass
def accuracy_score(self, predictions, labels, vocab_output):
labels = torch.tensor([vocab_output.getIndex(str(int(label))) for label in labels], dtype=torch.float)
correct = (predictions == labels).sum()... | treelstm/metrics.py | MIT | 407 | 29c32f05e8f899afaa8a7c5eba5cf87c6fe3e664 | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
from im2mesh.layers import ResnetBlockFC
class Decoder(nn.Module):
''' Decoder class.
As discussed in the paper, we implement the OccupancyNetwork
f and TextureField t in a single network. It consists of 5
fully-connected ResNet blocks with ReLU ... | im2mesh/dvr/models/decoder.py | MIT | 2,447 | e9a7eddef4589866eed5cf79037d829e48646286 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Encoder(nn.Module):
def __init__(self):
super(Encoder, self).__init__()
#Conv1
self.layer1 = nn.Conv2d(3, 32, kernel_size=3, padding=1)
self.layer2 = nn.Sequential(
nn.Conv2d(32, 32, kernel_size=3, ... | models/modelstituste.py | MIT | 6,887 | 106eb52aa98683117f7ae343fc1aa7865c59795a | Python | py | |
import os
import time
import numpy as np
import copy
import torch
import torch.nn as nn
from es_rnn.loss_modules import PinballLoss, sMAPE, np_sMAPE
from utils.logger import Logger
import pandas as pd
class ESRNNTrainer(nn.Module):
def __init__(self, model, dataloader, run_id, config, ohe_headers):
super(... | es_rnn/trainer.py | MIT | 7,400 | 5f699b38ff927fb73355685c2a36070cbea59805 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from modules.layers import SpotlightTransformer
class EntitySpotlightTransAgent(nn.Module):
def __init__(self, input_shape, args):
super(EntitySpotlightTransAgent, self).__init__()
self.args = args
self.entity_shape = None
... | src/modules/agents/entity_spotlight_trans_agent.py | Apache-2.0 | 2,493 | 29c34e94eb327bf7362aee6bd1690b0ff3059de0 | Python | py | |
import math
from typing import List, Union
import numpy as np
import torch
import torch.nn as nn
from torch.optim import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
from tqdm import tqdm
from chemprop.data import MoleculeDataLoader, MoleculeDataset
def compute_pnorm(model: nn.Module) -> float:
"... | chemprop/nn_utils.py | MIT | 8,606 | d701848b1016ba5d5c141573ef6522f83926cc32 | Python | py | |
"""Settings used by the tests in this submodule."""
import torch
from cockpit.utils.schedules import linear, logarithmic
from tests.settings import SETTINGS as GLOBAL_SETTINGS
from tests.utils.data import load_toy_data
from tests.utils.models import load_toy_model
from tests.utils.problem import make_problems_with_id... | tests/test_quantities/settings.py | MIT | 1,466 | 29c3727ca3e7a528f848a166065eb93868b261b4 | Python | py | |
r"""
The fmoe.functions module contains functions that are directly warped up from
C/CUDA functions to complete distributed communication, computation and gradient
computation.
"""
import torch
from torch.autograd import Function
import fmoe_cuda
from .utils import get_torch_default_comm
def moe_prepare_forward(gate... | fmoe/functions.py | Apache-2.0 | 7,213 | e64948f4fcb65b9a45c209effb530ae791abdd76 | 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... | HRNet-Human-Pose-Estimation/lib/core/function.py | MIT | 9,682 | 12adfd41f3e933e77f4be20d9602502b9439a6cf | Python | py | |
import os
import sys
import time
import torch
import torch.backends.cudnn as cudnn
def compute_speed(model, input_size, device='cuda:0', iteration=1000):
assert isinstance(input_size, (list, tuple))
assert len(input_size) == 4
os.environ['OMP_NUM_THREADS'] = '1'
os.environ['MKL_NUM_THREADS'] = '1'
device = torc... | benchmark/compute_speed.py | MIT | 1,259 | f9d210ca859624151f779aa3eb869e0bc5c7a2a6 | Python | py | |
import torch
from torch.utils.cpp_extension import load
cd = load(name="cd",
sources=["chamfer_distance/chamfer_distance.cpp",
"chamfer_distance/chamfer_distance.cu"])
class ChamferDistanceFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, xyz1, xyz2):
batc... | chamfer_distance/chamfer_distance.py | MIT | 1,798 | a9135faa48863846898bbc3ebd598d834023f5ed | Python | py | |
from __future__ import absolute_import, division, print_function
import json
import logging
import math
import collections
from io import open
import re
import string
from tqdm import tqdm, trange
import os
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from tra... | simpletransformers/question_answering/question_answering_utils.py | Apache-2.0 | 61,487 | 12badd8b6a181d1622c6cd9c478166403c0dfad0 | Python | py | |
import torch
from torch.utils.data import TensorDataset
import shifthappens.data.base as base_data
import shifthappens.data.torch as torch_data
from shifthappens.models import torchvision as torchvison_models
from shifthappens.models.base import PredictionTargets
def _create_mock_dataloader():
torch_ds = TensorD... | tests/test_models.py | Apache-2.0 | 1,589 | 5fac47227a1b0330b5280a997747ed235b9592e7 | Python | py | |
"""
(c) 2020 Spencer Rose, MIT Licence
Python Landscape Classification Tool (PyLC)
Reference: An evaluation of deep learning semantic segmentation
for land cover classification of oblique ground-based photography,
MSc. Thesis 2020.
<http://hdl.handle.net/1828/12156>
Spencer Rose <spencerrose@uvic.ca>, June 2020
Uni... | utils/extract.py | MIT | 12,631 | 29c40372d128cad7023e2c499a38b281e2a0b0b2 | Python | py | |
import json
import os
import random
import traceback
import numpy as np
import sys
from sklearn.utils import shuffle
import natural_language_utilities as nlutils
import embeddings_interface
import embeddings_interface as ei
from torch.utils.data import Dataset
import math
from auxiliary import read_json
if sys.versio... | kbcqa/method_ir/grounding/semantic_matching/data_loader.py | Apache-2.0 | 41,653 | 29c40bdb62275781ce02e617ab5e968a3914ebb4 | Python | py | |
import copy
from abc import ABC, abstractmethod
import torch
from torch import nn
from TTS.tts.utils.generic_utils import sequence_mask
class TacotronAbstract(ABC, nn.Module):
def __init__(self,
num_chars,
num_speakers,
r,
postnet_output_dim=80... | TTS/tts/models/tacotron_abstract.py | MIT | 9,066 | 10953269663a02fe52c181f8d7cfeeafe1240502 | Python | py | |
import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from transformers import (
BertModel,
BertPreTrainedModel,
DistilBertModel,
ElectraForMaskedLM,
ElectraForPreTraining,
FlaubertModel,
LongformerModel,
RobertaModel,
XLMModel,
XLMPr... | simpletransformers/custom_models/models.py | Apache-2.0 | 29,946 | 2480ec313cf668e206c3ceca03b7d2c6431e7718 | Python | py | |
# coding: utf-8
import sys
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as data
import time
import visdom
import numpy as np
from torchvision import datasets, transforms
from torch.autograd import Variable
sys.path.append(os.path.join(os.path.dirname(__file__),... | src/model/deconv/convVAE-mnist.py | MIT | 8,222 | 29c421cfbc74b9f07c5feebd40d3bd6636659664 | Python | py | |
import os
import sys
sys.path.append("..")
import time
import numpy as np
import librosa
import scipy.io.wavfile as wav
# from tqdm import tqdm_notebook
import torch
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from torch.utils.data import DataLoader
import torchvision
from torch.optim.lr_sc... | GSC/srnn_fin.py | MIT | 12,045 | 1e9f0cadbc2d2202a219ab16125ca32d0488111c | Python | py | |
import copy
import platform
import random
from functools import partial
import numpy as np
from mmcv.parallel import collate
from mmcv.runner import get_dist_info
from mmcv.utils import Registry, build_from_cfg
from torch.utils.data import DataLoader
from .samplers import DistributedGroupSampler, DistributedSampler, ... | mmcap/datasets/builder.py | Apache-2.0 | 3,321 | 109c43bbf82262835a97b9b9abe0b77052d68731 | Python | py | |
# coding=utf-8
# Copyright 2019 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... | robust_loss/tests/cubic_spline_test.py | MIT | 11,018 | e93d293be0ddd68d1b779f9ce6c661bbeebc576d | Python | py | |
import torch
import numpy as np
import ipdb
from utils import *
from losses import ContrastiveLoss_mod as const_loss
import copy
import operator
def cp(x):
return copy.deepcopy(x)
def minmax_norm(row):
return (row - np.min(row))/(np.max(row) - np.min(row))
# return (row - np.mean(row))/(np.std(row))
def... | backup/trainer.backup.py | BSD-3-Clause | 27,851 | 29c4737ed54ae3ed8aa4a796120df53e5ce71ec1 | Python | py | |
import torchvision.models as models
from overrides import overrides
import torch.nn as nn
import torch
class BilinearModel(nn.Module):
"""Load model with pretrained weights and initialise new layers."""
def __init__(self, num_classes: int = 200, pretrained=True) -> None:
"""Load pretrained model, set... | apps/prediction/neural_network/model.py | MIT | 2,838 | f97a722d01832d282bff850cf6999cda6bc7cfef | Python | py | |
import torch
def create_metric(model):
def G(z):
return torch.inverse(
(
model.M_tens.unsqueeze(0).to(z.device)
* torch.exp(
-torch.norm(
model.centroids_tens.unsqueeze(0).to(z.device) - z.unsqueeze(1),
... | src/pythae/models/rhvae/rhvae_utils.py | Apache-2.0 | 1,156 | 29c485eaed00eb378814a68dcaa85d45e840ec80 | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmocr.models.textrecog.necks import FPNOCR
def test_fpn_ocr():
in_s1 = torch.rand(1, 128, 32, 256)
in_s2 = torch.rand(1, 256, 16, 128)
in_s3 = torch.rand(1, 512, 8, 64)
in_s4 = torch.rand(1, 512, 4, 32)
fpn_ocr = FPNOCR(in_channel... | tests/test_models/test_ocr_neck.py | Apache-2.0 | 525 | 3454eab362c56209553d8c1e4796a157b382a34b | Python | py | |
import numpy as np
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import matplotlib.pyplot as plt
import imageio
import sys
A = imageio.imread('runs/detect/exp/zidane.jpg')
# Define how the convolution operation works
conv2 = nn.Conv2d(in_channels=3, out_channels=3, k... | old_files/display_conv_pytorch.py | Apache-2.0 | 808 | 5e328a2b31e66bfbcaab39405149674885f52d0f | Python | py | |
import codecs
import itertools
import functools
import os
import torch
from torch import nn
from torch.autograd import Variable
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import utils
from arch import define_Gen, define_Dis, set_grad
from torch.optim import lr_scheduler
from torch... | model.py | MIT | 10,222 | 29c4a2db17c66bc07757a1869d91ee0875b4cf72 | Python | py | |
from typing import Callable, Iterator, Sized, TypeVar
from torch.utils.data.datapipes._decorator import functional_datapipe
from torch.utils.data._utils.collate import default_collate
from torch.utils.data.datapipes.datapipe import IterDataPipe
from torch.utils.data.datapipes.utils.common import _check_lambda_fn
__al... | torch/utils/data/datapipes/iter/callable.py | Intel | 6,384 | 29c4bb694beeafe9bb4ddb1e4061c47e2715206f | Python | py | |
#!/usr/bin/env python3
import cv2
import os
import numpy as np
import tensorrt as trt
import torch.nn as nn
import torch.nn.functional as F
from torchvision.transforms import Normalize
import time
import argparse
import torch
import torch.nn as nn
from utils import get_seg_single,vis_seg
def torch_dtype_from_trt(dty... | inference.py | BSD-2-Clause | 6,606 | 29c4d8b75b444961a1e4c4520aa9af1d9d3b1ec3 | Python | py | |
#
import torch
from torch.utils.data import DataLoader
from ann.fme.fme_engine import FmeEngine
from ann.ds.asdk_ds import AsdkDs
from ann.envs.asdk_env import AsdkEnv
from apps.asdk.rxgb.asdk_rxgb_agent import AsdkRxgbAgent
from apps.asdk.rxgb.asdk_rxgb_renderer import AsdkRxgbRenderer
class AsdkApp(object):... | apps/asdk/asdk_app.py | Apache-2.0 | 1,471 | ffa9ef7172353d085db8918eb287aeeb4d525d2c | Python | py | |
import os
import pickle
import sys
from functools import partial
from typing import Callable
import numpy as np
import pytest
import torch
from torch.multiprocessing import Pool, set_start_method
from torchmetrics import Metric
try:
set_start_method("spawn")
except RuntimeError:
pass
NUM_PROCESSES = 2
NUM_BA... | tests/metrics/utils.py | Apache-2.0 | 9,722 | 29c530953f99c18b05749be1d7f69e79e42eceb3 | Python | py | |
import pandas as pd
import os
from pathlib import Path
import cv2
import numpy as np
from torch.utils.data import DataLoader, Dataset
from torchvideo.transforms import Compose, NDArrayToPILVideo, NormalizeVideo, RandomHorizontalFlipVideo, PILVideoToTensor
class TripletFrameDataset(Dataset):
r"""A Dataset for a fo... | R2Plus1D/dataset.py | MIT | 17,091 | 52f8d263d07c07412008fd8f5880cef65675f47f | Python | py | |
# @Date : 2019-10-22
# @Author : Chen Gao
import os
import numpy as np
import torch
import torch.nn as nn
from torchvision.utils import make_grid
from imageio import imsave
from tqdm import tqdm
from copy import deepcopy
import logging
from utils.inception_score import get_inception_score
from utils.fid_score imp... | network.py | MIT | 5,849 | 29c558cdb912d564bd8839aa4488ace1af4255a0 | 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 sys
import json
import random
import logging
import argparse
from io impo... | volta/train_concap_wiki.py | MIT | 19,865 | 29c55f7db02a66dcadf75763d80ff8a05e8031e6 | Python | py | |
from dataset import SurgeryDataset
import dataset
from torch.utils.data import DataLoader
import time
import click
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.tensorboard import SummaryWriter
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.metrics import average_p... | MULTITASK_FILES/TSM_FILES/train.py | MIT | 12,175 | 03928b17c93baa749d9c767d660f8f1b38105b5c | Python | py | |
import os.path
import numpy as np
import torch
import logging
logger = logging.getLogger(__name__)
class Landmark:
"""
Landmarks (i.e. labelled point sets).
The Landmark class represents a set of labelled points. This class assumes that the source and the target
have the same number of points with a... | deformetrica/core/observations/deformable_objects/landmarks/landmark.py | MIT | 3,536 | 5e967d76bc77cf93e30e6c99d3300414458fccfe | Python | py | |
###########################
# Latent ODEs for Irregularly-Sampled Time Series
# Author: Yulia Rubanova
###########################
import os
import logging
import pickle
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import math
import glob
import re
from shutil import copyfile
import skle... | latent-ode-irregular-understanding/library/utils.py | MIT | 21,832 | 12b70813198b36d93d0366b77e14b25ebce741fe | Python | py | |
#!/usr/bin/env python3
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Functions for putting examples into torch format."""
from collections import Counter
import torch
def vec... | reader/qanet/vector.py | MIT | 4,486 | 52facd2f51e958b8559471d7b90128733859375e | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from modeling.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 ==... | modeling/decoder.py | MIT | 3,098 | 29c5a106555e4f9dbfb58c1ced54de1de8cbdf10 | Python | py | |
import torch
import numpy as np
from torch.utils import data
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from PIL import Image
from torch import optim
import torch.nn.functional as F
from barbar import Bar
import torch.nn as nn
import random
import math
from torch.nn.parameter ... | memory.py | MIT | 5,691 | 29c5b22c3275c2e11abd577651d88ccb46610499 | Python | py | |
import os
import torch
import torch.nn as nn
import numpy as np
import math
import PIL
def dir_exists(path):
if not os.path.exists(path):
os.makedirs(path)
def initialize_weights(*models):
for model in models:
for m in model.modules():
if isinstance(m, nn.Conv2d):... | sea_ice_segmentation/models/helpers.py | Apache-2.0 | 1,893 | d7b334665c77e5c32634417f44119a5b0ca87798 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils import utils
from models.loss import Loss_interactive
def search(train_loader, valid_loader, model, optimizer, w_optim, alpha_optim, epoch, writer, logger, config):
# interactive retrain and kl
device = torch.device("cuda")
crit... | benchmark201/core/search_function.py | MIT | 10,063 | 29c60e38663c37ed1ee6323e520e227b15c7c6dc | Python | py | |
import pytest
import torch
import syft as sy
def test_encrypt_and_decrypt():
"""
Test the basic paillier encrypt/decrypt functionality
"""
pub, pri = sy.keygen()
x_tensor = torch.Tensor([1, 2, 3])
x = x_tensor.encrypt(pub)
y = x.decrypt(pri)
assert (x_tensor == y).all()
def test_... | test/torch/tensors/test_paillier.py | Apache-2.0 | 3,186 | 70837643475ed0f44ef143ea50767b49fa70941e | Python | py | |
# 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.
"""
This module implements utility functions for loading and saving
meshes and point clouds as PLY files.
"""
... | pytorch3d/io/ply_io.py | MIT,BSD-3-Clause | 52,430 | 5ec7f662c9e9aafa16607d4291c73dc90c68293d | Python | py | |
# Author: Jochen Gast <jochen.gast@visinf.tu-darmstadt.de>
import logging
import os
from glob import glob
import numpy as np
import torch
import torch.utils.data as data
from torchvision import transforms as vision_transforms
from datasets import common
from datasets import factory
from datasets.my_transforms import... | datasets/gopro_su.py | Apache-2.0 | 24,096 | 29c64a733584a2e7f1d3925bb98ae8ed328975d2 | Python | py | |
# pylint: disable=invalid-name, missing-docstring, no-member, line-too-long
import unittest
from functools import partial
import torch
from se3cnn.non_linearities import GatedBlock, rescaled_act
from se3cnn.point.kernel import Kernel
from se3cnn.point.operations import Convolution
from se3cnn.point.radial import Cons... | tests/point/gated_block_tests.py | MIT | 1,476 | 7c311368606a697283b5407f158b026605923707 | Python | py | |
#!/usr/bin/env python
# coding: utf-8
# # 5. Automatic Differentiation with ``Torch.autograd``
#
# When training neural networks, the most frequently used algorithm is
# **back propagation**. In this algorithm, parameters (model weights) are
# adjusted according to the **gradient** of the loss function with respect
#... | docs/_build/jupyter_execute/machine_learning/pytorch/autogradqs_tutorial.py | Apache-2.0 | 8,492 | 7c75854c0c296d354c076b1cd14b9e46ae4d9b4a | Python | py | |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | tests/python/frontend/pytorch/qnn_test.py | Zlib,Unlicense,Apache-2.0,BSD-2-Clause,MIT,ECL-2.0 | 20,687 | 29c69abba542c22cf39ac172ea564fcdec23cdb1 | Python | py | |
import argparse
import json
import os
import numpy as np
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
import sys
sys.path.append(sys.path[0] + '/..')
from lib.models import get_model_class
from util.datasets import load_dataset
from util.environments import load_environment, g... | scripts/compute_stylecon_ctvae.py | MIT | 7,948 | 29c69cf8790cf7bdfb3d971a0db8d2ecae87d518 | Python | py | |
"""
Entry point for training and evaluating a POS/morphological features tagger.
This tagger uses highway BiLSTM layers with character and word-level representations, and biaffine classifiers
to produce consistant POS and UFeats predictions.
For details please refer to paper: https://nlp.stanford.edu/pubs/qi2018univer... | stanfordnlp/models/tagger.py | Apache-2.0 | 11,116 | 52e03e9d777f1081eb5f1b740e6ac048b7268599 | Python | py | |
import os
import numpy as np
import torch
TEST_ROOT = os.path.dirname(__file__)
PACKAGE_ROOT = os.path.dirname(TEST_ROOT)
TEMP_PATH = os.path.join(PACKAGE_ROOT, 'test_temp')
# generate a list of random seeds for each test
RANDOM_PORTS = list(np.random.randint(12000, 19000, 1000))
if not os.path.isdir(TEMP_PATH):
... | tests/__init__.py | Apache-2.0 | 342 | 29c6a4a633ba8ee35b0105c80b2da02bdea7ee75 | Python | py | |
#!/usr/bin/env python3
"""
This example demonstrates the ability of pyoptmat to integrate material models under
strain control, stress control, or a combination of both.
The example first simulates standard, strain-rate controlled tensile curves
for a simple material model for Alloy 617 developed by Messner, ... | examples/structural-material-models/stress_strain_control.py | MIT | 4,018 | 4b7dd29bde9e9025dc7a596c12266ad9d8f5823f | Python | py | |
from pywick.datasets.tnt.batchdataset import BatchDataset
from pywick.datasets.transformdataset import TransformDataset
from pywick.datasets.shuffledataset import ShuffleDataset
from pywick.datasets.multipartitiondataset import MultiPartitionDataset
from torch.utils.data import DataLoader
class Dataset(object):
d... | pywick/datasets/tnt/dataset.py | MIT | 1,003 | ff3640ecd5295e9708c4ab49ef64bcd4fe4acf79 | Python | py | |
# Set up dataloaders
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import torch
import numpy as np
class SeismicDataset2D(Dataset):
"""Dataset class for loading 2D seismic images for 2-D TCN"""
def __init__(self, seismic, model, trace_indices, width):
self.seismic = sei... | datasets.py | MIT | 2,892 | 29c6d0c20b9597a10781ab8f338b1126e8f28be8 | Python | py | |
import torch.nn as nn
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
def discretized_mix_logistic_loss(x, l, sum_all=True):
xs = x.size() # (B,32,32,C)
ls = l.size() # (B,32,32,100)
# here and below: unpacking the params of the mixture of logistic... | pixelcnn_loss.py | MIT | 6,010 | 29c6e0b812a7b95aadc1e61fe920b04204c292a0 | Python | py | |
""" Optuna example that optimizes the hyperparameters of
a reinforcement learning agent using A2C implementation from Stable-Baselines3
on a OpenAI Gym environment.
This is a simplified version of what can be found in https://github.com/DLR-RM/rl-baselines3-zoo.
You can run this example as follows:
$ python sb3_s... | examples/rl/sb3_simple.py | MIT | 5,368 | 29c6ee3e9a16f15ddfad9107fd86cb15a83e20d0 | Python | py | |
#from utils import accuracy
from utils import Config
import numpy as np
from pygcn.utils import accuracy, encode_onehot, normalize, sparse_mx_to_torch_sparse_tensor
from pyagnn.agnn.model import AGNN
from pygcn.models import GCN
import torch.nn.functional as F
import torch.optim as optim
import scipy.sparse as sp
impor... | utils/Trainer_graph.py | MIT | 4,597 | 29c70c960daf791cee2e37ec534e898b5eef8b45 | Python | py | |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.distributions.categorical import Categorical
from torch.utils.tensorboard import SummaryWriter
from cleanrl.common import preprocess_obs_space, preprocess_ac_space
import argparse
import numpy as np
import gym
imp... | invalid_action_masking/ppo_no_mask_4x4.py | MIT | 21,360 | 29c7308b7a709bf1b191e6dbb4e77f93c957c8e7 | Python | py | |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | pytorch_lightning/plugins/training_type/fully_sharded.py | Apache-2.0 | 9,159 | 29c74439dd5eeb32d6a1cab49c23b44ac9bdf1f2 | Python | py | |
import argparse
import os
import dgl
from dgl import DGLGraph
from dgl.data import register_data_args, load_data
import dill
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
import torch
from torch.nn.functional import binary_cross_entropy_with_logits as BCELoss
... | gae_dgl/train_transductive.py | MIT | 2,645 | ff2f39191f929f8c78534165d52aec9cc95ef152 | Python | py | |
from __future__ import annotations
import torch
import torch.nn as nn
from typing import Optional, Any, Union
from torchvision.models import resnext50_32x4d
import warnings
warnings.simplefilter("ignore")
class ConvRelu(nn.Module):
def __init__(self, in_channels: int, out_channels: int, kernel: Union[... | brain_flair_segmentation/models/resnext_unet.py | MIT | 3,699 | 29c76a4936bada4c884c61da67abc45aa094c233 | Python | py | |
import math
import os
from abc import ABC, abstractmethod
from functools import lru_cache
from typing import Callable, List, Tuple
import numpy as np
import pytest
import torch
import torch.fx
from common_utils import assert_equal, cpu_and_gpu, needs_cuda
from PIL import Image
from torch import nn, Tensor
from torch.a... | test/test_ops.py | BSD-3-Clause | 55,555 | 6b35b4f0091c4315a76164e03378f6f17f046f8d | Python | py | |
#adapted from https://github.com/Bjarten/early-stopping-pytorch/blob/master/pytorchtools.py
import torch
from time import time
from util.file import create_if_not_exist
class EarlyStopping:
def __init__(self, model, patience=20, verbose=True, checkpoint='./checkpoint.pt'):
# set patience to 0 or -1 to av... | src/util/early_stop.py | BSD-3-Clause | 1,853 | 29c79914dcbfc6beecbcf77b33acfa5a9c438bee | Python | py | |
# -*- coding: utf-8 -*-
"""
@date: 2020/5/25 下午2:39
@file: test_fps.py
@author: zj
@description:
"""
from torchvision.models import alexnet
import torch
from metrics.model import compute_fps
def get_device():
return torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
if __name__ == '__main__':
... | py/test_fps.py | Apache-2.0 | 537 | 248ee0fb7c05bb5b337684a1ec8014ab88088c96 | Python | py | |
from __future__ import division
from collections import defaultdict
import numpy as np
import torch
from ..bbox import bbox_iou
class VOCMApMetric(object):
"""
Calculate mean AP for object detection task
Parameters:
---------
iou_thresh : float
IOU overlap threshold for TP
class_names : list of st... | tools/voc_metrices.py | BSD-2-Clause | 9,041 | e63a6ba4291a8d0df234bf935c59607379ee8d08 | Python | py | |
import torch
import torch.nn as nn
import torch.optim as optim
import os
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from data_loader import *
def get_iou(predict, label):
predict_f = torch.flatten(predict)
label_f = torch.flatten(label)
intersection = torch.sum(predict_f*lab... | projects/Multi Task Learning/code/single_task/segmentation.py | MIT | 6,196 | 10e2e283db32d3df286b2957efcbd812f25162ff | Python | py | |
# 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.
from typing import Sequence, Union
import torch
def mask_background(
image_rgb: torch.Tensor,
mask_... | pytorch3d/implicitron/tools/image_utils.py | MIT,BSD-3-Clause | 1,853 | 29c7e0a4122eb81b0e61343c74b29a0091ffcd8c | Python | py | |
# coding=utf-8
# Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved.
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Modifications Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you... | training/distributed_training/pytorch/model_parallel/bert/bert_example/sagemaker_smp_pretrain.py | Apache-2.0 | 39,338 | 29c7e2e563b4bd007c6b7fe333755fd5918b3519 | Python | py | |
from time import process_time
import torch
import torch.nn.functional as F
from torch import nn
#tensorboard --logdir=logs
from tensorboardX import SummaryWriter
writer = SummaryWriter(log_dir='logs',comment='train-loss')
from models import Net
from prepare_data import loader_tr, loader_ts
import myloss
device = tor... | train.py | MIT | 2,226 | 29c7edfd440bd6c32a2df9cd4619e1d2c73d4766 | Python | py | |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
"""
Train a network across multipl... | fairseq/trainer.py | BSD-3-Clause | 15,120 | 70833a7cb47708fcf80d037020b462a03e5a4832 | Python | py | |
import torch
# SR : Segmentation Result
# GT : Ground Truth
eps = 1e-6
def get_accuracy(SR, GT, threshold = 0.5):
"""
ACC: Accuracy
"""
SR = (SR > threshold)
GT = (GT == torch.max(GT))
cor = torch.sum(SR == GT)
acc = float(cor) / float(SR.numel())
return acc
def get_sensitivity(SR,... | code/semantic_segmentation/pspnet/pspnet_isic/utils_arma/evaluation.py | MIT | 2,064 | 1e2de9eb25de0fd95fba61b62a8c641fe2bc7487 | 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.net_utils import run_lstm, col_name_encode
class SelPredictor(nn.Module):
def __init__(self, N_word, N_h, N_depth, max_tok_num, use_ca):
super(SelP... | sqlnet/model/modules/selection_predict.py | BSD-3-Clause | 2,257 | a90a1cea28057ca64cc0b2ef6ca1a42c15079b7d | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 11 00:45:08 2018
seq1H: seqeunce learning model ONLY 1 Enc (256)
- q(x), l(x)
- non-autoregressive (not feeding predicted labels)
- instance Norm.
- G: GLU version
- H: Highway-net version
@author: mimbres
"""
import torch
import torch.nn as nn
i... | seqskip_train_seq1eH_lastfm1_only.py | Apache-2.0 | 14,619 | 29c838f3be9f2f0ca9c8d466d456e5cb9ccf8c49 | Python | py | |
import numpy as np
import seaborn as sns
import torch
from torch.nn.utils.rnn import PackedSequence, pad_packed_sequence
from tqdm import tqdm
import matplotlib.pyplot as plt
from pathlib import Path
from src.data.common import get_loader
from src.models.character_models import (
CrossEntropyLoss,
character_r... | src/ood_detection.py | MIT | 9,183 | 29c8395521f04547a249d75907b503b3d36688d0 | Python | py | |
# Once for All: Train One Network and Specialize it for Efficient Deployment
# Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han
# International Conference on Learning Representations (ICLR), 2020.
import math
import os
import random
import time
import json
import numpy as np
import torch.nn as nn
import torch... | ofa/imagenet_classification/run_manager/run_manager.py | MIT | 20,031 | 03d8cc386b0833d37c293ac3fb14c8a670b44e73 | 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 ... | examples/gpt-2/gpt2_train_main.py | Apache-2.0 | 9,500 | 29c85173ecdf1c3711cb171c0f27af12c1132495 | Python | py | |
from __future__ import division
from PIL import Image, ImageFilter, ImageOps, ImageChops
import numpy as np
#from torchvision.transforms import *
import torch
import random
import numbers
import pdb
import time
try:
import accimage
except ImportError:
accimage = None
scale_choice = [1, 1/2**0.25, 1/2**0.5... | dataset/preprocess_data.py | MIT | 13,103 | 29c86546268f2ed3bb02816ae82052af9743ec8e | 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.
"""General utility code for building PyTorch-based agents in ParlAI.
Contains the following main utilities:
* TorchAgen... | parlai/core/torch_agent.py | MIT | 54,132 | 7085884a5d8e3cdcb919a2a2c298dbadd22b65cb | Python | py | |
# *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. 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... | trt/test_infer_trt.py | BSD-3-Clause | 11,811 | d7d05692480b0687e4ad170f7070940a70320e0d | Python | py | |
import os
import time
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pydensecrf.densecrf as dcrf
import torch
from PIL import Image
from torchvision import transforms
from losses import binary_cross_entropy_loss
from losses import multilabel_soft_margin_loss
from model import fc_resnet50
from mo... | solver.py | MIT | 22,496 | 29c8a3a732fbdaa4394df3885e2cda9ee77f0fe0 | 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 math
import numpy as np
import torch
from fairseq import utils
from fairseq.criterions import FairseqCriterion... | infoxlm/fairseq/examples/speech_recognition/criterions/ASG_loss.py | MIT | 5,489 | 29c8a3d78e4e05bee00abcab60396145217c9567 | Python | py | |
# coding=utf-8
# Copyright 2020 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
#
# Unless required by applicable... | src/transformers/tokenization_utils_base.py | Apache-2.0 | 158,440 | 425942668cd97c901a6ebc4734b784d533500850 | Python | py | |
import sys
import time
import torch
import torch.optim as optim
import torch.nn.functional as F
from torch.optim.lr_scheduler import MultiStepLR
from torchvision.utils import make_grid
import mixed_precision
from utils import test_model
from stats import AverageMeterSet, update_train_accuracies
from datasets import D... | RepreLearn_Deep/task_self_supervised.py | MIT | 6,377 | e9039f27b55b19e74dc78160e98f663315ecf444 | Python | py | |
import json
import logging
import os
from typing import Tuple
import torch
import transformers
from transformers import Trainer as HFTrainer
from transformers import set_seed
from transformers.hf_argparser import DataClass
from transformers.optimization import Adafactor, AdamW
from transformers.trainer import Trainer
... | run.py | MIT | 8,103 | 29c8bfc8356b0582d204b0527dc79a540a9eaf70 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.