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 |
|---|---|---|---|---|---|---|---|
# 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 Dict, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from torch.nn ... | fairseq/modules/multihead_attention.py | MIT | 22,809 | dfaf226f3982399526f55710bf2f95f6d1ff2616 | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from .model import Model, ModelHelper
import torch
import torch.nn as nn
class ModelHelper_Hotpot(ModelHelper):
def __init__(self, node_encoder, args, bert_config, config_model):
super(ModelHelper_Hotpot, self).__init__(node_encoder... | transformer-xh/model/model_hotpotqa.py | MIT | 1,563 | 3a390a1308dde5f7d0fe1208f9ae7d0e570b2d58 | Python | py | |
# coding=utf-8
# Copyright 2019 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICEN... | src/transformers/models/electra/modeling_electra.py | Apache-2.0 | 71,417 | 4b14a0b012b177a018ae1ab38f6621a0779c06e4 | Python | py | |
import argparse
import os
import pickle
import torch
import data
import models
class BaseOptions:
"""This class defines options used during both training and test time.
It also implements several helper functions such as parsing, printing, and saving the options.
It also gathers additional options defi... | options/base_options.py | BSD-3-Clause | 7,824 | 3a392f98d6ed37b5b95bda2ecca501e19b7ab856 | Python | py | |
import context
import torch
import argparse
import config as cfg
from ipeps.ipeps_lc import *
from ctm.one_site_c4v.env_c4v import *
from ctm.one_site_c4v import ctmrg_c4v, transferops_c4v
from ctm.one_site_c4v.rdm_c4v import rdm2x1_sl
from models import j1j2
import u1sym.sym_ten_parser as tenU1
import unittest
import... | examples/ctmrg_j1j2_u1_c4v.py | MIT | 8,343 | dfecb4f6181830429f5482a4b5238709444c5fcb | Python | py | |
import sys
from functools import partial
import torch
from torch import nn
from torch.optim.lr_scheduler import StepLR, ReduceLROnPlateau, CosineAnnealingLR
from utils import losses
class Config(object):
def __init__(self):
self.path = "../input"
self.model_type = "JPUNet"
self.fold... | src/configs/cbamresnext50_mish_jpunet_cfg.py | MIT | 1,283 | 3a39599f0027ceca9916d41831e78381cf62ea1b | Python | py | |
# Copyright Niantic 2019. Patent Pending. All rights reserved.
#
# This software is licensed under the terms of the Monodepth2 licence
# which allows for non-commercial use only, the full terms of which are made
# available in the LICENSE file.
from __future__ import absolute_import, division, print_function
import n... | monodepth2/layers.py | MIT | 8,283 | 429ccc10aa5d359cb1b36ef8b52254bf3b37d777 | Python | py | |
import torch
import torchvision.ops
from torch import nn
class DeformableConv2d(nn.Module):
def __init__(self,
in_channels,
out_channels,
kernel_size=3,
stride=1,
padding=1,
bias=False):
super(Deformable... | src/network/DCNv2/dcn.py | MIT | 2,486 | 3a397e1c41e1fed17d0c416e5e4a3b3337983d50 | Python | py | |
import torch
from pdb import set_trace as st
import sys
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(dir_path)
from utils_yolo import convert2cpu
from pdb import set_trace as st
def parse_cfg(cfgfile):
blocks = []
fp = open(cfgfile, 'r')
block = None
line = fp.readl... | L3A_Physical/pytorch/yolo_models/cfg_yolo.py | MIT | 9,948 | 45eeccc1f2e41fc6c781f94b4a3c2748b71d03e9 | Python | py | |
import numpy as np
import torch
import torch.nn.functional as F
def logmeanexp_diag(x, device='cuda'):
"""Compute logmeanexp over the diagonal elements of x."""
batch_size = x.size(0)
logsumexp = torch.logsumexp(x.diag(), dim=(0,))
num_elem = batch_size
return logsumexp - torch.log(torch.tensor(... | rlkit/util/mi_estimators.py | MIT | 5,056 | 4598ff61c40f9697872cf088a9cf2a93981fa725 | Python | py | |
import torch
import numpy as np
import librosa
import os
import csv
from torch.utils.data import Dataset
class FxDataset(Dataset):
def __init__(self,
root,
excl_folders=None,
spectra_folder=None,
processed_settings_csv='proc_setting... | src/dataset/dataset.py | BSD-3-Clause | 10,915 | 3a398cebcf85d7f6b9b52ef5efc98fdd95126fe5 | Python | py | |
""" Some data loading utilities """
from bisect import bisect
from os import listdir
from os.path import join, isdir
from tqdm import tqdm
import torch
import torch.utils.data
import numpy as np
import os
import matplotlib.pyplot as plt
N=600
O=2
class _RolloutDataset(torch.utils.data.Dataset): # pylint: di... | data/loaders_each_batch.py | Apache-2.0,MIT | 4,575 | 7c96c7f97d92caf2d2edb878038ba78f7d8bf726 | Python | py | |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
import os
import random
import torch
import torch.distributed as dist
import torch.nn as nn
from yolox.exp.base_exp import BaseExp
class Exp(BaseExp):
def __init__(self):
super().__init__()
... | exps/default/yolox_pelee.py | Apache-2.0 | 10,020 | b2cd85785c147c5335ab7232f11ba86c9b12f50c | Python | py | |
import os
# Workaround for PyTorch spawning too many threads
os.environ['OMP_NUM_THREADS'] = '1'
import argparse
import sys
import math
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from packaging import version
try:
from tqdm import ... | run_reconstruction.py | MIT | 26,990 | fd7ec03c9ee3b0bd1210d0e5e43a520598908eb2 | Python | py | |
import cv2
import random
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import time
from game.flappy_bird import GameState
import os
import sys
class NeuralNetwork(nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.number_of_actions ... | dqn.py | MIT | 8,662 | 3a39d05dfcbe0de145ba14fb22b804328269f8da | Python | py | |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | tests/trainer/test_optimizers.py | Apache-2.0 | 16,115 | 52e085b2b7b8cb36b6242de3da76d1e43f86d5b5 | Python | py | |
from torchvision import transforms
def apply_test_transforms(inp):
# out = transforms.functional.resize(inp, [224])
# out = transforms.functional.to_tensor(out)
# out = transforms.functional.normalize(out, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
transform = transforms.Compose([transforms.Resize(... | cnn_app/input_data_preprocessing.py | MIT | 492 | 3a39e718e3a532a40f76f05e8895cf97b23e3c0d | Python | py | |
import math
import torch
import torch.nn.functional as F
import torch.nn as nn
from maskrcnn_benchmark.modeling.box_coder import BoxCoder
from .loss import make_retinanet_loss_evaluator
from ..anchor_generator import make_anchor_generator_retinanet
from .inference import make_retinanet_postprocessor
from maskrcnn_benc... | maskrcnn_benchmark/modeling/rpn/retinanet/retinanet.py | BSD-2-Clause | 6,178 | 5f22e5bd24b63b7b39a2554870e4c31e58096177 | Python | py | |
"""
The weak_script annotation needs to be here instead of inside torch/jit/ so it
can be used in other places in torch/ (namely torch.nn) without running into
circular dependency problems
"""
import inspect
import weakref
import warnings
import torch
# This is needed. `torch._jit_internal` is imported befor... | windows_packages_gpu/torch/_jit_internal.py | Apache-2.0 | 28,505 | 3a39fc286fe7810a5b9ad036e350a7afe6d412bf | Python | py | |
"""
Training a linear controller on latent + recurrent state
with CMAES.
This is a bit complex. num_workers slave threads are launched
to process a queue filled with parameters to be evaluated.
"""
import argparse
import sys
from os.path import join, exists
from os import mkdir, unlink, listdir, getpid
from time impor... | traincontroller_pepg_ae.py | MIT | 7,502 | 3a3a1f3bc552a84769d523de2edbcf1f82e03e4c | Python | py | |
#!/usr/bin/env python -W ignore::DeprecationWarning
# 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... | train.py | BSD-3-Clause | 16,754 | fdb60f298a064b9b427e1ce638e276b0c51684ca | Python | py | |
import math
import numpy as np
import torch
import torch.nn as nn
__all__ = [ 'Crop', 'Whiten', 'RandomFlipLR', 'RandomBrightness', 'RandomContrast' ]
# image cropping
class Crop(nn.Module):
'''
Random image cropping::
cro = Crop([n,p,q], ycrop, xcrop)
This layer cuts out a specified... | ummon/modules/imgproc.py | BSD-3-Clause | 13,779 | 12a74958ca01a935e1fda1fea17e5cfc8b96f845 | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
from torch.autograd import Variable
class ExternalMemory(object):
def __init__(self, args):
# logging
self.logger = args.logger
# params
self.... | core/memory.py | MIT | 1,919 | 3a3a2cf34488f04d816f841749101883c0a29ff8 | Python | py | |
import numpy as np
from numpy.linalg import inv, det, pinv
import matplotlib.pyplot as plt
from PIL import Image
import torch
from torch.distributions.multivariate_normal import MultivariateNormal
import matplotlib.pyplot as plt
train_on_gpu = torch.cuda.is_available()
device = torch.device('cuda' if train_on_gpu else... | GMM.py | MIT | 6,775 | fda1d06fb03e6e2e7778f5fba82063f374108dba | Python | py | |
"""
Copyright 2020 Nvidia Corporation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Re... | datasets/uniform.py | BSD-3-Clause | 11,992 | 3a3a472127633a3ecd661c5be0c1b29572871a19 | Python | py | |
import os
import torch
class BaseModel(object):
def name(self):
return 'BaseModel'
def get_image_paths(self):
pass
def initialize(self, opt):
self.opt = opt
self.gpu_ids = opt.gpu_ids
self.isTrain = opt.isTrain
self.Tensor = torch.cuda.FloatTensor if self.g... | cyclegan_arch/base_model.py | MIT | 1,648 | 12d6a6ba3a3a91167f4adab3b8e134bc47427838 | Python | py | |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) Megvii, Inc. and its affiliates.
import os
import torch
import torch.nn as nn
import torch.distributed as dist
from yolox.exp import Exp as MyExp
class Exp(MyExp):
def __init__(self):
super(Exp, self).__init__()
self.test_size = (256, ... | exps/default/yolox_m_ducha.py | Apache-2.0 | 5,767 | 3a3a96b130c21152ff2782a66531380b1f272790 | Python | py | |
from abc import ABCMeta, abstractmethod
import torch
from .sampling_result import SamplingResult
class BaseSampler(metaclass=ABCMeta):
def __init__(self,
num,
pos_fraction,
neg_pos_ub=-1,
add_gt_as_proposals=True,
**kwargs):
... | mmdetection/mmdet/core/bbox/samplers/base_sampler.py | MIT | 2,753 | 12df01306f31302390221b64c211926cca49ae96 | Python | py | |
"""BERT finetuning runner."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import json
import logging
import argparse
import math
from tqdm import tqdm, trange
import numpy as np
import torch
import random
import pickle
from transformers impor... | s2s-ft/decode_seq2seq.py | MIT | 13,128 | 7c116f14e4bdf52da8c644b21ddf87497b9b9b8d | Python | py | |
import torch
import sys
PIRL_WEIGHTS_PATH = sys.argv[1]
CONVERTED_WEIGHTS_OUT_PATH = sys.argv[2]
pirl_weights = torch.load(PIRL_WEIGHTS_PATH, map_location='cpu')
pirl_weights = {
k.replace("_feature_blocks.", "model."): v
for k, v in pirl_weights['classy_state_dict']['base_model']['model']['trunk'].items()
... | scripts/pirl_to_virb.py | Apache-2.0 | 405 | 3a3aef90b8ca006045882a849fc66a338190fa50 | Python | py | |
# -*- coding: utf-8 -*-
from math import ceil
from typing import Any, Tuple
import dipy.data
import numpy as np
import torch
from torch import Tensor
from torch.distributions import Categorical, MultivariateNormal
from torch.nn import (CosineSimilarity, Dropout, Linear, ModuleList, ReLU)
from torch.nn.modules.distance... | dwi_ml/models/direction_getter_models.py | MIT | 28,415 | 24ad722367fd521597505f469364459490c5d71d | Python | py | |
"""Pre-activation ResNet in PyTorch.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Identity Mappings in Deep Residual Networks. arXiv:1603.05027
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..registry import register_model
__all__ = ["PreActResNet18"]
class PreA... | lib/models/cnn/preact_resnet.py | MIT | 4,632 | a98e756b80eeb570b679d05adc6ebef9358b0433 | Python | py | |
"""
Filtering and dataset mapping methods based on training dynamics.
By default, this module reads training dynamics from a given trained model and
computes the metrics---confidence, variability, correctness,
as well as baseline metrics of forgetfulness and threshold closeness
for each instance in the training data.
I... | cartography/selection/train_dy_filtering.py | Apache-2.0 | 23,050 | e614515e60b838da367413595754c36759ee9f35 | Python | py | |
"""
MIT License
Copyright (c) 2021 martinpflaum
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, ... | data/list_transforms.py | MIT | 3,276 | 3a3b2ac3820255ea05d551fb1ff84e4621a1ffcd | Python | py | |
# Copyright (c) 2022, Kwanhyung Lee, AITRICS. All rights reserved.
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT ... | builder/utils/binary_performance_estimator.py | MIT | 2,350 | 45f96ddbfd24544f4f395c2fa6f87657c3bb1193 | Python | py | |
from __future__ import division, print_function, unicode_literals
import argparse
import json
import random
import time
from io import open
import numpy as np
import torch
from torch.optim import Adam
from utils import util
from model.model import Model
parser = argparse.ArgumentParser(description='S2S')
parser.ad... | train.py | MIT | 8,084 | 3a3b51cba1c3435c60576e1491ea22058ccb610e | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from .ext_layers import HFSampler, HNSWSampler, Ident
__all__ = ['Classifier', 'CosFaceClassifier', 'HFClassifier', 'HNSWClassifier']
class Classifier(nn.Module):
def __init__(self, base, feat... | models/classifier.py | MIT | 3,173 | 7075e2112fb178225eb04d0f628d55cb993947b7 | Python | py | |
# -*- coding: utf-8 -*-
import sys
import os
import argparse
import toml
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
from torch.cuda.amp import autocast
sys.path.append(os.getcwd())
from trainer.base_trainer import BaseTrainer
from dataset.dataset import DNS_Dataset
from module.dc_crn i... | trainer/knowledge_distillation_trainer.py | BSD-3-Clause | 5,980 | 70434d459fedee7cc3178ac7f957ca91bf61b462 | Python | py | |
import torch
from rl_safety_algorithms.algs.npg.npg import NaturalPolicyGradientAlgorithm
import rl_safety_algorithms.algs.utils as U
from rl_safety_algorithms.common import utils
import rl_safety_algorithms.common.mpi_tools as mpi_tools
class TRPOAlgorithm(NaturalPolicyGradientAlgorithm):
def __init__(
... | rl_safety_algorithms/algs/trpo/trpo.py | MIT | 3,099 | 3a3b7e14c47403921d19e183292557d40120d23a | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
class Matcher(object):
"""
This class assigns to each predicted "element" (e.g., a box) a ground-truth
element. Each predicted element will have exactly zero or one matches; each
ground-truth element may be assigned to... | maskrcnn_benchmark/modeling/matcher.py | MIT | 4,995 | 3a3b86af156f044d8f69523c0cdd1786728761e6 | Python | py | |
#!/usr/bin/env python3
# encoding: utf-8
# @Time : 2018/6/17 上午12:43
# @Author : yuchangqian
# @Contact : changqian_yu@163.com
# @File : seg_oprs.py
from collections import OrderedDict
import numpy as np
import torch
import torch.nn as nn
class ConvBnRelu(nn.Module):
def __init__(self, in_planes, out_plan... | furnace/seg_opr/seg_oprs.py | MIT | 6,512 | 3a3bae3aab068a0cf19bce34fef0429e0e277466 | Python | py | |
import torch
from torch.testing._internal.common_device_type import instantiate_device_type_tests, dtypes
from torch.testing._internal.common_utils import TestCase, run_tests
devices = (torch.device('cpu'), torch.device('cuda:0'))
class TestComplexTensor(TestCase):
@dtypes(*torch.testing.get_all_complex_dtypes())... | test/test_complex.py | Intel | 1,144 | 45482efbae56d80dead0f4fcef0ddaf7fe09b8f6 | Python | py | |
''' Translate input text with trained model. '''
import torch
import torch.utils.data
import argparse
from tqdm import tqdm
from tf.dataset import collate_fn, TranslationDataset
from tf.transformer.Translator import Translator
from tf.preprocess import read_instances_from_file, convert_instance_to_idx_seq
def main()... | self_attention/data/translate.py | MIT | 2,692 | 3a3bdeba0978b1dfe97d0e73d81d8f05617acaca | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import logging
import os
import copy
import torch
import numpy as np
from utils.vis import save_debug_images_multi
from utils.vis import save_debug_3d_images
from utils.vis import save_debug_3d_cu... | lib/core/function.py | MIT | 8,551 | 24c012aa58224334e4b9ebc9cfe2173c621a0212 | Python | py | |
# -*- coding: utf-8 -*-
from torch import nn
from utils.tensor_ops import cus_sample
class SIM(nn.Module):
def __init__(self, h_C, l_C):
super(SIM, self).__init__()
self.h2l_pool = nn.AvgPool2d((2, 2), stride=2)
self.l2h_up = cus_sample
self.h2l_0 = nn.Conv2d(h_C, l_C, 3, 1, 1)
... | paper_result/MINet/bicon/train/module/MyModule.py | MIT | 7,995 | cc2d2851de4ee29824bfaaeac653d597e64609c0 | Python | py | |
import os
import sys
from deepdrive_zero.experiments import utils
from spinup.utils.run_utils import ExperimentGrid
from spinup import ppo_pytorch
import torch
experiment_name = os.path.basename(__file__)[:-3]
notes = """
Try a smaller gamma to speed up learning of smaller grain interactions. Our
reward is mostly pe... | deepdrive_zero/experiments/intersection_2_agents_lower_gamma/intersection_2_agents_lower_gamma.py | MIT | 1,620 | 5fc92260aa8fc225bfad7c6b9f29bf268dbd42aa | Python | py | |
from __future__ import print_function, division, absolute_import
import torch
import torch.nn as nn
from torch.cuda.amp import autocast
import os
import sys
class BasicConv2d(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride, padding=0):
super(BasicConv2d, self).__init__()
... | InceptionResNetV2.py | MIT | 9,522 | 3a3bf21c143fdd68192a03e6b0952568f5fefa77 | Python | py | |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | tests/core/data/test_batch.py | Apache-2.0 | 2,575 | 102fb7196f0ec00b5bf10789ce75affbcb79d734 | Python | py | |
''' Incremental-Classifier Learning
Authors : Khurram Javed, Muhammad Talha Paracha
Maintainer : Khurram Javed
Lab : TUKL-SEECS R&D Lab
Email : 14besekjaved@seecs.edu.pk '''
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
class DownsampleStride(nn.Module)... | inclearn/convnet/my_resnet.py | MIT | 3,721 | 3a3c22b7737a192dfe1f9e9024ae59ca8fe3e8e0 | Python | py | |
"""
@file : focal_loss.py
@author : xiaolu
@email : luxiaonlp@163.com
@time : 2022-01-05
"""
import torch
from torch import nn
import torch.nn.functional as F
class BCEFocalLoss(nn.Module):
# 可用于二分类和多标签分类
def __init__(self, gamma=2, alpha=0.25, reduction='mean'):
super(BCEFocalLoss, self).__init_... | NEZHA_CLS/focal_loss.py | Apache-2.0 | 2,644 | 342e9e542a1dd7437ada07e740867af819d276cc | Python | py | |
# -*- coding: utf-8 -*-
# file: shufflenetv2.py
# brief: YOLOv3 implementation based on PyTorch
# author: Zeng Zhiwei
# date: 2019/9/12
import sys
import torch
import numpy as np
import torch.nn.functional as F
import jde
import iou
import focalloss
class ShuffleNetV2Block(torch.nn.Module):
def _... | shufflenetv2.py | MIT | 12,943 | 5f88cb285520b7397af4e6eea1133d1bb8b84c69 | Python | py | |
from collections import OrderedDict
import torch.distributed as dist
from torch._utils import (
_flatten_dense_tensors, _unflatten_dense_tensors, _take_tensors
)
from mmcv.runner import OptimizerHook
try:
from apex import amp
import apex
except ImportError:
raise ImportError('Use APEX for multi-precis... | dmb/utils/dist_utils.py | MIT | 3,042 | 249c42feb428e5d54f3d41b2a98e251a8499deb8 | 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... | PointCloud/chamfer_distance/chamfer_distance.py | MIT | 1,830 | e9d8f731d08522d5f26dc69e04f5a633d1ccaa84 | Python | py | |
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import numpy as np
import torch
from torch.nn.parameter import Parameter
from torch.autograd import Variable
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': 'https:/... | bpm/model/resnet_conv5_end.py | MIT | 14,634 | 12ce3fcb51d07bc911019e14304a222e30417a09 | Python | py | |
import numpy as np
import torch
import argparse
import json
import os
import json
LANGS='am,ar,bxr,cdo,cs,de,el,en,es,et,eu,fa,fi,fr,gn,hi,ht,hu,hy,id,ilo,is,ja,jv,ka,ko,kv,la,lv,mhr,mi,my,myv,pt,qu,ru,se,sw,tk,tr,vi,wo,xmf,zh,zh_yue'.split(',')
INFILE = 'outputs/{}/cloud-weights-100-bert-base-multilingual-cased-MaxLe... | scripts/display_scores.py | Apache-2.0 | 2,450 | 421e3cc9651cfeffa0c08bdf089bd45d0d2ba34e | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
from functools import partial
__all__ = [
'ResNet', 'resnet10'
]
def conv3x3x3(in_planes, out_planes, stride=1):
# 3x3x3 convolution with padding
return nn.Conv3d(
in_planes,
... | applications/Gesture/action_recognition/R3D/models/resnet.py | BSD-3-Clause | 7,410 | 3a3cad263d4eebcb185f8f5a38daed1eeec8f6a6 | Python | py | |
import os
import sys
import time
import glob
import numpy as np
import torch
import utils
import logging
import argparse
import torch.nn as nn
import genotypes
import torch.utils
import torchvision.datasets as dset
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from model import NetworkCIFAR ... | cnn/train.py | Apache-2.0 | 6,265 | 247743ed2e0a6bd613a86344d7874a12abfcb7dc | Python | py | |
import argparse
import os
import warnings
import numpy as np
import mmcv
import cv2
import torch
from scipy.optimize import linear_sum_assignment
from mmcv import Config, DictAction
from mmcv.cnn import fuse_conv_bn
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (get_dist_in... | tools/test.py | Apache-2.0 | 10,161 | f93df9e45fdc9e619a80f2caf0629a36bc805364 | Python | py | |
# Copyright (c) 2018-2019, NVIDIA CORPORATION
# Copyright (c) 2017- Facebook, Inc
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above ... | cli/jobs/pipelines-with-components/image_classification_with_densenet/image_cnn_train/image_classification/dataloaders.py | MIT | 15,289 | d7382db145cb80296ab09570a4238b6e19af9f85 | Python | py | |
import torch
import sys
OUTPUT_DIR=sys.argv[1]
mode=sys.argv[2]
if mode == 'train':
total_num = 144
elif mode == 'valid':
total_num = 7
elif mode == 'test':
total_num = 6
cnt = 0
for i in range(total_num):
a=torch.load(f'cnndm.{mode}.{i}.bert.pt')
out_pt=f'{OUTPUT_DIR}/cnndm.{mode}.{i}.bert.pt... | bert/highligted_sentence_data.py | MIT | 1,135 | 28a74481a60d83b03cc50378f9dd2de67875ea4f | 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 Ge... | windows_packages_gpu/torchvision/models/detection/generalized_rcnn.py | Apache-2.0 | 4,768 | 3a3ce7cd1e53cb8323defa16c592a1866991a32d | Python | py | |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Dongjie Yang, Zhe Li, Jiajie Wu
import numpy as np
import random
import math
import h5py
from torch.utils import data
from tqdm import tqdm
import torch
from torch.utils.data import TensorDataset, DataLoader
class Construct_raw_dataset(object):
def __init__(se... | data.py | MIT | 7,849 | 3a3cea03c64fd8488da5faa6344782ce380b8e64 | Python | py | |
"""Train a single model on NyuV2 dataset."""
from datetime import timedelta
import numpy as np
import torchvision.utils as vutils
from distributions.distribution_wrappers import ProbabilisticWrapper
from distributions.distribution_wrappers import GaussianEnsembleWrapper
from training.distribution_trainer import NLLSi... | training/nyu_trainers.py | MIT | 6,880 | 7c41e1e9ffecf40dc337e3c253f51264887ad682 | Python | py | |
import os
import random
import json
import imgaug
import torch
import numpy as np
seed = 1234
random.seed(seed)
imgaug.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
from tqdm import tqdm
import ... | script/gen_results.py | MIT | 3,571 | 3a3d20d5228d476a1b5deaa1ad1c648aa126d64a | Python | py | |
# Copyright (c) Open-MMLab. All rights reserved.
import os.path as osp
import time
import torch
from torch.optim import Optimizer
import mmcv
from .base_runner import BaseRunner
from .checkpoint import save_checkpoint
from .hooks import IterTimerHook
from .utils import get_host_info
class IterLoader:
def __ini... | mmcv/runner/iter_based_runner.py | Apache-2.0 | 8,609 | 3a3d22f2fc09fe90ecda16868f29afea4054e3d3 | Python | py | |
import torch
from torch.distributions import Categorical
import string
# Utility function
def expand(dist, indices):
for idx in dist.indices:
assert idx in indices
p = dist.p
dim_to_add = [indices.index(e) for e in indices if e not in dist.indices]
for dim in sorted(dim_to_add):
p = p.... | src/discrete/distribution/distribution.py | MIT | 11,298 | 3a3d6dae6d466d5fb3184a86e98cd81ae8157f22 | Python | py | |
import time
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import torch
from torch.optim.lr_scheduler import ReduceLROnPlateau, CyclicLR
from segmentation_models_pytorch.utils.losses import DiceLoss, JaccardLoss
from utils.meter import Meter
def imshow_img_pair(img, mask):
f, (ax1, ax2) ... | utils/trainer.py | MIT | 5,513 | 3a3d6faa65b31c058b83d6d2dc1ecc772aa43993 | Python | py | |
import argparse
import os
import sys
import time
from typing import Callable
import numpy as np
import pandas as pd
import torch
from torch.optim import Adagrad, Adadelta, Adam
from torch.utils.data import DataLoader
from common.data_iterator import Iterator, TestIterator
from config import CONFIG
from model.callback... | deepfm_train.py | MIT | 7,799 | 12c08e067d769f8905b9e8c2aa4120645ee68492 | Python | py | |
import numpy as np
import csv
import torch.nn.parallel
import torch.optim
import torch.utils.data
import pickle
from tqdm import tqdm
import torch.nn as nn
from model import *
from noise_data_cifar_100 import *
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import in... | CIFAR-100/runner_CE.py | MIT | 4,239 | 3a3d99c43bd329d76ed2368feaff2c8232ab7212 | Python | py | |
import os
import torch
import torch.nn as nn
from .tsm.ops.models import TSN
from collections import OrderedDict
class BackboneTSM(TSN):
def __init__(self, lfd_params, is_training=False, filename=None,
trim_model=False, output_size=2048, end_point=None):
super().__init__(output_size, lf... | model/backbone_model/backbone_tsm.py | MIT | 3,487 | 3a3da3ab9f2c4c1969b4ad047f6a64fff530870e | Python | py | |
from torch import nn
from torchvision.models import resnet50
from torchvision.ops.misc import FrozenBatchNorm2d
from .utils import pooling
class RCNN(nn.Module):
"""
An R-CNN inspired parking lot classifier.
Pools ROIs directly from image and separately
passes each pooled ROI through a CNN.
"""
... | models/rcnn.py | MIT | 1,266 | 3a3db38d54b1b3a1d9f5e2a6e5b74b84f583c35d | Python | py | |
# Copyright 2020 - 2021 MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in wri... | tests/test_affine_transform.py | Apache-2.0 | 18,136 | 42af58be737a749344b8606552e00fc03030a9c5 | Python | py | |
""""""
from GAN_utils import loadStyleGAN2, loadBigGAN
from GAN_utils import StyleGAN2_wrapper, BigGAN_wrapper
import torch
import numpy as np
import matplotlib.pylab as plt
import os
from os.path import join
from torchvision.utils import make_grid
from torchvision.transforms import ToPILImage
#%%
rootdir = r"E:\OneDr... | GAN_compression_cmp.py | Apache-2.0 | 3,478 | 52a1fd6fa2c4e9dfcd2460b46d560b9e5094f385 | Python | py | |
import importlib
import torch.utils.data
from data.base_dataset import BaseDataset
from data.regular_dataset import RegularDataset
def create_dataset(opt, augment, istrain, uniform_val):
data_loader = CustomDatasetDataLoader(opt, augment, istrain, uniform_val)
dataset = data_loader.load_data()
return data... | data/__init__.py | MIT | 1,386 | 3a3dcebe030f1e2db4515c1e33a7c56cd81b002b | Python | py | |
import waitGPU
# import setGPU
# waitGPU.wait(utilization=20, available_memory=10000, interval=60)
# waitGPU.wait(gpu_ids=[1,3], utilization=20, available_memory=10000, interval=60)
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
import... | examples/cifar_test3.py | MIT | 7,104 | 3a3dd69c20ae768cab315523fbb8a520511e59a4 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd as autograd
import math
from torch.nn.modules import loss
def class_select(logits, target):
batch_size, num_classes = logits.size()
if target.is_cuda:
device = target.data.get_device()
one_hot_mask = autog... | loss.py | MIT | 12,525 | 3a3deb4ea6cccf3ff5953da192b41de903f794c6 | Python | py | |
import numpy as np
import pandas as pd
import torch
import torch.utils.data
from torch.utils.data import Dataset, TensorDataset
import torchvision
import torchvision.models
import torchvision.transforms
import cv2
import os
import glob
class ImageDataset(Dataset):
def __init__(self, image_dir, data_dir, train,... | dataloader.py | MIT | 4,323 | 6b30024c0b6d06429e0c4ebd0db1b61bf656e275 | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
API for exporting a pytorch model to a predictor, the predictor contains model(s) in
deployable format and predefined functions as glue code. The exported predictor should
generate same output as the original pytorch mod... | d2go/export/api.py | Apache-2.0 | 14,333 | 3a3dfcf7696a7ab2cb2353fd01198d2ae54a758a | Python | py | |
import torch
torch.set_default_tensor_type(torch.DoubleTensor)
#seed = 5
#torch.manual_seed(seed)
def prod_normal(mu1,s1,mu2,s2,rho):
'''Stats of the product of two normal distributions'''
v1 = s1*s1
v2 = s2*s2
cov = s1*s2*rho
det = v1 + v2 - 2*cov #determinant of the covariance matrix
... | apps/regression/data.py | MIT | 5,768 | 7ca73d63854a81ab069f439393fc28f45cc83cf9 | Python | py | |
from transformers import Trainer
from typing import Any, Callable, Dict, List, Optional, Tuple, Union, NamedTuple
from enum import Enum
import random
import json
import math
import os
import re
import shutil
import warnings
from contextlib import contextmanager
from pathlib import Path
import numpy as np
import torch
f... | ariadne/contrib/OptimTrainer.py | Apache-2.0 | 18,460 | 3a3e4223c6fca4376aa57bf22f8a66c7e020123c | Python | py | |
import random
import torch
import numpy as np
import logging
LOGGER = logging.getLogger(name="infotropy.utils.random")
def set_seed(seed):
"""Set the random number generation seed globally for `torch`, `numpy` and `random`"""
np.random.seed(seed)
torch.manual_seed(seed)
random.seed(seed)
LOGGE... | vseq/utils/rand.py | MIT | 510 | 804459cf2148a6072323c81ea0944d8d5f1e6116 | Python | py | |
"""
ResNet for CIFAR dataset proposed in He+15, p 7. and
https://github.com/facebook/fb.resnet.torch/blob/master/models/resnet.lua
From https://github.com/moskomule/senet.pytorch
"""
import torch.nn as nn
def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes... | models/resnet.py | MIT | 3,260 | 3a3e5a3561061a5221f50f40d294561d24f9cdd1 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import weight_reduce_loss
def cross_entropy(pred,
label,
weight=None,
class_weight=None,
reduction='mean',
avg_factor=N... | mmseg/models/losses/cross_entropy_loss.py | Apache-2.0 | 7,917 | 7caaecccc43bfa9611c057637f3edc036c6e208a | Python | py | |
import torch
import torch.nn.functional as F
import torch.optim as optim
from envs import create_atari_env, create_doom_env, create_picolmaze_env
from model import ActorCritic, IntrinsicCuriosityModule
from itertools import chain # ICM
import os
import signal
class Killer:
kill_now = False
def __init__(s... | train_curiosity.py | MIT | 4,624 | 10973884956bcede1a6429013038dada20788054 | Python | py | |
"""LightningFlower Strategy"""
from flwr.server.strategy import FedAvg
import numpy as np
import os
import pytorch_lightning.utilities.argparse as arg_parser
from argparse import ArgumentParser, Namespace
from lightningflower.utility import printf, load_params, boolean_string, create_dir
from lightningflower.config imp... | lightningflower/strategy.py | MIT | 5,364 | 4b8d90f67269f4f9b28f81240eeb7525c2221996 | 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 Union
import torch
import torch.nn.functional as F
from pytorch3d.ops.knn import knn_gather... | pytorch3d/loss/chamfer.py | BSD-3-Clause | 8,236 | 3a3eab3c5ae4d26849bfb7522744953a78a8162d | Python | py | |
import PixelUnshuffle
import torch
import torch.nn as nn
import torch.nn.functional as F
x = torch.range(start=0, end=31).reshape([1, 8, 2, 2])
print('x:')
print(x.shape)
print(x)
y = F.pixel_shuffle(x, 2)
print('y:')
print(y.shape)
print(y)
x_ = PixelUnshuffle.pixel_unshuffle(y, 2)
print('x_:')
print(x_.shape)
print(x... | example.py | MIT | 322 | 3a3eb0611c7a7942c52246d26b7ce014cf9c8f60 | Python | py | |
import torch
from torch import nn
from torch.distributions import Normal as NormalDistribution
import omnifig as fig
# import torch
# import torch.nn as nn
# from .. import framework as fm
# from ..op import framework as fm
# from omnibelt import InitWall, unspecified_argument
# import omnifig as fig
# from .layer... | omnilearn/models/features.py | MIT | 3,668 | 3a3ec3cafb4f44cb8f53559f5aea37cd21f616ae | Python | py | |
import dataclasses
from typing import Tuple, Optional, List, Any, Sequence
import numpy as np
import torch
from falkon.options import BaseOptions
from falkon.utils import devices, PropagatingThread
from falkon.utils.devices import DeviceInfo
from falkon.utils.fake_queue import FakeQueue
from falkon.utils.tensor_helpe... | falkon/mmv_ops/utils.py | MIT | 4,860 | 3a3edec2e2d1baf442790d102f2f0e74f42e0694 | Python | py | |
"""
https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class deepQ(nn.Module):
def __init__(self, action_size, obs_size, hidden_size=256):
super().__init__()
self.input_layer = nn.Linear(obs_size, hidden_size)
self.output_... | Exiles/models/deepQ.py | MIT | 482 | 7c6ecf19948c56d70a8bc03fbb8a39d9de1cf95a | Python | py | |
import numpy as np
import random
import copy
from collections import namedtuple, deque
from model import Actor as Actor_Network
from model import Critic as Critic_Network
import torch
import torch.nn.functional as F
import torch.optim as optim
#SEED = 4
BUFFER_SIZE = int(1e5) # Number of episodes to keep in memory (... | p2_continuous-control/ddpg_agent.py | MIT | 9,341 | 5eaa29c9dc2d8e9675c0c45ef3859401a8e43a69 | Python | py | |
from libcity.data import get_dataset
from libcity.utils import get_executor
from libcity.utils import get_model
from libcity.utils import get_logger
config = {
'log_level': 'INFO',
'dataset': 'METR_LA',
'model': 'AGCRN',
'evaluator': 'TrafficStateEvaluator',
'executor': 'TrafficStateExecutor',
... | test/test_agcrn.py | Apache-2.0 | 2,590 | 3a3f3b8bd40c2cb64c405c907dc8e09961d3f288 | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import unittest
import torch
from pytext.contrib.pytext_lib.datasets import BaseDataset, PoolingBatcher
from pytext.contrib.pytext_lib.transforms import (
VocabTransform,
WhitespaceTokenizerTransform,
)
from pytext.da... | pytext/contrib/pytext_lib/tests/base_dataset_test.py | BSD-3-Clause | 3,254 | 3a3f3d16cddfaacd00627204d71ed27319d06b2d | Python | py | |
'''
Code borrowed from https://github.com/lukasruff/Deep-SVDD-PyTorch
'''
from PIL import Image
import numpy as np
from random import sample
from abc import ABC, abstractmethod
import torch
from torch.utils.data import Subset
from torchvision.datasets import MNIST
import torchvision.transforms as transforms
from torc... | examples/pytorch/DROCC/data_process_scripts/process_mnist.py | MIT | 5,309 | f9c553fba3555e8103742b6d9c57aa124522701f | Python | py | |
from tqdm import tqdm
import torch
import torch.nn.functional as F
import cv2
import numpy as np
def resize_target(target, s):
new_target = np.zeros((target.shape[0], s[0], s[1]), np.int32)
for i, t in enumerate(target.cpu().numpy()):
new_target[i, ...] = cv2.resize(t, (s[1],s[0]), interpolation=cv2.INT... | zs3/base_trainer.py | Apache-2.0 | 2,856 | 3a3f4cba3bf38e57194bc134dbdf8829b59c10e9 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import xavier_init
from mmdet.core import AnchorGenerator, anchor_target, multi_apply
from ..losses import smooth_l1_loss
from ..registry import HEADS
from .anchor_head import AnchorHead
# TODO: add loss evaluator for... | mmdet/models/anchor_heads/ssd_head.py | Apache-2.0 | 8,268 | e99a8ac6c4aed4f23c19a126251849347798ca58 | Python | py | |
from typing import Tuple, Optional, List, overload, Union, TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
import torch
from labml.internal.analytics import cache as _cache
from labml.internal.analytics.altair import density as _density
from labml.internal.analytics.altair import histogram as _histogram
from ... | client/labml/analytics/__init__.py | MIT | 18,032 | 12f0ed92ceb12a663a8b42aac08173ecddc0f47f | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Train a video classification model."""
import numpy as np
import pprint
import torch
from fvcore.nn.precise_bn import get_bn_modules, update_bn_stats
import slowfast.models.losses as losses
import slowfast.models.optimi... | tools/train_net.py | Apache-2.0 | 11,127 | 3a3f8a79cddf39f05d180af7bb319ba38d63dca0 | Python | py | |
import os
import sys
# Flask
from flask import Flask, redirect, url_for, request, render_template, Response, jsonify, redirect
from werkzeug.utils import secure_filename
from gevent.pywsgi import WSGIServer
# PyTorch
import torch
import torchvision
from torch.autograd import Variable
from torchvision import transform... | demo/app.py | Apache-2.0 | 2,377 | 3a3f94d20906d79c5fb3b70c8f47caf7e128078f | Python | py | |
import numpy as np
import torch.nn.functional as F
import logging
import time
import torch
import os
import shutil
import tensorboardX
import torch.optim as optim
from torchvision.utils import make_grid, save_image
from torchvision.datasets import MNIST, CIFAR10, ImageFolder
import torchvision.transforms as transforms
... | SSM/runners/vae_runner.py | MIT | 40,943 | 45914a631360e449dff8af9a06e02e3542ef0ac0 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.