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 |
|---|---|---|---|---|---|---|---|
# Adapted from https://github.com/pyg-team/pytorch_geometric/blob/master/examples
# /multi_gpu/distributed_sampling.py.
import os
import argparse
from filelock import FileLock
import torch
import torch.nn.functional as F
from torch_geometric.datasets import Reddit, FakeDataset
from torch_geometric.loader import Neig... | python/ray/ml/examples/pytorch_geometric/distributed_sage_example.py | Apache-2.0 | 7,831 | 03b9a60136fe996d3e927c3dcf471ccd718ffb19 | Python | py | |
import torch
from tqdm import tqdm
from src.utils.fixseed import fixseed
from src.evaluate.action2motion.evaluate import A2MEvaluation
# from src.evaluate.othermetrics.evaluation import OtherMetricsEvaluation
from torch.utils.data import DataLoader
from src.utils.tensors import collate
import os
from .tools import... | src/evaluate/gru_eval.py | MIT | 5,433 | 3a3fcf22fa7ccc662303f8799b2f72daf18d2649 | Python | py | |
import torch.nn as nn
import torch
import torch.utils.checkpoint as checkpoint
class AtrouMMU(nn.Module):
def __init__(self,inf, scale_factor=10,bias=False):
super(AtrouMMU, self).__init__()
print(inf,scale_factor)
self.conv1= nn.Sequential(nn.Conv2d(inf, inf, kernel_size=3,padding=1,stride... | graphs/models/universal_embedding.py | MIT | 11,723 | fdd568aa17dc9e227b0e794bcd83b34aa5f00fa0 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
LRELU_SLOPE = 0.1
def init_weights(m, mean=0.0, std=0.01):
classname = m.__class__.__name__
if classname... | pororo/models/tts/hifigan/model.py | Apache-2.0 | 12,031 | 3a40009d95207c64b51f0ed2867191c70302dd76 | Python | py | |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#
# This test must run as a separate process since we assert ORT things
# are unavailable before we import torch_ort, then test that they do
# in fact become available after importing it. The act of importing
# torch_ort makes... | orttraining/orttraining/eager/test/ort_init.py | MIT | 922 | 3a40058701ee135c0c7f72d19bff612484a7081d | Python | py | |
import torch
import pandas as pd
import PIL
import os
import gc
import matplotlib.pyplot as plt
import time
import numpy as np
from torch._C import device
from torchvision import datasets, models, transforms
import torch.nn as nn
import torch.optim as optim
from torchvision.transforms import ToTensor
def main():
... | Old_Scripts/template_split0.2_biggroups_ResNet18_epoch40.py | Apache-2.0 | 6,699 | 3a400739ed3902cb3973c46cd3adbb42202ae530 | Python | py | |
'''
Dataset for training
Written by Whalechen
'''
import math
import os
import random
import numpy as np
from torch.utils.data import Dataset
import nibabel
import SimpleITK as sitk
from scipy import ndimage
import blosc
blosc.set_nthreads(1)
class CbctOnTheFlyDataset(Dataset):
def __init__(self, img_list, set... | datasets/cbct_onthefly.py | MIT | 8,509 | 03f0a86ce6a76eaca6d286babdad821f520e2bda | Python | py | |
import pytest
import torch
import torchgeometry as tgm
from torch.autograd import gradcheck
import utils # test utilities
from common import TEST_DEVICES
@pytest.mark.parametrize("device_type", TEST_DEVICES)
@pytest.mark.parametrize("batch_size", [1, 2, 5, 6])
def test_inverse_pose(batch_size, device_type):
# ... | test/test_pinhole.py | Apache-2.0 | 5,883 | 3a402602d3727a2f6536e321bccbc847da81df53 | Python | py | |
import torch
import torchvision
import numpy as np
from torch.nn import init
import torch.nn as nn
import sys
sys.path.append("..") # 为了导入上层目录的d2lzh_pytorch
import utils as d2l
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
num_inputs = 784
num_outputs = 10
class LinearNet(nn.Module... | codenew/d2lzh_pytorch/softmax_pytorch.py | Apache-2.0 | 915 | 7c333b7578f13208b624685b3cc78cb986813b4e | Python | py | |
# ------------------------------------------------------------------------------
# From an mp.data.datasets.dataset_segmentation.SegmentationDataset, create a
# mp.data.pytorch.PytorchDataset. There are different types of datasets:
#
# PytorchSeg2DDataset: the length of the dataset is the total number of slices
# (fo... | mp/data/pytorch/pytorch_seg_dataset.py | MIT | 9,972 | 4b5a3a14a1c8adf2c256f89ef9fd38a054dd7323 | Python | py | |
import matplotlib
matplotlib.use('Agg')
import os, sys
import yaml
from argparse import ArgumentParser
from tqdm import tqdm
import imageio
import numpy as np
from skimage.transform import resize
from skimage import img_as_ubyte
import torch
from sync_batchnorm import DataParallelWithCallback
from modules.generator i... | testcameradrive.py | MIT | 6,791 | 3a409bf850b1839c7c1a43209202e38685df219c | Python | py | |
"""
Copyright (c) 2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writin... | tests/torch/test_models/mobilenet_v3.py | Apache-2.0 | 8,766 | 3a409f9707f808f7e6d43dbf752c74e6c0ac06bd | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import os
import logging
import random
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
from parser_train import parser_, relative_path_to_absolute_path
from tqdm import ... | caco_proda_finetune/generate_pseudo_label.py | MIT | 5,483 | 3a40a291071a7cfd0f72783641a03fbf68883bfb | Python | py | |
# General
import numpy as np
import random
import argparse
import json
import commentjson
import joblib
import os
import pathlib
from collections import OrderedDict
# Pytorch
import torch
import pytorch_lightning as pl
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.callbacks import Mode... | SubGNN/train_config.py | MIT | 10,954 | 3a40a3dc3c7dad1402d90748b300d9094d71e4ef | Python | py | |
import torch
import numpy as np
import pickle
import os
import pandas as pd
import simple_nn as nn
# import flood_depth.flood_depth as flood_depth
from sklearn.base import BaseEstimator
class EnsembleLearner(BaseEstimator):
def __init__(self, config, names, learners, hidden=10):
"""
Args:
... | learners/ensemble_learner.py | MIT | 7,248 | 3a40d52bccff4cdfd15a46ff06f1e5cabc63a612 | Python | py | |
"""
Contains the worker side implementation of the FedAvg algorithm.
"""
import io
import time
from datetime import datetime
import logging
import msgpack
import torch
from dc_federated.utils import get_host_ip
from dc_federated.backend import GLOBAL_MODEL, GLOBAL_MODEL_VERSION, WID_LEN
from dc_federated.backend imp... | src/dc_federated/algorithms/fed_avg/fed_avg_worker.py | Apache-2.0 | 4,725 | 3a40d9a5df66d47daa191216d80eebcbcd1657b4 | Python | py | |
from typing import Optional, List
from pathlib import Path
import logging
from pydantic import BaseModel, validator
from transformers import (
AutoModel,
AutoModelForQuestionAnswering,
AutoTokenizer,
BertForSequence... | pygaggle/run/evaluate_kaggle_highlighter.py | Apache-2.0 | 7,561 | 3a40de320fad422e306584e535e0e6089234a36e | Python | py | |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, 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 cop... | source/modelling/run_squad.py | MIT | 29,769 | 3a40e0716413351e2cfec0dc4a2b07624f151bc4 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
def calc_iou(a, b):
area = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1])
iw = torch.min(torch.unsqueeze(a[:, 2], dim=1), b[:, 2]) - torch.max(torch.unsqueeze(a[:, 0], 1), b[:, 0])
ih = torch.min(torch.unsqueeze(a[:, 3], dim=1), b[:, 3]) - torch.max(torch.u... | pytorch_retinanet/losses.py | Apache-2.0,MIT | 5,408 | 429426423eb67b652baa2d1b3077c1b3b2c4648e | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
from abc import ABCMeta, abstractmethod
import torch
import torch.nn as nn
from mmcv.runner import BaseModule, auto_fp16, force_fp32
from mmseg.core import build_pixel_sampler
from mmseg.ops import resize
from ..builder import build_loss
from ..losses import accuracy
... | mmseg/models/decode_heads/decode_head.py | Apache-2.0 | 10,630 | 6b05a5fb1deeae696d52b41957e8e713dc721120 | Python | py | |
'''
use utilities/lisp_generator.py to seed simgan refiner and discriminator blocks
'''
### packages
import numpy as np
import torch
### sys relative to root dir
import sys
from os.path import dirname, realpath
sys.path.append(dirname(dirname(realpath(__file__))))
### absolute imports wrt root
from codes.utilities i... | misc/seed_simgan.py | MIT | 11,005 | f9c9c65efc6dcd6267b2a5cdf96187d00b9cb2ed | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import operator_benchmark as op_bench
import torch
import torch.nn as nn
"""Microbenchmarks for Linear operator."""
linear_configs_short = op_bench.config_list(
a... | benchmarks/operator_benchmark/pt/linear_test.py | Intel,X11 | 1,182 | f935ff79c284a13b49557e4c58379f3af88ac151 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from onmt.modules.Transformer.Layers import XavierLinear as Linear
# Relative Multihead Attention
# Only for self-attention
class RelMultiHeadAttn(nn.Module):
def __init__(self, n_head, d_model, d_head, dropatt=0,
tgt_len=None, ext_... | onmt/modules/RelativeAttention.py | MIT | 15,622 | fd86016f70cbfa23472a5e19e2838f748ec7a3d9 | Python | py | |
"""
This file includes the torch models. We wrap the three
models into one class for convenience.
"""
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
class LandlordLstmModel(nn.Module):
def __init__(self):
super().__init__()
self.lstm = nn.LSTM(162, 128, batch... | douzero/dmc/models.py | Apache-2.0 | 16,445 | 3a411aaf59c6f069dca8341aabafee61578f651b | Python | py | |
__all__ = ['OnnxClip']
from typing import Optional
import torch
from torch import nn
from onnx2torch.node_converters.registry import add_converter
from onnx2torch.onnx_graph import OnnxGraph
from onnx2torch.onnx_node import OnnxNode
from onnx2torch.utils.common import OnnxMapping
from onnx2torch.utils.common import ... | onnx2torch/node_converters/clip.py | Apache-2.0 | 2,957 | 3a4123baeb8a9deebf646d55daf6a76c8d9fdec4 | Python | py | |
import torch
from torch_geometric.utils import negative_sampling
def create_link_label(pos_edge_index, neg_edge_index):
"""
Create labels for link prediction, based on positive and negative edges
Args:
pos_edge_index (torch.tensor): Positive edge index [2, num_edges]
neg_edge_index (torc... | torch_geometric/graphgym/models/transform.py | MIT | 1,391 | 802621292f1521230b53794db9415de339d5b7b4 | Python | py | |
import torch
import torch.nn as nn
class ODEfunc(nn.Module):
"""
Base Class to represent the Neural Network for the ODE
i.e. dz/dt = f(z, t; θ)
To use this Class, subclass it and add User specific Neural Network architecture
Important function:
- forward_with_grad
We need the following ... | ODEfunc.py | MIT | 2,344 | cc2c67bc3b8b86f064165284d9d22ed5dc365a2d | Python | py | |
# Created by Lena
import time
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
torch.manual_seed(2021)
device = torch.device("cuda:0" if... | cnn/cnn_classifier.py | BSD-3-Clause | 6,271 | 7ce24ca238b0454977c3c99298e05d7d6dda4f77 | Python | py | |
r"""Vanilla RNN language model."""
import argparse
from typing import ClassVar, Dict, List, Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from lmp.model._base import BaseModel
from lmp.tknzr._base import BaseTknzr
class RNNModel(BaseModel):
r"""Vanilla RNN language model.
Use... | lmp/model/_rnn.py | Beerware | 16,484 | 5faef0dde25bb40dc89cadce5c7a96be659eb2e5 | Python | py | |
from typing import Optional, Tuple
from torch_geometric.typing import Adj, OptTensor, PairTensor
import torch
from torch import Tensor
from torch.nn import Parameter
from torch_scatter import scatter_add
from torch_sparse import SparseTensor, matmul, fill_diag, sum, mul
from torch_geometric.nn.conv import MessagePassi... | autogl/module/nas/space/gasso_space/gcn_conv.py | MIT | 7,861 | 3a41b9d7d1cb29334f8be1d842d2e2a84be7973f | Python | py | |
"""Assortment of layers for use in models.py.
Author:
Chris Chute (chute@stanford.edu)
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import math, copy
import reformer
import util
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from torch.autograd import Variable
... | layers.py | MIT | 9,089 | e993019750e043f5ac048a6b50a33b55358fec4b | Python | py | |
from torch.utils.data import Dataset
import torch
from tqdm import tqdm
import numpy as np
import os
from torch.utils.data import Dataset, DataLoader
import pandas as pd
import json
import sys
from pkgutil import simplegeneric
from transformers import XLNetTokenizer, XLNetModel
from keras.preprocessing.sequence import ... | torchmeta/datasets/clinic.py | MIT | 5,900 | 45b2946aef16bb86c04a52c52370cc06421d4790 | Python | py | |
import argparse
import torchani
import torch
import timeit
import tqdm
# parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('filename',
help='Path to the xyz file.')
parser.add_argument('-d', '--device',
help='Device of modules and tensors',
... | tools/inference-benchmark.py | MIT | 2,883 | 3a41f63710609e1f83fdc549e8e101f34d38ebd3 | Python | py | |
"""
Copyright (C) 2010-2020 Alibaba Group Holding Limited
"""
import os
import re
import sys
import errno
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
from torch.hub import download_url_to_file
HASH_REGEX = re.compile(r"-([a-f0-9]*)\.")
def _create_netblock_list_from_str_(s,... | GENet/base.py | Apache-2.0 | 60,442 | 45916b056bc8c83c7325a9dd32fbd23a6fcde60d | Python | py | |
from functools import partial
import torch
import torch.nn as nn
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm2d') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
... | ops.py | MIT | 3,381 | 6b29145ba3630acf41bc6cdab56b2845776834e3 | 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 numpy as np
import torch
from . import FairseqDataset, data_utils
def collate(samples, pad_idx, eos_idx, fixed_pad_length... | edgelm/fairseq/data/monolingual_dataset.py | MIT | 9,085 | 5e6706f6d41d029f8d1d6e633e4092f6892a28f9 | Python | py | |
import torch
from transformer import attention
def test_attention():
# TODO this should be a mini-batch of phrases of word embeddings
query = torch.diag(torch.Tensor(range(10)))
key = torch.diag(torch.Tensor(range(10)))
value = torch.ones(10, 10)
context, weights = attention(query, key, value)
... | tests/test_transformer/test_attention.py | MIT | 1,016 | fdafa18273b1f4f2fddaf0fe9432d60736b3a34e | Python | py | |
import pdb
import argparse
import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
from torch.optim.lr_scheduler import MultiStepLR
from torchvision.utils import make_grid
from torchvision import datasets, transforms
from ut... | train_cutout.py | ECL-2.0 | 9,195 | 3a422f18b4dd78eb7b9a319974d3b07a80267765 | Python | py | |
import argparse
import datetime
import glob
import os
import re
import time
from pathlib import Path
import numpy as np
import torch
from tensorboardX import SummaryWriter
from eval_utils import eval_utils
from pcdet.config import cfg, cfg_from_list, cfg_from_yaml_file, log_config_to_file
from pcdet.datasets import b... | tools/test.py | Apache-2.0 | 8,239 | 45d6ea05ed8385fa09aa79870d7a654048a4b805 | Python | py | |
import torch
#
torch.multiprocessing.set_sharing_strategy('file_system')
import pandas as pd
import numpy as np
import sys
import os
import pickle
import argparse
# local imports
import train_model
import experiment_routines as experiments
from subsetting_exp import subset_experiment
# can add different
from datase... | code/scripts/hyperparameter_search.py | BSD-3-Clause | 3,588 | 3a4254814ff3394454a24a78e7559debf8079a8a | Python | py | |
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as dsets
from torch.autograd import Variable
train_dataset = dsets.MNIST(root='./data/MNIST',
train=True,
transform=transforms.ToTensor(),
... | recNN.py | MIT | 4,609 | 12ca96d89f05dc212b4a1b90edf19f759bed0cae | Python | py | |
import os, sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import numpy as np
from tqdm import tqdm
from arguments import get_args
from augmentations import get_aug
from models import get_model
from tools import AverageMeter, knn_monitor, Logger, file_exist_check, visualize_ma... | main_ddp.py | MIT | 4,982 | 1ee0c8728aac0b7b0f54a1dd0e88760051542001 | Python | py | |
import pytest
from mapreader import classifier
from mapreader import loadAnnotations
from mapreader import patchTorchDataset
import numpy as np
import torch
from torch import nn
import torchvision
from torchvision import transforms
from torchvision import models
PATH2IMAGES = "./examples/non-geospatial/classificati... | tests/test_non_geo_pipeline.py | MIT | 8,027 | dfa50091667e6058e172af2ef3f5f3062245773a | Python | py | |
import torch
import torchvision
from dataset import CarvanaDataset #这个dataset是自己做的,看dataset.py
from torch.utils.data import DataLoader
def save_checkpoint(state, filename="my_checkpoint.pth.tar"):
print("=> Saving checkpoint")
torch.save(state, filename)
def load_checkpoint(checkpoint, model):
print("=>... | ML/Pytorch/image_segmentation/semantic_segmentation_unet/utils2.py | MIT | 2,418 | d75fd88c389a289417039f44d2c0509e51449f5b | Python | py | |
import argparse
import logging
import os
import random
import sys
import numpy as np
import torch
import wandb
sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../")))
from fedml_api.data_preprocessing.cifar10.data_loader import load_partition_data_cifar10
from fedml_api.data_preprocessing.cifar10... | fedml_experiments/standalone/fedavg_affinity/main_fedavg_affinity.py | Apache-2.0 | 15,912 | 804d4e2825d3a3c00791840de4839e6137e30bd1 | Python | py | |
# -*- coding: utf-8 -*-
import os
import torch
import torch.optim
import network as models
from tensorboardX import SummaryWriter
import numpy as np
from tqdm import tqdm
from utils.util import *
from utils.util_args import get_args
from utils.util_loader import data_loader
from utils.util_loss import \
... | main.py | MIT | 9,552 | 3a42d9ada8e63ca6c29a752da8d4a59f1c6b5d2b | Python | py | |
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from PIL import Image
from utils.parse_config import *
from utils.utils import build_targets
from collections import defaultdict
##import matplotlib... | utils/models.py | MIT | 14,724 | 7c3e5b8f3ef564039d4f2f34ecb35841cadf17bb | Python | py | |
from __future__ import print_function
import torch
import numpy as np
from PIL import Image
import os
# Converts a Tensor into an image array (numpy)
# |imtype|: the desired type of the converted numpy array
def tensor2no_norm_im(input_image, imtype=np.uint8):
sflag = False
if isinstance(input_image, torch.Te... | utils/util.py | MIT | 3,816 | b29790182cbc202f541ed0c4c7c9f81882233dda | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, xavier_init
import torch
import numpy as np
from mmdet.ops import NonLocal2D
from ..builder import NECKS
@NECKS.register_module
class WFPNLargeKernel(nn.Module):
"""by weighting bottom-up and top-down process outputs
(botto... | mmdet/models/necks/wfpn_largekerne.py | Apache-2.0 | 4,370 | 127794cb6a5baa41cdc165890e2fff02e6ecab9f | Python | py | |
import logging
import pickle
from typing import Optional, Dict, Tuple, Union
from omegaconf import DictConfig, OmegaConf as oc
from tqdm import tqdm
import torch
from .model3d import Model3D
from .feature_extractor import FeatureExtractor
from .refiners import PoseRefiner, RetrievalRefiner
from ..utils.data import Pa... | pixloc/localization/localizer.py | Apache-2.0 | 5,827 | a971e4a3d090c7ab5841dbfaf3774127b6077d67 | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.intrinsic as nni
import torch.nn.qat as nnqat
import torch.nn.functional as F
from torch.nn import init
from torch.nn.modules.utils import _single, _pair, _triple
from torch.nn.parameter import Parameter
from typing import TypeVar
_BN_CLASS_MAP = {
1: ... | torch/nn/intrinsic/qat/modules/conv_fused.py | Intel | 21,151 | b25a4cf5ca7b7d9dd7a46143fbce0d3a6195fe46 | Python | py | |
from utilities import eprint, exp, log, timing, valid
from task import Task, EvaluationTimeout
import random
import gc
import signal
from program import *
from utilities import *
from collections import Counter
import math
import pregex as pre
from groundtruthRegexes import gt_dict
gt_dict = {"Data column no. "+str(... | likelihoodModel.py | Unlicense | 15,141 | 3a42ff2df22abd8394d1f1d65fa7c74c1839b824 | Python | py | |
import argparse, time
import numpy as np
import networkx as nx
import torch
import torch.nn as nn
import torch.nn.functional as F
from dgl import DGLGraph
from dgl.data import register_data_args, load_data
from gcn import GCN
#from gcn_mp import GCN
#from gcn_spmv import GCN
def evaluate(model, features, labels, mask... | examples/pytorch/gcn/train.py | Apache-2.0 | 4,654 | f9c52f42cd302f407785e164b4be37d04ba1bcd5 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch
import torch.nn as nn
class DeepLabCE(nn.Module):
"""
Hard pixel mining with cross entropy loss, for semantic segmentation.
This is used in TensorFlow DeepLab frameworks.
Paper: DeeperLab: Single-Shot Image Parser
Reference: https://g... | projects/DeepLab/deeplab/loss.py | Apache-2.0 | 1,776 | 3a43087b7c1a2b4d2b249fad117724dbd0f14fdd | Python | py | |
'''Used with MixMatch
Downloaded from:
https://github.com/YU1ut/MixMatch-pytorch
'''
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import pdb
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, dropRate=0.0, activate_before_residual=False):
su... | src/cgan/classification/models/wideresnet.py | MIT | 8,222 | b2997ea31e2018a2e889df2283b0eb20c38a599a | Python | py | |
import cv2
import os
import torch
from .models import Darknet
from .utils.parse_config import *
from .utils.utils import load_classes, non_max_suppression, rescale_boxes
from .utils.datasets import pad_to_square, resize
from .utils.google_drive import download_file_from_google_drive
import torchvision.transforms as tra... | detection_api/detection.py | OLDAP-2.3 | 3,194 | 3a4321727ce170cf544584ee7f614f2de9a02731 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
from tqdm.auto import tqdm
from torch.nn.utils.rnn import pad_sequence
from moses.interfaces import MosesTrainer
from moses.utils import CharVocab, Logger
class PolicyGradientLoss(nn.Module):
def forward(self, outputs, targets, rew... | moses/organ/trainer.py | MIT | 15,115 | 3a4333e3b0ea4f8bdab51d3d48f75d73cbb20ffe | Python | py | |
import torch.nn.functional as func
def train_unit(config, model, device, federated_train_loader, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(federated_train_loader):
# send model to federated points
model.send(data.location)
data, target = data.to(... | train.py | Apache-2.0 | 1,199 | ff925fa32ecf189a4e4f16699626f10b5d2d400d | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import model
from model import repackage_hidden
import torch
import torch.optim as optim
import torch.nn as nn
from torch.a... | projects/continual-lm/learner/static_learner.py | BSD-3-Clause | 2,504 | 29f35499253a563b04b580cf2fd0026553ca5194 | Python | py | |
#! /usr/bin/env python
"""
Copyright (c) Facebook, Inc. and its affiliates.
All rights reserved.
This source code is licensed under the license found in the LICENSE file in the
root directory of this source tree.
Implementation of Disambiguation Model.
Author(s): Satwik Kottur
"""
from __future__ import ... | evaluation/model/disambiguate/disambiguator.py | MIT | 1,147 | 3a434cf8c8d46d99999d5a880bbc21dfcada485b | Python | py | |
import os.path
import time
import librosa
import random
import math
import numpy as np
import glob
import torch
from torch.utils.data import Dataset
from PIL import Image, ImageEnhance
import torchvision.transforms as transforms
def audio_normalize(samples, desired_rms = 0.1, eps = 1e-4):
rms = np.maximum(eps, np.... | data/stereo_dataset.py | CC-BY-4.0 | 3,946 | 4549248a7e29e58897265e0eaa0c330629ae402b | Python | py | |
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from copy import deepcopy
from cell_operations import ResNetBasicblock
from genotypes import Structure
from prog_search_cells import NAS201SearchCell as SearchCell
class TinyNetwork_Prog(nn.Module):
def __init_... | s2/prog_search_model_s2.py | MIT | 8,640 | 3a4384f5f1e7d8ec8ca42fc674fe9cfe6538dd01 | 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
import torch
import torch.nn.functional as F
from fairseq import metrics, utils
from fairseq.criterions import FairseqCriterion, ... | fairseq/criterions/wav2vec_criterion_autoencoder_FL.py | MIT | 8,148 | 3a4387c3c869691227bd82f3200ec2dbd2d02526 | Python | py | |
r"""
The MIT License (MIT)
Copyright (c) 2020 Varuna Jayasiri
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, me... | darts/models/components/feed_forward.py | Apache-2.0 | 4,628 | 65248d72ecac67a4d9b42a894fefd415a8865afa | Python | py | |
import math
import torch
from torch import nn
from torch.nn import Dropout
from src.transformer.operations import softmax
class TransformerEncoder(nn.Module):
def __init__(self, num_layers: int, d_model: int, num_heads: int, d_ff: int, layer_norm_eps: float):
super(TransformerEncoder, self).__init__()
... | src/transformer/modules.py | MIT | 7,813 | 3a438fb7c062bb8c03e5bffce8a4d2fb92e8c13c | Python | py | |
import torch
import numpy as np
def find_distance(X_n, X_o):
"""
:param X_n: tensor [[x_0, y_0, t_0], ..., [x_j, y_j, t_j]], containing all manipulatable nodes for a given leg
:param X_o: tensor [[x_s, y_s, t_s], ..., [x_e, y_e, t_e]] points of sim contact
:return d_s: distance vector to first object,... | sample/server/src/optimization/feed_forward_utils.py | MIT | 6,562 | f9fbd18d2ffdd1cd748a1750fa64ae1e37b283aa | Python | py | |
from typing import Any, Dict, List, Union
from overrides import overrides
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.common.registrable import Registrable
from allennlp.training.scheduler import Scheduler
from allennlp.training.optimizers import Optimizer
class LearningRateSche... | allennlp/training/learning_rate_schedulers/learning_rate_scheduler.py | Apache-2.0 | 3,850 | 3a43ae3d4b2fd1eba50bc015c836d165eb6649fe | Python | py | |
# Copyright 2022 san kim
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | retrieve_images.py | Apache-2.0 | 9,497 | 1e4edbdf7aeb7eaad5cab58d06b1e5abac530911 | Python | py | |
import numpy as np
import pandas as pd
import torch
from transformers import RobertaForMaskedLM, RobertaConfig, DataCollatorForLanguageModeling, Trainer, TrainingArguments
from .data import MaskedDatasetPreparer, get_mlm_train_validation_dataset
import os
import random
device = torch.device("cuda") if torch.cuda.... | src/train_mlm.py | MIT | 2,460 | 3a43d73711641ddf15e5755eaf76262d4a15f736 | Python | py | |
import math
import torch
import torch.nn.functional as F
from kge import Config
# https://github.com/pytorch/pytorch/issues/7455#issuecomment-513062631
class LabelSmoothingLoss(torch.nn.Module):
def __init__(self, dim=-1):
super(LabelSmoothingLoss, self).__init__()
self.dim = dim
self.smoot... | kge/util/loss.py | MIT | 14,215 | 4b9b36a74203b29e33a32dd90d9e81446d2a2393 | Python | py | |
from PIL import Image
from hypergan.samplers.base_sampler import BaseSampler
import numpy as np
import random
import torch
import torch.nn as nn
import time
class FactorizationBatchWalkSampler(BaseSampler):
def __init__(self, gan, samples_per_row=4, session=None):
BaseSampler.__init__(self, gan, samples_pe... | hypergan/samplers/factorization_batch_walk_sampler.py | MIT | 2,183 | fcdbe949d4f68fe5347c6fc94614c8aacf932de7 | Python | py | |
import torch
from torch import Tensor
import torch.nn as nn
import math
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, c_in, c_out, stride=1):
super().__init__()
self.conv1 = nn.Conv2d(c_in, c_out, kernel_size=3, stride=stride,
padding=1, bias=Fals... | train/src/dualnet7x7.py | MIT | 3,935 | 5e175e491196a926cb5bf6a6a9d2c79a34c1f8be | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# Copyright (c) 2018-2019 NVIDIA CORPORATION. All rights reserved.
import torch
import pycocotools.mask as mask_utils
# transpose
FLIP_LEFT_RIGHT = 0
FLIP_TOP_BOTTOM = 1
class Mask(object):
"""
This class is unfinished and not meant for... | pytorch/sagemakercv/core/structures/segmentation_mask.py | Apache-2.0,BSD-2-Clause-FreeBSD | 7,496 | ff4faf248aafca738d58702540dc8e3d48acafe9 | Python | py | |
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import gpustat
import numpy as np
from problems import Flatten
def gpu_mem():
stats = gpustat.GPUStatCollection.new_query()
for gpu in stats:
util = gpu.entry['memory.used']
break
return u... | examples/runtime.py | MIT | 3,227 | 7c2cb95f25b34af28d9c92c15b2d30f6aaa86d74 | Python | py | |
import sys
import cv2 as cv
import numpy as np
# pip install torch==0.3.1 (0.4.0 does not work)
# pip install torchvision==0.2.1
import torch
import torch.nn as nn
import torchvision.models as models
import torchvision.transforms as transforms
from torch.autograd import Variable
sys.path.append('/vframe/tools/')
from... | vsearch/feature_extractor_pytorch.py | MIT | 3,906 | 3a43fc72648ef544facb6a6b060edee9c3b9e8ce | Python | py | |
# Authors: Divyesh Narayanan <divyesh.narayanan@gmail.com>
#
# License: BSD (3-clause)
import math
import copy
from copy import deepcopy
import warnings
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
class SleepStagerEldele2021(nn.Module):
"""Sleep Staging Architecture fro... | braindecode/models/sleep_stager_eldele_2021.py | BSD-3-Clause | 14,037 | 3a43ff3f24ac09248e685c9b575417beaa8a9f41 | 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/accelerator_connector.py | Apache-2.0 | 45,385 | fd65975618f021d035e29bab965aee17cdac54f4 | Python | py | |
import math
import torch
import torch.nn.functional as F
from torch import nn
from .inference import make_fcos_postprocessor
from .loss import make_fcos_loss_evaluator
# from .inference_reorg import make_fcos_postprocessor
# from .loss import make_fcos_loss_evaluator
# from .loss_adap_range import make_fcos_loss_eval... | maskrcnn_benchmark/modeling/rpn/rfcos/rfcos-ignoress.py | BSD-2-Clause | 8,231 | d734dcb70caedcb6e8596afcb2c4e2cca71d12ea | Python | py | |
from __future__ import absolute_import
import torch
from torch import nn
from torch.nn import functional as F
from ..modules.activated_batch_norm import ABN
__all__ = [
"FPNBottleneckBlock",
"FPNBottleneckBlockBN",
"FPNPredictionBlock",
"FPNFuse",
"FPNFuseSum",
"FPNFinalBottleneckBlock",
... | pytorch_toolbelt/modules/fpn.py | MIT | 7,886 | 3a440ec023e900000542be327dc25cf80ce6d5da | Python | py | |
import torch
from ..UnaryOperators.GradientFilter import Gradient
from ._BinaryFilter import Filter
class L2Similarity(Filter):
def __init__(self, dim=2, device='cpu', dtype=torch.float32):
super(L2Similarity, self).__init__()
self.device = device
self.dtype = dtype
self.gradient... | camp/StructuredGridOperators/BinaryOperators/L2ImageSimilarity.py | MIT | 2,580 | 654c9e3b64c7375a6b843337675ece2d9b63d5ac | Python | py | |
import os
import numpy as np
from numpy.random import uniform
import torch
from torch.utils.data import Dataset
import cv2
def process_path(directory, create=False):
directory = os.path.expanduser(directory)
directory = os.path.normpath(directory)
directory = os.path.abspath(directory)
if create:
... | util.py | BSD-3-Clause-Clear | 9,890 | 52de5601325815f8e9afbca8fd644769139f9807 | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import warnings
from abc import ABCMeta, abstractmethod
import json_tricks as json
import numpy as np
from torch.utils.data import Dataset
from xtcocotools.coco import COCO
from mmpose.core.evaluation.top_down_eval import (keypoint_auc, keypoint_epe,
... | mmpose/datasets/datasets/base/kpt_2d_sview_rgb_img_top_down_dataset.py | Apache-2.0 | 10,610 | 3a443336057b3df073e0dc1887bcc3462aca2cd4 | Python | py | |
import torch
import torch.nn.functional as F
from models.initializer import initialize_model
from algorithms.single_model_algorithm import SingleModelAlgorithm
from configs.supported import process_pseudolabels_functions
from utils import detach_and_clone
class FixMatch(SingleModelAlgorithm):
"""
FixMatch.
... | examples/algorithms/fixmatch.py | MIT | 5,755 | 3a4438cc06d0c7135e00bfb4ba72d23b8e1e8721 | Python | py | |
#--coding:utf-8--
import torch.nn as nn
import torch
import math
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 conv2DBatchNormRelu(nn.Module):
def __init_... | seg_vgg19_3layer/lanenet.py | MIT | 6,008 | 038c7baaf2b5247e1aa19a47542434c8a47312c2 | Python | py | |
import dgl
import torch as to
import torch.nn as nn
import networkx as nx
import matplotlib.pyplot as plt
import dgl.function as df
from dgl.nn.pytorch import GraphConv
DIM_FEAT = 5
def build_graph():
# 0->1, 0->2, 1-2
src = [0, 0, 1]
dst = [1, 2, 2]
graph = dgl.DGLGraph((src, dst))
n_nodes = g... | gcn_tiny.py | Apache-2.0 | 1,584 | 3a4462705f16d256aa45f5efe05b27052688b608 | Python | py | |
import torch
import torch.nn as nn
import math
import torch.nn.functional as F
class DWT(torch.nn.Module):
def __init__(self):
super(DWT, self).__init__()
self.requires_grad = False
def forward(self, x):
x01 = x[:, :, 0::2, :] / 2
x02 = x[:, :, 1::2, :] / 2
x1 = x01[:,... | tiny_generator.py | MIT | 38,340 | b2b51e2b168f6f68645bf778a191890120e52911 | Python | py | |
import torch
import numpy as np
from scipy.signal import get_window
import librosa.util as librosa_util
def window_sumsquare(
window,
n_frames,
hop_length=200,
win_length=800,
n_fft=800,
dtype=np.float32,
norm=None,
):
"""
# from librosa 0.6
Compute the sum-square envelope of a... | src/glow_tts/audio_processing.py | MIT | 2,625 | 3a4467355952fefaba117b6014864139ac319c6b | Python | py | |
import re
import torch
import models.modules as mmodules
import models.utils as mutils
class CycleResnetGenerator(torch.nn.Module):
def __init__(self, in_channels=3, out_channels=None, ngf=64, n_down=2,
n_blocks=9, norm=torch.nn.InstanceNorm2d, keep_prob=0.5,
activation=torch.nn.... | models/networks.py | MIT | 11,413 | d74bfe423d1f39ba64adeb892e933498f8415495 | Python | py | |
import math
import os
import re
import time
import torch
from sacred import observers
from torch import nn
from torch.utils import checkpoint
import utils
from nde import transforms
from utils import NoDataRootError
class NamingObserver(observers.RunObserver):
def __init__(self, basedir, priority):
self... | nsf/experiments/autils.py | MIT | 5,996 | 1e3bcaad724237a4691a7a28c8003294db43af40 | Python | py | |
import os
import sys
import torch
import numpy as np
import nn.vnn2 as vnn
import collections
from torch import nn
from torch.nn import functional as F
from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence
from model.seq2seq_semantic import Module as Base
from models.utils.metric import... | alfred/models/model/seq2seq_im_semantic.py | MIT | 22,958 | 3a4482726ef69a78c75e501cc427a2fc36658aaf | Python | py | |
import os.path as osp
import warnings
from collections import OrderedDict
import torch
from mmdet.core import eval_map, eval_recalls
from .builder import DATASETS
from .pipelines import Compose
import mmcv
import numpy as np
from mmcv.utils import print_log
from terminaltables import AsciiTable
import os.path as os... | mmdet/datasets/ytvis.py | MIT | 13,917 | 2483488fa4e788e9f348bc1bdfa0ab136bc097bd | Python | py | |
import sys
import os
import argparse
import logging
import json
import time
import subprocess
from shutil import copyfile
import numpy as np
from sklearn import metrics
from easydict import EasyDict as edict
import torch
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch.nn import DataP... | bin/train.py | Apache-2.0 | 20,145 | 346350a93bf0087a4627309123ca24d04b6cd84f | Python | py | |
#!/usr/bin/env python3
"""Calculates the Frechet Inception Distance (FID) to evalulate GANs
The FID metric calculates the distance between two distributions of images.
Typically, we have summary statistics (mean & covariance matrix) of one
of these distributions, while the 2nd distribution is given by a GAN.
When run a... | nn.py | MIT | 3,977 | 3a44d5f6856fa12a13c5f2031f2cea2b141f38f9 | Python | py | |
import math
import random
import torch
import numpy as np
import torch_geometric
from sklearn.metrics import roc_auc_score, average_precision_score
from torch_geometric.utils import to_undirected
from typing import Tuple
from .gnn_layers import *
import sys
import numpy as np
import torch.nn.functional as F
from torc... | models/euclidean_vgae.py | MIT | 25,456 | 3a44e29e49747524a496a3725ed6f8d9555851df | Python | py | |
import numpy as np
import random
from collections import namedtuple, deque
from model import QNetwork
import torch
import torch.nn.functional as F
import torch.optim as optim
BUFFER_SIZE = int(1e5) # replay buffer size
BATCH_SIZE = 64 # minibatch size
GAMMA = 0.99 # discount factor
TAU = 1e-3 ... | dqn_agent.py | MIT | 6,458 | 3a44e2f66ca046d6955fd8b4c797dc0146e6edf7 | Python | py | |
# encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
from bisect import bisect_right
import torch
from torch.optim.lr_scheduler import *
# FIXME ideally this would be achieved with a CombinedLRScheduler,
# separating MultiStepLR with WarmupLR
# but the current LRScheduler design doesn't a... | mmt/utils/lr_scheduler.py | MIT | 1,873 | 5f80a0644872c3fd1aac54cac60f7aa3433fb03e | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import six
import logging
import os
import os.path as osp
import copy
from ast import literal_eval
import numpy as np
from packaging import version
import torch
import t... | lib/core/config.py | MIT | 47,448 | 3a44e86a943ab31000ceccf0d621f9d5c798ee31 | Python | py | |
import pytest
import torch
import torchgeometry as tgm
from torch.autograd import gradcheck
import utils # test utils
from torchgeometry.core.depth_warper import normalize_pixel_coordinates
class TestDepthWarper:
eps = 1e-6
def _create_pinhole_pair(self, batch_size):
# prepare data
fx, fy ... | test/test_depth_warper.py | Apache-2.0 | 7,247 | 24b5bfcb8e5418405f8a14166e05153e0d75f689 | Python | py | |
import numpy as np
import torch
import torch.nn.functional as F
from torch.autograd import Variable
def convert_ids_to_toks(token_ids, tokenizer):
"""
Convert tokens id to tokens word
:input:
token_ids: tokens id
tokenizer: tokenizer from Huggingface
"""
special_tokens = tokeniz... | models/transformer/search.py | MIT | 9,308 | 3a4508de40db62482d298c7d98f5fe09a4e387a6 | Python | py | |
import os
import numpy as np
from itertools import cycle
import torch
import torch.optim as optim
from torchvision import datasets
from torch.autograd import Variable
from tensorboardX import SummaryWriter
from utils import weights_init
from utils import transform_config
from networks import Encoder, Decoder
from tor... | training.py | MIT | 6,665 | 3a4540694fc6c15653081127e2671f5ec1e23555 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.