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 |
|---|---|---|---|---|---|---|---|
from typing import Dict
import torch
from overrides import overrides
from allennlp.common import Params
from allennlp.common.checks import ConfigurationError
from allennlp.data import Vocabulary
from allennlp.modules.text_field_embedders.text_field_embedder import TextFieldEmbedder
from allennlp.modules.time_distribu... | allennlp/modules/text_field_embedders/basic_text_field_embedder.py | Apache-2.0 | 2,989 | fec6efcdf28f4dbf562384c37f52373ae2856094 | Python | py | |
# Copyright 2021 TUNiB Inc.
import torch
import torch.distributed as dist
from transformers import GPT2Tokenizer
from oslo.models.gptj.modeling_gptj import (
GPTJForCausalLM,
GPTJForSequenceClassification,
GPTJModel,
)
class Test3DInference:
def __init__(self, num_gpus):
self.num_gpus = num... | tests/gptj/gptj_test_3d_inference.py | Apache-2.0 | 5,159 | ff4a8732ae1d40cfec98c7149a45cb35161d6a49 | Python | py | |
import pytest
import torch
import torchgeometry
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_smoke(batch_size):
x = torch.rand(batch_size, 2, 3)
assert x.shape == (batch_size, 2, 3), x.shape
| test/smoke_test.py | Apache-2.0 | 216 | 52d90d01bec3ff9b4b9e1ac5b7456d87bc1cf9b4 | Python | py | |
import warnings
from typing import Union, Sequence, Dict
import torch
import numpy as np
from ...data.subject import Subject
from .. import Transform
from . import RandomTransform
from typing import List
TypeTransformsDict = Union[Dict[Transform, float], Sequence[Transform]]
class Compose(Transform):
"""Compo... | torchio/transforms/augmentation/composition.py | Apache-2.0 | 8,806 | fec73c74f440fe46e754f7e88b3222db7c3ff0e5 | Python | py | |
import torch_audiomentations
from torch import Tensor
from hw_asr.augmentations.base import AugmentationBase
class Gain(AugmentationBase):
def __init__(self, *args, **kwargs):
self._aug = torch_audiomentations.Gain(*args, **kwargs)
def __call__(self, data: Tensor, sample_rate):
x = data.unsq... | hw_asr/augmentations/wave_augmentations/Gain.py | MIT | 381 | b22a0b76f32c7ec217cec918d22b0616d4354d0c | Python | py | |
import math
import torch
import torch.nn as nn
from ibug.roi_tanh_warping.pytorch_impl import (roi_tanh_polar_to_roi_tanh,
roi_tanh_to_roi_tanh_polar)
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1,
mix_padding=False, padding_modes=['replicate', 'circu... | ibug/face_parsing/rtnet/rtnet.py | MIT | 17,485 | ff5ba57c8837e33c75b3056e4b2370f4c3f52919 | Python | py | |
# pylint: disable=attribute-defined-outside-init
"""A recurrent network with LSTM for encoding context of RL tasks."""
import torch
from torch import nn
from metarl.torch.modules import MLPModule
class RecurrentEncoder(MLPModule):
"""This recurrent network encodes context of RL tasks.
Context is stored in ... | src/metarl/torch/embeddings/recurrent_encoder.py | MIT | 4,249 | ff025d7e56fc5b6c3a7acf0185bfc7c4b38686fc | Python | py | |
"""Ideal words - extraction and aggregation functions
Usage:
nn_compatibility_test.py --model=<file> [--ext=<file>] [--att] [--sit] [--rel] [--ppmi]
nn_compatibility_test.py (-h | --help)
nn_compatibility_test.py --version
Options:
-h --help Show this screen.
--version Show version.
--m... | tests/compatibility/nn_compatibility_test.py | MIT | 5,156 | 12d2b9c77c492a8577c52e6d7354e425d25f838c | Python | py | |
"""model.py"""
import torch.nn as nn
import torch.nn.init as init
class Discriminator(nn.Module):
def __init__(self, z_dim):
super(Discriminator, self).__init__()
self.z_dim = z_dim
self.net = nn.Sequential(
nn.Linear(z_dim, 1000),
nn.LeakyReLU(0.2, True),
... | disentanglement/model.py | MIT | 10,071 | d702f2ef44020a883668af66516441e14620f56c | Python | py | |
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in th... | finite_ntk/experiments/simple_reg/ntk_transfer_regression.py | Apache-2.0 | 5,247 | fec7f37465b9d0edf70e42657372ac1343ed62d2 | Python | py | |
"""Train a neural net."""
import argparse
import copy
import hashlib
import logging
import shutil
import time
import torch
from ..profiler import TorchProfiler
LOG = logging.getLogger(__name__)
class Trainer():
epochs = None
n_train_batches = None
n_val_batches = None
clip_grad_norm = 0.0
cli... | openpifpaf/network/trainer.py | CC-BY-2.0,CC-BY-4.0 | 17,385 | fec81a1fdefa31f5e8524e495e6842a55c7e950d | Python | py | |
import torch
from fcos_core.modeling.box_coder import BoxCoder
from fcos_core.structures.bounding_box import BoxList
from fcos_core.structures.boxlist_ops import boxlist_nms
from fcos_core.structures.boxlist_ops import cat_boxlist
from fcos_core.structures.boxlist_ops import remove_small_boxes
from ..inference import ... | fcos_core/modeling/rpn/retinanet/inference.py | BSD-2-Clause | 6,853 | e64c9758ca2abfeacefeabcd723199f54be84006 | Python | py | |
import torch
import sys
import abganlibs.models.dcgan as dcgan
import numpy as np
# Check the parameter is legal or not
if 1 == len(sys.argv) or ".pth" != sys.argv[1][-4:]:
saved_model = "saves/WGAN_5/netG_epoch_750_32.pth"
#exit('USE: decoder.py MODEL.pth')
else:
saved_model = sys.argv[1]
# Set number of... | tools/level generator/wgan_5.py | MIT | 1,772 | 1075be9ef4784dab69d5825824746a69416f2f1b | Python | py | |
import PIL
import torch
import torch.nn as nn
import cv2
from skimage.color import lab2rgb, rgb2lab, rgb2gray
from skimage import io
import matplotlib.pyplot as plt
import numpy as np
class ColorizationNet(nn.Module):
def __init__(self, input_size=128):
super(ColorizationNet, self).__init__()
MIDLEVEL_FEATU... | app.py | Apache-2.0 | 3,341 | fec86afc8408bf1af48b5c923200772712b6750b | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
def conv1dbnrelu(in_channels, out_channels, **kwargs):
return nn.Sequential(
nn.Conv1d(in_channels, out_channels, **kwargs),
nn.BatchNorm1d(out_channels),
nn.ReLU(inplace=True),
)
class Linear(nn.Module):
def __ini... | evaluate/previous_works/HoHoNet/lib/model/horizon_refinement/linear.py | MIT | 629 | fec87732aaca14167c0fea75b8ad6339155d0536 | Python | py | |
import logging
from collections import OrderedDict
import torch
from .SRRaGAN_model import SRRaGANModel
from .base_model import nullcast
logger = logging.getLogger('base')
from . import optimizers
from . import schedulers
from dataops.batchaug import BatchAug
from options.options import opt_get
class SRFlowModel(... | codes/models/SRFlow_model.py | Apache-2.0 | 11,746 | f94a3e94151d52686be15797205929da7b54a995 | Python | py | |
import argparse
import os
from re import A
import warnings
import easymd
import mmcv
import torch
import os.path as osp
from mmcv import Config, DictAction
from mmcv.cnn import fuse_conv_bn
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (get_dist_info, init_dist,
... | tools/test.py | Apache-2.0 | 9,397 | dfd8803776ebb54dcecc33501a27bc0fdc01c61a | Python | py | |
import copy
from functools import partial
import json
import logging
import os
import pickle
from typing import Optional, Sequence, List, Any
import ml_collections as mlc
import numpy as np
import pytorch_lightning as pl
import torch
from torch.utils.data import RandomSampler
from openfold.data import (
data_pipe... | openfold/data/data_modules.py | Apache-2.0 | 25,046 | fec88f02607b8366552658583213bdbdb49db7c4 | Python | py | |
"""
Uses LightCNN to generate features from a face
Code is based off the implementation from https://github.com/AlfredXiangWu/LightCNN by AlfredXiangWu
Download and extract the model from here: https://drive.google.com/uc?id=0ByNaVHFekDPRWk5XUFRvTTRIVmc&export=download
"""
__author__ = "Animesh Koratana"
import torc... | lightcnn-embed/embeddings.py | Apache-2.0 | 2,170 | fec88fe16ee4b7819cbb51ad2ae2d6b269f975ca | Python | py | |
from __future__ import absolute_import
import sys
import torch
import torch.nn as nn
import torch.nn.init as init
from torch.autograd import Variable
import numpy as np
from pdb import set_trace as st
from skimage import color
from IPython import embed
import PerceptualSimilarity.models.pretrained_networks as pn
fro... | codes/PerceptualSimilarity/models/networks_basic.py | MIT | 8,092 | 7c149e521a8dabb14d24f840430d84772383ca11 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
Implements the Generalized R-CNN framework
"""
from collections import OrderedDict
import torch
from torch import nn
import warnings
from torch.jit.annotations import Tuple, List, Dict, Optional
from torch import Tensor
class GeneralizedRCNN... | object_detection/model/detection/generalized_rcnn.py | MIT | 4,686 | fec8adc88b3ecd7825adcd25e371594949c7204b | Python | py | |
from collections import namedtuple
from typing import List
import torch
import torch.nn as nn
class CharLM(nn.Module):
"""CNN + highway network + LSTM
# Input:
4D tensor with shape [batch_size, in_channel, height, width]
# Output:
2D Tensor with shape [batch_size, vocab_size]
# Argume... | model.py | MIT | 4,440 | fec8c78c7cac2dcf1345cf4f9d3ccdbe40492e21 | Python | py | |
import torch
import torch.nn as nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
from torch.autograd import Variable
# Hyper Parameters
sequence_length = 28
input_size = 28
hidden_size = 128
num_layers = 2
num_classes = 10
batch_size = 300
num_epochs = 20
learning_rate = 1e-2
train_... | tutorials/02-intermediate/recurrent_neural_network/own.py | MIT | 2,548 | fec8d89c95e7389496daf90019b36236f150884b | Python | py | |
import os
import math
import time
import datetime
from multiprocessing import Process
from multiprocessing import Queue
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import imageio
import torch
import torch.optim as optim
import torch.optim.lr_scheduler as lrs
class time... | src/utility.py | MIT | 10,446 | fec8dfe71235bb26c6fd6491d315a9773c9c8a7e | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
class BasicBlock(nn.Module):
def __init__(self, in_chan, out_chan, stride=1... | facexlib/parsing/resnet.py | MIT | 2,357 | fec8e82cf64469fb51be21ad5130217052addbda | Python | py | |
import torch
import sys
import logging
def main():
if not torch.cuda.is_available():
logger.info('No GPU device available')
sys.exit(1)
logger.info('GPU device available')
if __name__ == '__main__':
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
stream_handler = loggi... | DARTS/train.py | MIT | 430 | fec8f3b8ecf2c1bf1b059156481b21313a6966e7 | Python | py | |
# %% md
# Notebook for generating and saving SBM PATTERN graphs
# %%
import numpy as np
import torch
import pickle
import time
import networkx as nx
# %matplotlib inline
import matplotlib.pyplot as plt
import scipy.sparse
# %% md
# Generate SBM PATTERN graphs
# %%
def schuffle(W, c):
... | data/SBMs/smoothing_pattern.py | MIT | 13,144 | d757bfeaa76c0623208d707cd4649fce20b3a85c | Python | py | |
import torch.nn as nn
import torch
import numpy as np
from models.spectral_normalization import SpectralNorm
from torch.autograd import Variable
Tensor = torch.cuda.FloatTensor
import torch.autograd as autograd
import scipy.io
import argparse, json, glob, os, sys
from models.unet import Unet
from pathlib import Path
... | helper/gan_helper_fun.py | BSD-3-Clause | 44,271 | 4bb1c93522a628aa607c743af075bdff3485da0d | 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... | pl_bolts/callbacks/torch_ort.py | Apache-2.0 | 2,046 | fec900e1e1535dd89b2ed8c4c086d43ea993e79e | Python | py | |
import plyfile
import argparse
import torch
import numpy as np
import skimage.measure
import scipy
import mrcfile
import os
N_CHANNELS = 22
def create_samples(N=256, voxel_origin=[0, 0, 0], cube_length=2.0):
# NOTE: the voxel_origin is actually the (bottom, left, down) corner, not the middle
voxel_origin = ... | extract_double_semantic_shapes.py | MIT | 7,337 | fec91ba26b52cdeeb9e403d69775559eb63bbe2a | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import time
from torch.autograd import Variable
from util import *
def build_targets(
pred_boxes, pred_conf, pred_cls, target, anchors, num_anchors, num_classes, grid_size, ignore_thres
):
nB = target.size(0)
nA = num_anchors
nC = num_... | yolo_layer.py | MIT | 8,488 | fec95f13b1e5835e99e8809ba16325d4db1a74ab | 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 io
import logging
import os
import pickle
import random
import socket
import struct
import subprocess
import warnings
from argparse imp... | fairseq/distributed_utils.py | MIT | 20,288 | 3439508c94987c4956ba09e801dea095a3e844ce | Python | py | |
import torch
from lib.pytorch_misc import enumerate_by_image, diagonal_inds, to_variable, random_choose
from config import REL_FG_FRACTION
@to_variable
def proposal_assignments_gtbox(rois, gt_boxes, gt_classes, gt_rels, image_offset, RELS_PER_IMG, sample_factor=-1):
"""
Assign object detection proposals to gr... | lib/proposal_assignments_gtbox.py | MIT | 3,180 | 1eba6eec9f1ec1154c2ae7dccf58311f2c0322ed | Python | py | |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import argparse
import csv
import json
import logging
import os
import random
import sys
import numpy as np
import torch
import torch.nn.functional as F
from pytorch_transformers import (WEIGHTS_NAME, AdamW, BertConfig,
... | src/model/ner.py | Apache-2.0 | 18,869 | fec98a48a02ae1c5594824b9b9ca1aa6b226f559 | Python | py | |
import os, sys
import yaml
import importlib
import logging
from itertools import product
from more_itertools import collapse
import torch
import pytorch_lightning as pl
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger
from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor
fro... | traintrack/utils/model_utils.py | MIT | 4,053 | fec98e8e36cb65475dda14f356a4dcf4971e71cd | 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 json
import logging
import os
import errno
import time
import torch
import numpy as np
from omegaconf import OmegaConf
from lib.pc_ut... | downstream/insseg/lib/utils.py | MIT | 11,704 | 5e2a8d53e92ead92b99d8b086dfac4b0fb6e4f91 | Python | py | |
from typing import Dict, Optional
import torch
from torch.nn import Module
from allennlp.common import Registrable
from allennlp.modules import Embedding
class SeqDecoder(Module, Registrable):
"""
A `SeqDecoder` abstract class representing the entire decoder (embedding and neural network) of
a Seq2Seq a... | allennlp/modules/seq2seq_decoders/seq_decoder.py | Apache-2.0 | 2,827 | fec9a0ee07b82a4826278af7374e8a3a4e003cde | Python | py | |
# -*- coding: utf-8 -*- #
"""*********************************************************************************************"""
# FileName [ upstream/mockingjay/builder.py ]
# Synopsis [ build the transformer model for downstream usage ]
# Author [ Andy T. Liu (https://github.com/andi611) ]
# Copyri... | s3prl/upstream/mockingjay/builder.py | MIT | 20,838 | fec9a4285eeaed00ab4deccf6d19c32020355631 | Python | py | |
import argparse
import logging
# pytorch_lightning can cause issues if
# torch or other torch libraries are imported first
# noinspection PyUnresolvedReferences
import pytorch_lightning as pl
from transformers import BertTokenizerFast
from torch.utils.data import DataLoader
from pytorch_lightning import loggers as pl... | rel/train.py | Apache-2.0 | 8,032 | fec9b62333ebd09a773f22b5c4fbf956c56b9265 | Python | py | |
import torch
from torch.utils import data
import json
import os
import numpy as np
import soundfile as sf
DATASET = 'WHAM'
# WHAM tasks
enh_single = {'mixture': 'mix_single',
'sources': ['s1'],
'infos': ['noise'],
'default_nsrc': 1}
enh_both = {'mixture': 'mix_both',
... | bin/ssw/dataset.py | MIT | 6,003 | fec9c7abb1722b60707195df4dde8fc10332ea1b | Python | py | |
import time
import os
import enum
import torch
from torchtext.legacy.data import Dataset, BucketIterator, Field, Example
from torchtext.data.utils import interleave_keys
from torchtext.legacy import datasets
import spacy
from .constants import BOS_TOKEN, EOS_TOKEN, PAD_TOKEN, DATA_DIR_PATH
class DatasetType(enum.... | utils/data_utils.py | MIT | 16,121 | 03ec2892e944bc36ebb897c1bee0b5a43fa33c6c | Python | py | |
# Copyright 2021 Quantapix 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 l... | std/huggingface/beam.py | MIT | 17,975 | f9b7275bf85a03d57cc9ec8411d92b8f451a902b | Python | py | |
import torch
import json
import re
import random
import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('--percentage', type=str, default='None', help='Percentage')
args = parser.parse_args()
percentage = args.percentage
with open("createData/multiwoz21/delex_query_results.json") as f... | create_percentage_multiwoz_dataset.py | Apache-2.0 | 35,906 | 5fc5e130e1d1a818353e12451441d8f9659390a0 | Python | py | |
import os
import numpy as np
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from collections import Counter
import torch.utils.data as data_utils
from torch.utils.data import Dataset
import pickle
import tqdm
from sklearn.model_selection import train_test_split
from ... | expert/ECG/mlp.py | MIT | 6,667 | feca1dadd6fcc13b3cc1304fd81cbcd98e1b37f1 | Python | py | |
# Copyright (c) FULIUCANSHENG.
# Licensed under the MIT License.
import torch
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
from torch.cuda.amp import autocast
from unitorch.models.deberta import (
DebertaV2ForClassification as _DebertaV2ForClassification,
)
from unitorch.cli import cac... | unitorch/cli/models/deberta/modeling_v2.py | MIT | 2,850 | f9923437bf056cc0bcb74ec9257c368b3721639d | Python | py | |
import math
import torch
import torch.nn as nn
from actnn.layers import QLinear, QReLU, QBatchNorm1d
from cogdl.utils import spmm
from cogdl.operators.actnn import QDropout
class ActGCNLayer(nn.Module):
"""
Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
"""
def __init__(self, in_feat... | cogdl/layers/actgcn_layer.py | MIT | 1,779 | feca4439b68a988add1075fa908575c21c16cfd2 | Python | py | |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Common data processing utilities that are used in a
typical object detection data pipeline.
"""
import logging
import numpy as np
import pycocotools.mask as mask_util
import torch
from fvcore.common.file_io import PathMa... | detectron2/data/detection_utils.py | Apache-2.0 | 21,014 | 1e5f43ef04f2ab17cd54268419e521bf680ba114 | Python | py | |
# /usr/bin/env python3.6
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2021, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification,... | TrainingExtensions/torch/src/python/aimet_torch/adaround/adaround_tensor_quantizer.py | BSD-3-Clause | 8,291 | feca5de67dff1e9f40bea32e25691d5ae6940619 | Python | py | |
import cv2
import math
import numpy as np
import torch
import transforms3d
class Compose(object):
def __init__(self, transforms):
self.transformers = []
for tr in transforms:
transformer = eval(tr['callback'])
parameters = tr['parameters'] if 'parameters' in tr else None
... | lib/net/data_transforms.py | MIT | 7,999 | 103c32f35853ffc636eeffb81081ada25327c71b | Python | py | |
import numpy as np
import torch
import compressors
import algorithms
import topologies
config = {
"seed": 42,
"algorithm": "choco",
"topology": "ring",
"matrix_size": 100,
"hyperparameter_num_samples": 20,
"hyperparameter_range_min": 1e-4,
"hyperparameter_range_max": 1.308,
"theta_num... | gossip_run.py | MIT | 8,525 | feca7a7977b6f372a22e849d45c7eeedb5c5adb5 | Python | py | |
import torch
import torch.nn as nn
import pickle
from collections import OrderedDict
class Bottleneck(nn.Module):
""" Adapted from torchvision.models.resnet """
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer=nn.BatchNorm2d, dilation=1, use_dcn=False):
sup... | backbone.py | MIT | 11,296 | 4251edf184c11abc62dbafdc6a420edea2788a68 | Python | py | |
""" This file stores some common functions for learners """
import torch
import torch.nn as nn
import pdb
import math
import numpy as np
import logging
import os
import torch.distributed as dist
import torch.nn.functional as F
from collections import defaultdict
class CrossEntropyLabelSmooth(nn.Module):
def __init... | NAS/APS-channel-search/utils/utils.py | Apache-2.0 | 7,965 | feca8210d3311d7f9aaa4ce0271506960a4871af | Python | py | |
import os
# Used to ignore warnings generated from StackingCVClassifier
import os
# Used to ignore warnings generated from StackingCVClassifier
import warnings
import matplotlib.pyplot as plt
# For reading, visualizing, and preprocessing data
import numpy as np
import pandas as pd
import seaborn as sns
import torch... | submissions/make_submissions_stacking.py | MIT | 6,268 | f98ce73f06531faaa3f61169133f78863262a85c | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from mgnet.geometry import Camera, Pose, calc_smoothness, inv2depth, match_scales, view_synthesis
__all__ = ["DeepLabCE", "OhemCE", "MultiViewPhotometricLoss"]
class DeepLabCE(nn.Module):
"""
Hard pixel mining with cross entropy loss, for sem... | mgnet/modeling/loss.py | Apache-2.0 | 11,809 | feca88ed2143f8084f220be772580fa3942e52aa | Python | py | |
import os
import time
import faiss
import random
import torch
from colbert.utils.runs import Run
from multiprocessing import Pool
from colbert.modeling.inference import ModelInference
from colbert.evaluation.ranking_logger import RankingLogger
from colbert.utils.utils import print_message, batch
from colbert.ranking.... | colbert/ranking/batch_retrieval.py | MIT | 1,819 | b288f73d96d3b763992399e115ad239779cbf5c9 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from agents.drgn import DRGNAgent
from agents.sdgn import soft_value_based_model_entropy_activation_function
from modules.drgn import DRGNNetwork
from utils.numba_utils import *
from utils.torch_utils import *
from utils.hparams imp... | agents/sdrgn.py | MIT | 5,425 | d7987a3017236292eec17997f3b49627b5e3881f | Python | py | |
from __future__ import absolute_import, division, print_function, unicode_literals
from collections import namedtuple
from .observer import *
from .fake_quantize import *
import torch.nn as nn
class QConfig(namedtuple('QConfig', ['activation', 'weight'])):
"""
Describes how to quantize a layer or a par... | windows_packages_gpu/torch/quantization/qconfig.py | Apache-2.0 | 5,638 | 346c3e704e052838bd6981786cb67cca4c5aab9e | Python | py | |
# https://github.com/jhoffman/cycada_release/blob/master/cycada/data/usps.py
import gzip
import os.path
from urllib.parse import urljoin
import numpy as np
from PIL import Image
from torch.utils import data
import logging
import requests
logger = logging.getLogger(__name__)
def maybe_download(url, dest):
"""Dow... | dset_loaders/usps.py | Unlicense | 3,114 | fecb00269b20ed802aee43ee46bc6d1c352ac123 | Python | py | |
import torch
import torch.nn.functional as F
from torch import nn
import math
from util import box_ops
from util.misc import (NestedTensor, nested_tensor_from_tensor_list,
accuracy, get_world_size, interpolate,
is_dist_avail_and_initialized, inverse_sigmoid)
from .backbone ... | models/deformable_detr.py | MIT | 9,078 | 1081b16c5f8f37eeb5877496b335f92043d2b5fb | 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 typing import List, Tuple, Optional
import fastmri
import torch
import torch.nn as nn
import torch.nn.functional as F
from ... | fastmri/models/varnet_3d.py | MIT | 11,063 | 6b2e7852d95fc2f6a90e2b78e11e0e96a3833054 | Python | py | |
"""
Code adapted from the StarGAN v2: https://github.com/clovaai/stargan-v2
"""
import os
from os.path import join as ospj
import time
import datetime
from munch import Munch
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.utils as vutils
from .model import build_model, semantic... | src/models/sg_sem_cont/train.py | MIT | 13,528 | fecb240b515a8cc75e8670a44c8ff2ec1801f495 | Python | py | |
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from . import sigmoid_focal_loss_ext
class SigmoidFocalLossFunction(Function):
@staticmethod
def forward(ctx, input, target, gamma=2.0, alpha=0.25):
ctx.save_for_backward(inpu... | mmdet/ops/sigmoid_focal_loss/sigmoid_focal_loss.py | Apache-2.0 | 1,679 | 7ce6f7daed3a66e0bfed3fac981cd642ccf3cf9b | Python | py | |
import re
import torch
import os
import boto3
from botocore import UNSIGNED
from botocore.client import Config
from model import IrisNet
labels = ["setosa", "versicolor", "virginica"]
class PythonPredictor:
def __init__(self, config):
# download the model
bucket, key = re.match("s3://(.+?)/(.+)",... | test/apis/traffic-splitter/pytorch_predictor.py | Apache-2.0 | 1,405 | fecb3dd75184c32a5e47f8f05b4ac6ea43b7437c | Python | py | |
# Owner(s): ["module: fft"]
import torch
import unittest
import math
from contextlib import contextmanager
from itertools import product
import itertools
import doctest
import inspect
from torch.testing._internal.common_utils import \
(TestCase, run_tests, TEST_NUMPY, TEST_LIBROSA, TEST_MKL)
from torch.testing._i... | test/test_spectral_ops.py | Intel | 61,252 | fecb4735976ed99f4cc9c2f6bf67819bd0f306b5 | Python | py | |
import math
from typing import List, Optional, Tuple
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import TransformerDecoder, MultiheadAttention, LayerNorm
from torch.nn.init import xavier_uniform_
from torch.nn.modules.transformer import TransformerDecoderLayer
from code_transformer... | code_transformer/modeling/decoder/transformer.py | MIT | 34,565 | 7065ce5978a9ebfaecd21bcea4fa62325124f293 | Python | py | |
import pandas as pd
import numpy as np
import math
from scipy.stats import nct
import torch
from copy import deepcopy
import matplotlib.pyplot as plt
from ..constants import ktrx as constants
from ..constants.constants import (
CoefPriorDictKeys,
)
from ..constants.ktrx import (
DEFAULT_REGRESSOR_SIGN,
DEF... | orbit/models/ktrx.py | Apache-2.0 | 49,132 | ff1afb832b9e1046a08a1b672a0ce4fdb9d5e7b1 | Python | py | |
import math
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
from fedml_api.model.cv.group_normalization import GroupNorm2d
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106c... | fedml_api/model/cv/resnet_gn.py | Apache-2.0 | 7,767 | fecb7c0a70372a89bee808e1e5cf8f7cb229814c | Python | py | |
import mmcv
import numpy as np
import torch
from mmdet3d.core import Box3DMode, CameraInstance3DBoxes, LiDARInstance3DBoxes
from mmdet3d.datasets import ObjectNoise, ObjectSample
def test_remove_points_in_boxes():
points = np.array([[68.1370, 3.3580, 2.5160, 0.0000],
[67.6970, 3.5500, 2.50... | tests/test_pipeline/test_transforms_3d.py | Apache-2.0 | 5,396 | fecb7c9d60e47fc99cb4ffc8588881dccd8c566d | Python | py | |
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as Functional
class PSRNN_Model(nn.Module):
"""Container module with an encoder, a recurrent module, and a decoder."""
def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, tie... | forecaster/models/PSRNN_Model.py | Apache-2.0 | 3,240 | fecb7df3a027672b231d039b3fb1056924ba2672 | Python | py | |
import unittest
import torch
from fastreid.layers import BatchNorm, GhostBatchNorm
import torch.nn.functional as F
class TestGhostBN(unittest.TestCase):
def test_ghostbn(self):
dummy_inputs = torch.randn(64, 3, 64, 32)
mean_sp1 = torch.mean(dummy_inputs[::2], dim=[0, 2, 3])
var_sp1 = tor... | tests/layers/test_ghostbn.py | Apache-2.0 | 1,238 | 6b1d7f9b4e2397b6af8257654a2183626cc9cf15 | Python | py | |
"""
Script to evaluate the network quality if it is trained for densities or for colors.
They are tested with world-space training and the best configuration from eval_network_configs
"""
import sys
import os
sys.path.insert(0, os.getcwd())
import numpy as np
import sys
import os
import shutil
import sub... | applications/volnet/eval_Fourier.py | MIT | 12,366 | 7082be3dab11108c7163f74e1c69b8587b158955 | Python | py | |
from __future__ import absolute_import, division, print_function
import logging
import os
import json
import random
import glob
import torch
import tqdm
import torch.utils.data
import numpy as np
from unilm.old_school_transformers import (
BertTokenizer,
RobertaTokenizer,
XLMRobertaTokenizer,
)
import s2s... | unilm/s2s-ft/s2s_ft/utils.py | Apache-2.0 | 10,014 | 1049604b6938e874154bcf85f78701f8fffc468b | Python | py | |
import os
import torch
from collections import OrderedDict
from abc import ABC, abstractmethod
from . import networks
class BaseModel(ABC):
"""This class is an abstract base class (ABC) for models.
To create a subclass, you need to implement the following five functions:
-- <__init__>: ... | OSABA/pix2pix/models/base_model.py | MIT | 10,451 | fecbdf18df93ce4c9fe91d448dc3bb0299313be1 | Python | py | |
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
# Also available under a BSD-style license. See LICENSE.
import torch
from torch_mlir_e2e_test.torchscript.framework imp... | e2e_testing/torchscript/basic.py | Apache-2.0 | 34,451 | d7d140c69f03077f5c0c44dc553e03f65d5f5663 | 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 ... | test/parser/testcases/elu/elu_generator.py | Apache-2.0 | 1,308 | fecbfa771277910dc30958c4969e67110ba148e4 | Python | py | |
#!/usr/bin/env python3
from __future__ import print_function
import torch
import unittest
from torch.nn import Embedding
from captum.attr._models.base import (
configure_interpretable_embedding_layer,
remove_interpretable_embedding_layer,
InterpretableEmbeddingBase,
)
from ..helpers.basic_models import... | tests/attr/models/test_base.py | BSD-3-Clause | 2,856 | 653f5ae8dd43942f6e62ae4051b50ea4bf45928b | Python | py | |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import torch
import glob
import os
from tqdm import tqdm
# import sys # might be necessary
# sys.path.append('..')
from utils import make_dataloaders, create_loss_meters, update_losses, log_results
from nets import MainModel
cuda = torch.cuda.is_ava... | HPC/baseline_hpc.py | MIT | 2,814 | 12ce99252020296447bcd568c46e9e9fda9b509d | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
import torch
class AttentionUNet(torch.nn.Module):
"""
UNet, down sampling & up sampling for global reasoning
"""
def __init__(self, input_channels, class_number, **kwargs):
super(AttentionUNet, self).__init__()
down_... | src/deepke/relation_extraction/document/module.py | MIT | 3,791 | fecc40e8127cf05920979637b024cf88c6a1d23a | Python | py | |
import torch
import torch.nn as nn
class ValueFunction(nn.Module):
"""
The Value Function
:param optimizer: (torch.optim.Optimizer) The optimizer.
:param network: (nn.Module) The network.
"""
def __init__(self, network: nn.Module, optimizer: torch.optim.Optimizer) -> None:
super().__... | src/rl_replicas/common/value_function.py | MIT | 743 | fecc42b64df896d283c07cc5e4f0a53aec08cbac | Python | py | |
#! /usr/bin/python
# -*- encoding: utf-8 -*-
# Adapted from https://github.com/CoinCheung/pytorch-loss (MIT License)
import torch
import torch.nn as nn
import torch.nn.functional as F
import time, pdb, numpy
from accuracy import accuracy
class AMSoftmax(nn.Module):
def __init__(self,
in_feats,
... | loss/cosface.py | MIT | 1,628 | f9577a2ad6da4013fb13e58b1c73cc46777cd5f9 | 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/trainer/connectors/profiler_connector.py | Apache-2.0 | 2,297 | 5fad9bca8ecf118059894c59ebc21b7dcf3a8374 | Python | py | |
# MIT License
#
# Copyright (c) 2020 CNRS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish... | pyannote/audio/models/segmentation/PyanNet.py | MIT | 4,897 | 7cc31276486a4c8bbcfb1b4e7eb38762610f62a7 | Python | py | |
# Copyright 2021 Medical Imaging Center, Vingroup Big Data Insttitute (VinBigdata), Vietnam
#
# 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
... | spine/dataset_mapper.py | Apache-2.0 | 5,275 | fecc7e479929c236545adebf56f81670669198c5 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
# transpose
FLIP_LEFT_RIGHT = 0
FLIP_TOP_BOTTOM = 1
class BoxList(object):
"""
This class represents a set of bounding boxes.
The bounding boxes are represented as a Nx4 Tensor.
In order to uniquely determine the bou... | maskrcnn_benchmark/structures/bounding_box.py | MIT | 10,421 | 5f2590a7ba542137804bed8d7ccec54d9b92358c | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from unittest import mock
import torch
from ax.models.torch.botorch_defaults import _get_model, get_and_fit_model
from ax.utils.common.testutils import TestCase
from botorch.exceptions.errors import UnsupportedError
from bo... | ax/models/tests/test_botorch_defaults.py | MIT | 3,158 | a901be0a17f409cc0494102f57b948368c0c5964 | Python | py | |
################################################################################
# MIT License
#
# Copyright (c) 2018
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, in... | rnn/part1/dataset.py | Apache-2.0 | 1,968 | fecce2d41fe57f408788ef9748b6dc2dfdd083f4 | Python | py | |
import math
import sys
import torch
task = sys.argv[1]
from nltk.tokenize.treebank import TreebankWordDetokenizer
detokenizer = TreebankWordDetokenizer()
assert task == "QNLI"
def mean(values):
return sum(values)/len(values)
sensitivityHistogram = [0 for _ in range(40)]
from scipy.optimize import linprog
de... | estimateS1ensitivity_QNLI_getSensitivityParts_PMLM_raw_1billion.py | MIT | 9,961 | 458665844105c8615a1a691ca60114e65052d8dd | Python | py | |
import os
import random
import time
import numpy as np
import logging
import argparse
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.multiprocessing as mp
import torch.distributed a... | tool/train.py | MIT | 20,624 | 7c2c1f798b11046befb7fb3ebc4ff9df12742a60 | Python | py | |
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence
from torch.nn.utils.rnn import pad_packed_sequence
from tests.torch.modules.seq2seq.seq2seq_base import PAD
class ResidualRecurrentEncoder(nn.Module):
"""
Encoder with Embedding, LSTM layers, residual connections and optional
dropo... | tests/torch/modules/seq2seq/encoder.py | Apache-2.0 | 3,506 | 1e0891ca765236130a7596097f8af4d5df5c1ce7 | Python | py | |
import torch.nn as nn
from .base import BaseDetector
from .. import builder
from ..registry import DETECTORS
from mmdetection.core import bbox2result
@DETECTORS.register_module
class SingleStageDetector(BaseDetector):
def __init__(self,
backbone,
neck=None,
bbo... | mmdet/models/detectors/single_stage.py | Apache-2.0 | 2,481 | fecd0a69df241818ee77ba976758c3c9052c270e | Python | py | |
import sys, os
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import transforms
from torchvision.utils import save_image
from tqdm import tqdm
from PIL import Image
from src.model import FeatureExtracter... | main.py | MIT | 9,967 | ff9506d33659a9c3bc91b942414dd95ca715a772 | 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.
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq.modules import (
Layer... | fairseq/model_parallel/modules/transformer_sentence_encoder.py | MIT | 1,884 | 101eca7bd4d143195ec89ffb1cfdd7b05060fcf1 | Python | py | |
import os
import torch
import numpy as np
from network import *
def savetxt(name, loss_log):
np_loss_log = np.array(loss_log)
np.savetxt(name, np_loss_log)
def get_files(path):
# read a folder, return the complete path
ret = []
for root, dirs, files in os.walk(path):
for filespath in file... | resnet50_in_pre_training/utils.py | MIT | 2,899 | fecd52958a2ce295a90e42efcc606bbf9533e886 | Python | py | |
"""image classifier callbacks"""
import warnings
from typing import Any, Dict, List, Optional, Union
import torch
from torch import Tensor
from torchvision import transforms
import pytorch_lightning as pl
from pytorch_lightning import Callback
from uetai.logger import SummaryWriter
from uetai.callbacks.utils import ... | src/uetai/callbacks/image_monitor.py | MIT | 10,102 | fecd705508560d5d00025d37e3ef01bd2deb86bd | Python | py | |
'''
Learning How To Train Neural Networks in Parallel (The Right Way)
===
Author: Nicholas Geneva (MIT Liscense)
url: https://nicholasgeneva.com/blog/
github: https://github.com/NickGeneva/blog-code
===
conda install -c conda-forge cupy cudnn cutensor nccl
'''
import torch
import os
from .dist import Distributed
try:
... | parallel-nn/distributed/nccl.py | MIT | 7,662 | d7db56a6e8251bcb48f2055f00e1b56a20c05548 | Python | py | |
import sys
import os
import numpy as np
import argparse
import random
import openslide
import PIL.Image as Image
import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
import torch.utils.data as data
import torchvision.transforms as transforms... | MIL-nature-medicine-2019/MIL_test.py | MIT | 5,029 | cc2c77bc10404459e7c9ead44d70fe99ad07852e | Python | py | |
import torch as th
from torch import nn
from torch.optim import Adam, RMSprop
import numpy as np
from common.Agent import Agent
from common.Model import ActorNetwork, CriticNetwork
from common.utils import entropy, index_to_one_hot, to_tensor_var
class A2C(Agent):
"""
An agent learned with Advantage Actor-... | gymfc/examples/controllers/A2C.py | MIT | 5,937 | fecdbd7022b3de8cfaf32dd46070281f2152d14e | Python | py | |
#!/usr/bin/env python3 -u
# 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.
"""
Translate pre-processed data with a trained model.
"""
import torch
from fairseq import bleu, checkpoint_utils,... | generate.py | MIT | 8,313 | ff13ec7ffb3f454f10c2f9c8d8a529fd510051c6 | Python | py | |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: romanshen
@file: variational_bayes.py
@time: 2021/05/07
@contact: xiangqing.shen@njust.edu.cn
"""
import math
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
from omegaco... | src/models/variational_bayes.py | Apache-2.0 | 16,960 | fece57c85e68f44a644f4b537272c0b67630718a | Python | py | |
import torch
from torch_geometric.utils import get_laplacian
def test_get_laplacian():
edge_index = torch.tensor([[0, 1, 1, 2], [1, 0, 2, 1]], dtype=torch.long)
edge_weight = torch.tensor([1, 2, 2, 4], dtype=torch.float)
lap = get_laplacian(edge_index, edge_weight)
assert lap[0].tolist() == [[0, 1, 1... | test/utils/test_get_laplacian.py | MIT | 788 | dfe8ed944a4c78b1454792aa6ccebcf625edcda0 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.