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) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
"""
Interpreting hyperbole with RSA models of pragmatics.
Taken from: https://gscontras.github.io/probLang/chapters/03-nonliteral.html
"""
import torch
import collections
import argparse
import pyro
import pyro.distributions as... | examples/rsa/hyperbole.py | Apache-2.0 | 5,669 | 29ace836e735fca4b4464ea15224e0afc2c81edc | Python | py | |
import time
import torch
from helpers import list_of_distances, make_one_hot
def _train_or_test(model, dataloader, optimizer=None, class_specific=True, use_l1_mask=True,
coefs=None, log=print, sw=None, epoch=0):
'''
model: the multi-gpu model
dataloader:
optimizer: if None, will be ... | train_and_test.py | MIT | 9,046 | 29ad10dfa881190061575232acc1d207a05e06ff | Python | py | |
from setuptools import setup
from torch.utils.cpp_extension import CppExtension, BuildExtension, CUDAExtension
setup(name='tcmm_cpp',
ext_modules=[CUDAExtension(
name='tcmm',
sources=['tcmm.cpp', 'tcmm_kernel.cu'],
libraries=['cusolver'],
... | packages/tcmm/bk/setup.py | MIT | 635 | 4207e9aeb831b0aec09c2a9ca24af9190fee6e51 | Python | py | |
# code for building PlaqueGAN generator and discriminator.
# Adapted from code of official FastGAN implementation:
# https://github.com/odegeasslbc/FastGAN-pytorch
# with additional adaptations from:
# https://github.com/lucidrains/lightweight-gan
import torch
import torch.nn as nn
from torch.nn.utils import s... | PlaqueGAN/models.py | MIT | 25,473 | 4bab394aa1ac4da5237da136f8a0397dac8ad4ad | Python | py | |
"""
Code references:
https://github.com/HRNet/HRNet-Image-Classification/blob/master/lib/models/cls_hrnet.py
https://github.com/HRNet/HRNet-Object-Detection/blob/master/configs/hrnet/faster_rcnn_hrnetv2p_w32_syncbn_mstrain_1x.py
https://github.com/lyrgwlr/HRNet-Facial-Landmark-Detection-v1/blob/master/lib/m... | fastreid/modeling/backbones/hrnet.py | Apache-2.0 | 28,366 | 29ad2fa2c90f09b843479fb9b8d9a689e493bc49 | Python | py | |
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence as pack
from torch.nn.utils.rnn import pad_packed_sequence as unpack
from deepbond import constants
from deepbond.initialization import init_xavier
from deepbond.models.model import Model
from deepbond.modules.attention import Atten... | deepbond/models/rnn_attn.py | MIT | 6,255 | 28fa7aa030f6ede465c0ff112af1c75a2155efc4 | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
from utils import CONFIG
from networks.encoders.resnet_enc import ResNet_D
from networks.ops import GuidedCxtAtten, SpectralNorm
class ResGuidedCxtAtten(ResNet_D):
def __init__(self, block, layers, norm_layer=None, late_downsample=False):
... | networks/encoders/res_gca_enc.py | MIT | 3,948 | 1e2bc5b5a6abc54afad69c29d579a919a2990ddb | Python | py | |
import os
import torch
import torchvision
from torchvision.datasets import CocoDetection
from PIL import Image
import numpy as np
from tqdm import tqdm
VERBOSE = False
class MSCOCODataset(CocoDetection):
"""
root (string): Root directory where images are downloaded to.
annFile (string): Path to ... | ReferentialGym/datasets/MSCOCO_dataset.py | MIT | 4,159 | 29ad43a4d3f432ab8e54f62c6319da2645c89a5a | Python | py | |
import torch
from apex.multi_tensor_apply import multi_tensor_applier
class FusedNovoGrad(torch.optim.Optimizer):
"""Implements NovoGrad algorithm.
Currently GPU-only. Requires Apex to be installed via
``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./``.
Th... | pytorch/sagemakercv/training/optimizers/fused_novograd.py | Apache-2.0,BSD-2-Clause-FreeBSD | 10,190 | 5e76d2dd601a613b2008ef2198ccc14843dd1712 | Python | py | |
import collections
import copy
import csv
import datetime
import math
import os
import pickle
import platform
import pprint
import queue
import time
from abc import ABCMeta, abstractmethod
from functools import partial
from itertools import zip_longest
import gym
import IPython
import numpy as np
import pandas as pd
i... | es/algorithms.py | MIT | 113,975 | b250d0c8449d385b7a75b0d94b92eb1942f4b0fd | Python | py | |
import pytest
from easydict import EasyDict
import torch
from ding.model.template import PDQN
@pytest.mark.unittest
class TestPQQN:
def test_dqn(self):
T, B = 3, 4
obs_shape = (4, )
act_shape = EasyDict({'action_type_shape': (3, ), 'action_args_shape': (5, )})
if isinstance(obs_sh... | ding/model/template/tests/test_pdqn.py | Apache-2.0 | 2,415 | 10dfa25737dbec6f8ccd7f6a0fa7c3195e4b9611 | Python | py | |
import numpy as np
import torch
from torchvision.utils import make_grid
from base import BaseTrainer
from utils import inf_loop, MetricTracker
from trader import Trader
from sklearn.metrics import roc_auc_score
import os
class Trainer(BaseTrainer):
"""
Trainer class
"""
def __init__(self, model, criter... | trainer/trainer.py | MIT | 8,391 | 7ccdd855d2bdff791bd1ad767710ba280e42514c | Python | py | |
"""General-purpose test script for image-to-image translation.
Once you have trained your model with train.py, you can use this script to test the model.
It will load a saved model from '--checkpoints_dir' and save the results to '--results_dir'.
It first creates model and dataset given the option. It will hard-code ... | BoostingMonocularDepth-main/pix2pix/test.py | MIT | 5,040 | f9e0b1edc636ac3a5d2dc32a7622156131ee5e1d | Python | py | |
import torch
from torch import nn
class AttentionModel(nn.Module):
def __init__(self, embeddings, in_dim, num_layers = 1, hidden_size = 100, out_dim = 1, use_word_dropout = False):
super(AttentionModel, self).__init__()
self.num_layers = num_layers
self.hidden_size = hidden_size
sel... | src/models/attention_rnn.py | MIT | 3,499 | 29adabdf5c1bb95e4c74070f520a9c96e79ac4f2 | Python | py | |
#!/usr/bin/env python
"""
Example runs the differentiable GPMP2 planner as a torch network
allowing gradients to be backpropagated.
"""
import os, sys
sys.path.insert(0, "..")
import matplotlib.pyplot as plt
plt.rcParams['axes.facecolor'] = 'white'
import numpy as np
import pprint
import time
import torch
from diff_gpm... | examples/diff_gpmp2_2d_example.py | BSD-3-Clause | 4,383 | a957476f51f7de662868d316ca0d28d2eda5fa58 | Python | py | |
# -*- coding: utf-8 -*-
##########################################################################
# NSAp - Copyright (C) CEA, 2021
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
#... | surfify/tests/test_models_unet.py | CECILL-B | 3,814 | 5e7022841b7a082ac6383f1445f2320f3f179f86 | Python | py | |
"""ABY3 Protocol.
ABY3 : A Mixed Protocol Framework for Machine Learning.
https://eprint.iacr.org/2018/403.pdf
"""
# stdlib
import itertools
from typing import Any
from typing import List
from typing import Tuple
# third party
import torch
import torchcsprng as csprng
from sympc.config import Config
from sympc.proto... | src/sympc/protocol/aby3/aby3.py | MIT | 15,717 | 4b19c2ea75b6980aab0582d0f4c48c4edf609a09 | Python | py | |
#!/usr/bin/env python
# ros
import rospy
from geometry_msgs.msg import PoseStamped, Twist, Vector3
from nav_msgs.msg import Odometry
from sensor_msgs.msg import LaserScan
# viz
from visualization_msgs.msg import Marker, MarkerArray
from std_msgs.msg import ColorRGBA
# arena
import fc
import math
from torch.nn.utils.rn... | navigation/arena_local_planner/learning_based/arena_ros/scripts/arena_node_tb3.py | MIT | 9,040 | 7041af04d5c6f89e469529129ba6b31d567170ba | Python | py | |
from __future__ import print_function
import os
current_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(current_dir)
import torch
from torch.autograd import Variable
import cv2
import time
from imutils.video import FPS, WebcamVideoStream
import argparse
import numpy as np
import serial
def cv2_demo(net, t... | Detection_and_control/ASUM-GUI-with-detection-and-control/final_live_slicollect_detect_with_control.py | MIT | 10,880 | 29ae1a41bd73cf4f34d67badf20691b8a51d8d3d | Python | py | |
import torch.nn as nn
class ResidualBlock(nn.Module):
"""
Residual Block module containing:
- Convolution layer
- PReLU
- Convolution Layer
- Addition/ Residual connection
"""
def __init__(self, in_channels, hidden_channels, kernel_size, padding):
"""
I... | SRCNN.py | MIT | 3,709 | 29f93adebc96c87907c2e49eefc0230ab8842fd0 | Python | py | |
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Train a YOLOv5 model on a custom dataset
Usage:
$ python path/to/train.py --data coco128.yaml --weights yolov5s.pt --img 640
"""
import argparse
import logging
import math
import os
import random
import sys
import time
from copy import deepcopy
from pathlib import P... | warthog/server_reconhecimento/yolov5/train.py | BSD-3-Clause-Clear | 32,031 | 29ae43e3bd37940f25e87a8e68e4948b378f4474 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
class EdgeRes(nn.Module):
"""
input:
- inp: b x (num_dims+id) x num_points
outputs:
- out: b x num_dims x num_points
"""
def __init__(self, use_SElayer: bool = False):
super(EdgeRes, self).__init__()
self.k ... | models/edge_res.py | MIT | 6,914 | 29ae45f7aba0855e9f76fe53ccd79476528c3675 | Python | py | |
import config
import transformers
import torch.nn as nn
class BertBaseForQAWithoutSentiment(nn.Module):
def __init__(self):
super(BertBaseForQAWithoutSentiment, self).__init__()
self.bert = transformers.BertModel.from_pretrained(config.BERT_BASE)
self.linear4span = nn.Linear(768, 2)
de... | src/models.py | Apache-2.0 | 1,977 | 342f11d7b44f394939416bf83c63768aafba83fc | Python | py | |
#!/bin/env python
# -*- coding: utf-8 -*-
#
# Created on 29.07.21
#
# Created for ensemble_transformer
#
# @author: Tobias Sebastian Finn, tobias.sebastian.finn@uni-hamburg.de
#
# Copyright (C) {2021} {Tobias Sebastian Finn}
# System modules
import logging
import abc
# External modules
import torch
import torch... | ens_transformer/layers/attention/weight_estimators.py | MIT | 2,975 | 29ae5caf4aece33cc53f466eb0d073ac230cd120 | Python | py | |
import argparse
import json
import logging
import os
import glob
import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
from tqdm import tqdm, trange
from attrdict import AttrDict
from transformers import (
BertConfig,
BertTokenizer,
AdamW,
get_linear... | run_goemotions.py | Apache-2.0 | 12,463 | 1edb358a46556272d073b1b07d08e1b99924cba1 | Python | py | |
import PIL.Image
import torch
from torch.utils.data import DataLoader
from torchvision import transforms
from datasets import StereoDataset, StereoPlusDataset, StereoDataset_new, StereoDataset_HoloPix50k
import time
import torchvision
from losses import *
from model_new import *
#from model import *
from model_small im... | train_2StepsNet.py | MIT | 11,776 | d7c54aafd627aa08bcc44295c5068709d304b9c1 | Python | py | |
#!/usr/bin/env python3
"""
part1.py
UNSW COMP9444 Neural Networks and Deep Learning
ONLY COMPLETE METHODS AND CLASSES MARKED "TODO".
DO NOT MODIFY IMPORTS. DO NOT ADD EXTRA FUNCTIONS.
DO NOT MODIFY EXISTING FUNCTION SIGNATURES.
DO NOT IMPORT ADDITIONAL LIBRARIES.
DOING SO MAY CAUSE YOUR CODE TO FAIL AUTOMATED TESTIN... | part1.py | MIT | 2,728 | fdafd9247732ccaca09084e84eae69ccd8567c17 | Python | py | |
from omegaconf import DictConfig
import torch.nn as nn
import torch.nn.functional as F
from functools import partial
class ResBlock(nn.Module):
def __init__(self, channel_size: int, negative_slope: float = 0.2):
super().__init__()
self.block = nn.Sequential(
nn.Conv2d(channel_size, ch... | src/models/resizer.py | Apache-2.0 | 2,415 | 803f4c2585618690e52c44f7c8303113085f6c44 | Python | py | |
import os
import sys
import pandas as pd
import numpy as np
import pdb
import torch
import torch.nn as nn
import torch.nn.functional as F
sys.path.insert(1,"../")
sys.path.insert(1,"../../")
sys.path.insert(1,"../../../")
sys.path.insert(1,"../../../../")
sys.path.insert(1,"../../../../../")
sys.path.ins... | train_with_your_data/scripts/cpmg/pathologic_classification/control_tumor/metabolites/predicted/most_important_metabolites/30/config.py | MIT | 5,864 | e65b34de5fd009fa6a58cac52f1257f330fa8c95 | Python | py | |
'''
Copyright 2019 The Microsoft DeepSpeed Team
'''
import os
import re
import stat
import math
import torch
import warnings
import hashlib
import torch.distributed as dist
from collections import defaultdict, OrderedDict
from shutil import copyfile
from torch.nn.modules import Module
from torch.distributed.distribute... | deepspeed/runtime/engine.py | MIT | 108,988 | b2278c579fc9a6a1f912b2ce6f241fe7a7798e63 | Python | py | |
"""utils.py - Helper functions for building the model and for loading model parameters.
These helper functions are built to mirror those in the official TensorFlow implementation.
"""
# Author: lukemelas (github username)
# Github repo: https://github.com/lukemelas/EfficientNet-PyTorch
# With adjustments and added ... | efficientnet_pytorch/utils.py | Apache-2.0 | 24,930 | 29af0ed11a2338b328be8ac48a96c51cc682c499 | Python | py | |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) Megvii, Inc. and its affiliates.
# nano-juliet
# lower resolution and shallower neural network than default nano
# so as to run it faster on Jetson Nano
# based on pretrained nano-india
import os
import torch.nn as nn
from yolox.exp import Exp as MyExp
... | computer_vision/yolox_exps/nano_juliet.py | Apache-2.0,Unlicense | 1,659 | 29af17b2098f136b873ef1b577d63e3bddc8b8a6 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import collections
import gc
import os
from bisect import bisect
import requests
import torch
import tqdm
import yaml
import tarfile
import zipfile
import pdb
from torch import nn
from pythia.common.constants import DOWNLOAD_CHUNK_SIZE
def lr_lambda_update(i_iter, c... | pythia/utils/general.py | BSD-3-Clause | 6,944 | 29af1916a8d55e0b6367ceebc71a54ac3f37b954 | Python | py | |
import random, os
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from tqdm import tqdm
from torch.autograd import Variable
from pytorch_pretrained_bert.tokenization import whitespace_tokenize, BasicTokenizer, BertTokenizer
from pytorch_p... | ranking_nlp4if/kgat/train.py | Apache-2.0 | 8,667 | 1e5c0f676358f204648b4899482258d55dd48e25 | Python | py | |
import os
import torch
import torch.distributed as dist
from stft_core.utils import gpu_indices, ompi_size, ompi_rank, get_master_ip
def init_dist(launcher, args, backend='nccl'):
if launcher == 'pytorch':
_init_dist_pytorch(backend, args)
elif launcher == 'mpi':
_init_dist_mpi(backend, args... | stft_core/utils/dist_env.py | BSD-2-Clause | 1,230 | 29af3637618d1300e829ea66f5c3cd163efcd8f5 | Python | py | |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 19 06:21:32 2020
@author: Marcin
The file generates an CartPole experiments and loads pretrained RNN network. It feeds
"""
import torch
import torch.utils.data.dataloader
import collections
from utilis import get_device, plot_results, create_rnn_instance
# Parameters ... | modeling/RNN0/Test.py | MIT | 1,714 | b23d2980b43579d5547a2eaca333e5d19e81ddd5 | Python | py | |
# Copyright (c) 2019-2021 NVIDIA CORPORATION. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | Dell/benchmarks/bert/implementations/pytorch/bind_pyt.py | Apache-2.0 | 6,447 | 5f5bd7a7a84195c182d90a74b326e159c37455c8 | Python | py | |
# -*- coding: utf-8 -*-
"""Implementation of the HolE model."""
from typing import Any, ClassVar, Mapping, Optional
import torch
from ..base import EntityRelationEmbeddingModel
from ...constants import DEFAULT_EMBEDDING_HPO_EMBEDDING_DIM_RANGE
from ...moves import irfft, rfft
from ...nn.emb import EmbeddingSpecific... | src/pykeen/models/unimodal/hole.py | MIT | 6,212 | 29af5334d0df869a1b89a9fa3918f020ff438834 | Python | py | |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import os
import itertools
import soundfile as sf
import argparse
from tqdm import tqdm
from configs import config, get_all_params_dict
from model import get_model
from tokenizer import Wav2Vec2Tok
from datasets import load_... | src/train2.py | Apache-2.0 | 10,306 | e95f5a4c22c54c6af3bcf8a475eaba2609426b6d | Python | py | |
import sys
import json
import torch
import numpy as np
import argparse
import torchvision.transforms as transforms
import cv2
from DRL.ddpg import decode
from utils.util import *
from PIL import Image
from torchvision import transforms, utils
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
aug = ... | torchbenchmark/models/LearningToPaint/baseline_modelfree/env.py | BSD-3-Clause | 3,390 | 5e45b7d93a2b28fe16c0746746c035082ac0b6e9 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torch.nn.functional as F
from torch import nn
from maskrcnn_benchmark.layers import ROIAlign
from .utils import cat
class LevelMapper(object):
"""Determine which FPN level each RoI in a set of RoIs should map to based
... | maskrcnn_benchmark/modeling/poolers.py | MIT | 4,581 | a91f689a49ee8fce5b21750b6a37bb234aaa155b | Python | py | |
import sys
import argparse
import os
import numpy as np
import fnmatch
import criteria
import string
import pickle
import random
from InferSent.models import NLINet
from esim.model import ESIM
from esim.data import Preprocessor
from esim.utils import correct_predictions
import tensorflow as tf
import tensorflow_hub a... | attack_nli.py | MIT | 51,679 | 29af888ecab235d6a025131538f3688336523b7f | Python | py | |
import torch.optim as optim
from torch.nn.utils import clip_grad_norm
class MultipleOptimizer(object):
def __init__(self, op):
self.optimizers = op
def zero_grad(self):
for op in self.optimizers:
op.zero_grad()
def step(self):
for op in self.optimizers:
op... | onmt/Optim.py | MIT | 5,574 | d758a78998af5e78cdf4d68a48983f987eeea684 | 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... | src/transformers/data/processors/utils.py | Apache-2.0 | 13,867 | 4550e5756bbd302f5ec2f64962ca854cea6c5c37 | Python | py | |
import numpy as np
import torch
class KlueDpInputExample:
"""
A single training/test example for Dependency Parsing in .conllu format
Args:
guid : Unique id for the example
text : string. the original form of sentence
token_id : token id
token : 어절
pos : POS tag(s)... | inference/klue-dp/utils.py | Apache-2.0 | 7,537 | 29afb1652042f9366ff03fc7d7d6006d70d7b793 | Python | py | |
"""
An example for loss class definition, that will be used in the agent
"""
import torch.nn as nn
from torch.nn import functional as F
class BCE_KLDLoss(nn.Module):
def __init__(self, weight=None, size_average=True):
super(BCE_KLDLoss, self).__init__()
self.loss = nn.backends()
# def forward... | graphs/losses/bce_kld.py | MIT | 909 | 42445e57c372f1cb9c94eb6a98288f259f8c79e0 | Python | py | |
import mmcv
import numpy as np
import os
import sys
import time
import torch
from torch import nn
import torch.nn.functional as F
from scipy.spatial.distance import cdist
from libs.models.backbone import build_backbone
from libs.models.matcher import build_matcher
from libs.models.transformer import build_transforme... | libs/models/asnet.py | MIT | 33,193 | 29afd3b52fff70ffea290f6681775e442eec4c46 | Python | py | |
"""
Override timm.models.vision_transformer.VisionTransformer to
output all output tokens (excluding class or distill tokens)
This works for the vision_transformer_hybrid models as well
"""
import torch
import timm.models.vision_transformer
class VisionTransformer(timm.models.vision_transformer.VisionTransformer):
... | segmenter/vision_transformer.py | MIT | 1,682 | 709a00102e077bba65ac0f0bb20eed60de7b9e0a | Python | py | |
import copy
import logging
import numpy as np
import torch
from sklearn.cluster import KMeans
from torch import nn
from torch.nn import functional as F
from .. import utils, distance as distance_lib
from .postprocessors import FactorScalar, HeatedUpScalar
from inclearn.utils import LOGGER as logger
class Classifi... | CIFAR100/inclearn/lib/network/classifiers.py | MIT | 23,770 | a9045dccae84e3f964156e36018ee27df9f17acc | Python | py | |
import torch
from torch.utils.data import Dataset, DataLoader
from torchsupport.modules.structured.nodegraph import PartitionedNodeGraphTensor as PNGT
import torchsupport.modules.structured.nodegraph as ng
class LazyGraph(object):
def __init__(self, adjacency_source, feature_source):
self.adjacency_source = adja... | torchsupport/data/graph.py | MIT | 3,490 | 29aff896127f850d605d1f676e87493985d4891b | Python | py | |
# Copyright (c) Chris Choy (chrischoy@ai.stanford.edu).
#
# 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, ... | examples/reconstruction.py | MIT | 20,860 | 4264f6e94bdef088c17cad1da9b1d2fb038dff09 | Python | py | |
'''
Author: jianzhnie
Date: 2021-12-23 16:42:56
LastEditTime: 2021-12-23 16:42:56
LastEditors: jianzhnie
Description:
'''
import torch
import torch.nn as nn
from torch.autograd import Variable
from .gru import GRUBase
from .lstm import LSTMBase
from .rnn import RNNBase
class BidirRecurrentModel(nn.Module):
def... | nlptoolkit/models/rnn/birnn.py | Apache-2.0 | 6,201 | d70c2f1fa2567efcc056a3dad7a3f0aca4327022 | Python | py | |
"""
Copyright (c) 2019-2020 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 w... | tests/sparsity/magnitude/test_algo.py | Apache-2.0 | 10,872 | 03960f4171f9a64364a5eb702b8d8b1f98fac8e6 | Python | py | |
import torch
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, ChebConv, SplineConv, GATConv, DNAConv
from tinydfa import DFALayer, DFA
class ChebNet(torch.nn.Module):
def __init__(self, num_features, num_classes):
super(ChebNet, self).__init__()
self.conv1 = ChebConv(num_f... | paper-experiments/geometric-learning/models.py | MIT | 10,243 | 29b020a59c4db1fcfd7fdb044def12f248a59597 | Python | py | |
"""
Timeseries models share a number of common characteristics. This module implements these in a common base class.
"""
from collections import namedtuple
import copy
from copy import deepcopy
import inspect
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union
import matplotlib.pyplot as plt
import nu... | pytorch_forecasting/models/base_model.py | MIT | 89,111 | 24fbc020ee9d64054d9b9b593d9b24d8b0f31c03 | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import os
import torch
import torch.nn.functional as F
from torchvision.models.vgg import vgg16
from torchvision import datasets, transforms
import unittest
from unittest import TestCase, main
from nni.algorithms.compression.pytorch.quantization... | test/nni_test/nnitest/test_quantize_model_speedup.py | MIT | 7,992 | e9209b52fe7c4aea69ef2f20e5d66e92d3a5b892 | Python | py | |
import numpy as np
import torch
from .slater_jastrow import SlaterJastrow
from .jastrows.elec_elec.kernels.pade_jastrow_kernel import PadeJastrowKernel as PadeJastrowKernelElecElec
from .jastrows.jastrow_factor_combined_terms import JastrowFactorCombinedTerms
from .jastrows.elec_nuclei.kernels.pade_jastrow_kernel im... | qmctorch/wavefunction/slater_combined_jastrow.py | Apache-2.0 | 2,799 | 4b7137e7ff7d7085a6ba9316245d5969ced75c09 | Python | py | |
#!/usr/bin/env python3
#
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 requi... | examples/maml-omniglot.py | Apache-2.0 | 9,466 | 29b05fbed45e5fae180274aa3446467a542b593a | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import normal_init
from mmdet.core import delta2bbox
from mmdet.ops import nms
from ..registry import HEADS
from .ba_anchor_head import BackgroundAwareAnchorHead
@HEADS.register_module
class BackgroundAwareRPNHead(BackgroundAwareAnchorH... | mmdet/models/anchor_heads/barpn_head.py | Apache-2.0 | 4,986 | 29b06b623d6fe85cbe5c19a86a9c1d63360bda93 | Python | py | |
import torch
import numpy as np
import os
import torch.nn.functional as F
# visualization module
import matplotlib.pyplot as plt
asc_classes = ['0', '1', '2', '3', '4', '5', '6', '7','8', '9', '10', '11', '12', '13', '14']
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f... | utils/utilities.py | MIT | 6,417 | 29b078870758d4b4a3d8bad0575d8b1d3a738a3f | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@file : thucnew_dataset.py
@author: zijun
@contact : zijun_sun@shannonai.com
@date : 2021/6/30 0:03
@version: 1.0
@desc : Dataset for document classification
"""
from functools import partial
import torch
from torch.utils.data import DataLoader
from datasets.chine... | datasets/thucnew_dataset.py | MIT | 2,446 | 7ca287d6e2e71efa14c7a0cc8bdc4944731fa9fd | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import warnings
from numbers import Number
import mmcv
import numpy as np
import torch
from mmcv import DictAction
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import get_dist_info, init_dist, load_checkpo... | tools/test.py | Apache-2.0 | 8,300 | 1eafc20470e3eafe77a2772ddb6999252b74521e | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import torch
import math
import random
from . import utils
from .lv_types import ImagePlotItem
from collections import OrderedDict
from itertools import groupby, islice
def skip_mod(mod, g):
for index, item in enumerate(g):
if index ... | tensorwatch/evaler_utils.py | MIT | 4,493 | 29b0d65b94452d636efb5ec501f89da6e1e9d1c4 | Python | py | |
#!/usr/bin/env python3
# Copyright 2019 Tomoki Hayashi
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
from __future__ import print_function
from __future__ import division
import numpy as np
import pytest
import torch
from argparse import Namespace
from espnet.nets.pytorch_backend.e2e_tts_tacotron2 im... | test/test_e2e_tts_tacotron2.py | Apache-2.0 | 7,271 | 5e98d7002fab547016da026ab5e809aa2c6cce2b | Python | py | |
import torch
from torch import nn
from Models.nn_Model import nn_Model
class StackOverflow_Model(nn_Model):
def __init__(self, n_vocab=10004,sequence_length=19):
super().__init__()
self.lstm_size = 670
self.embedding_dim = 96
self.num_layers = 1
self.sequence_length = sequen... | Models/StackOverflow_Model.py | MIT | 5,141 | 6b17c927ab0508eecc482a8ac7758a043f5501cd | Python | py | |
from typing import Callable, Optional
from torch_geometric.typing import Adj, OptTensor
import torch
from torch import nn
from torch import Tensor
from torch.nn import Parameter, ReLU
import torch.nn.functional as F
from torch_sparse import SparseTensor, matmul
from torch_geometric.nn.conv import MessagePassing
from t... | torch_geometric/nn/conv/arma_conv.py | MIT | 6,275 | 804dd2ed3e99b722347ffb0b3330900986588159 | Python | py | |
"""
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | python/oneflow/test/expensive/test_rnn_pack_sequence.py | Apache-2.0 | 10,034 | 29b0f6394400e3bd343d16b5903ca1442eeed707 | Python | py | |
# -*- coding: utf-8 -*-
"""
@date: 2020/12/30 下午4:28
@file: mnasnet_unit.py
@author: zj
@description:
"""
from abc import ABC
import copy
import torch.nn as nn
from zcls.model import registry
from zcls.model.conv_helper import get_conv
from zcls.model.norm_helper import get_norm
from zcls.model.act_helper import get... | zcls/model/backbones/mobilenet/mobilenetv3_backbone.py | Apache-2.0 | 9,394 | 29b1110afe6a92e9fbe301f9814981c261f2b7ab | Python | py | |
from utils import utils
from utils import vis as V
from utils.CrossingDetector import CrossingDetector
import criteria as C
import quality as Q
import time
import itertools
import numpy as np
import torch
from torch import nn, optim
from torch.utils.data import DataLoader
import pickle as pkl
d... | gd2.py | Apache-2.0 | 24,612 | 24a209767fc448790213d9712808694d3eeda003 | Python | py | |
from functools import partial
from models.vit import VisionTransformer, interpolate_pos_embed
# from models.xbert import BertConfig, BertForMaskedLM
from models.xbert import BertConfig, BertModel, BertForMaskedLM
from typing import Dict
import torch
import torch.nn.functional as F
from torch import nn
import numpy as... | models/single_stream/baseline_pretrain.py | BSD-3-Clause | 11,815 | f9f6c244c33cb2ff1a5327f7683967e7866f64eb | Python | py | |
# coding: utf8
import torch
import pandas as pd
import numpy as np
from os import path
from torch.utils.data import Dataset
import torchvision.transforms as transforms
import abc
import logging
import warnings
from clinicadl.tools.inputs.filename_types import FILENAME_TYPE
#################################
# Dataset... | clinicadl/clinicadl/tools/deep_learning/data.py | MIT | 26,304 | 29b1677e00a3d26b14ccd62f0a8ca4f13132730d | Python | py | |
import os, sys
sys.path.append("./common")
import logging
logging.basicConfig(level = logging.INFO, format='%(levelname)s:%(name)s:%(message)s')
import pytorch_lightning as pl
from model import RNN_Model, BERT_OIE
import json
from pprint import pformat
import time
import argparse
def main():
parser = argparse.Ar... | src/train.py | MIT | 4,160 | 29b1738e643c13f802fa7f7835c79489d1ad4de4 | Python | py | |
import os
from setuptools import setup
from torch.utils.cpp_extension import CppExtension, BuildExtension
setup(name='mlpcell',
py_modules = ['mlpcell'],
#ext_modules=[CppExtension('mlpcell_ext', ['mlpcell_main.cpp'], extra_compile_args=['-fopenmp', '-g', '-O0', '-march=native'],
ext_modules=[CppExte... | samples/deeplearning/pytorch/xsmmptex/mlpcell/setup.py | BSD-3-Clause | 643 | a947394b020dcf6ebf98d9071cf33976ee902ac2 | Python | py | |
# -*- coding:utf-8 -*-
import os.path as osp
import sys
import torch
import argparse
from functools import partial
sys.path.insert(0, osp.join(osp.dirname(osp.abspath(__file__)), '../'))
from mmdet.cv_core import Timer, Config
from mmdet.models import build_detector
def parse_args():
parser = argparse.ArgumentP... | tools/infertime_analyze.py | MIT | 1,789 | 6539607bf1149d21d8f170adf0d6810be2014d1d | Python | py | |
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from .common import MLP, ResNet18, ResNet18_TinyImagenet
class Net(torch.nn.Module):
def __init__(self, n_inputs, ... | model/joint_train.py | MIT | 2,781 | ff72c0ccd4536aa41aa2ed7e7bef8ea624d0db9a | Python | py | |
"""Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dis... | preprocess.py | MIT | 5,562 | 29b1a9bc6098069cc82dbf2410beeee171c685fa | Python | py | |
from __future__ import print_function
import numpy as np
import os
import sys
import cv2
import random
import pickle
from lib.param_summary import torch_summarize_df
import torch
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import torch.optim as optim
from torch.optim import lr_scheduler
imp... | lib/ssds_train.py | MIT | 36,305 | 29b1bb46b6fe67b26277ab09f317d49166a53e96 | Python | py | |
import torch
import torch.nn as nn
import lib.layers as layers
from lib.layers.odefunc import ODEnet
import numpy as np
from . import modules
from . import thops
class ODENVP(nn.Module):
"""
Real NVP for image data. Will downsample the input until one of the
dimensions is less than or equal to 4.
Arg... | lib/odenvp_conditional_v2.py | MIT | 7,801 | 29b1f54753eaa1f36484926387ef5ebcf0ae0a7e | Python | py | |
import torch
from flask import Flask, request, jsonify
import uuid
import os
model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # or yolov5m, yolov5x, custom
names = model.names
def _detection(img):
results = model(img)
detects = []
for result in results.xyxy[0]:
p1x, p1y, p2x, p2y, score, i... | python3/microservice.py | MIT | 1,276 | 29b1f9099fa72606d48929482400a617ac1aa264 | Python | py | |
import os.path as osp
import numpy as np
import pycocotools.mask as maskUtils
from collections.abc import Sequence
import torch
from .data_container import DataContainer as DC
from .compose import Compose
import cv2
from .imgutils import rescale_size, imresize, imrescale, imflip, impad, impad_to_multiple
class LoadI... | data/piplines.py | Apache-2.0 | 28,214 | 29b224c6415ec36c8f7a17b69f973663f873408b | Python | py | |
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... | tuframework/training/network_training/nnUNet_variants/architectural_variants/nnUNetTrainerV2_FRN.py | Apache-2.0 | 2,471 | a95b9961c7f4b0d91300b8d7e9da73208f74abb2 | Python | py | |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 23 09:39:52 2020
@author: tycoer
"""
from .registry import ACTIVATION_LAYERS
import torch
@ACTIVATION_LAYERS.register_module()
class Mish(torch.nn.Module):
def __init__(self):
super(Mish, self).__init__()
def forward(self, x):
x = x * (torch.tanh... | rflib/cnn/bricks/mish.py | Apache-2.0 | 372 | 24f5ac8d8bfca8516e094d741d27cd8bd79098bb | Python | py | |
from __future__ import print_function
import torch
import torch.nn as nn
from types import MethodType
import models
from utils.metric import accuracy, AverageMeter, Timer
import ipdb
class NormalNN(nn.Module):
'''
Normal Neural Network with SGD for classification
'''
def __init__(self, agent_config):
... | agents/default.py | MIT | 11,758 | d73fda7e422822c353f72eae0c1b50baf60da20c | Python | py | |
# @Time : 2020/6/26
# @Author : Shanlei Mu
# @Email : slmu@ruc.edu.cn
# UPDATE:
# @Time : 2020/8/7, 2020/9/26, 2020/9/26, 2020/10/01, 2020/9/16, 2020/10/8, 2020/10/15, 2020/11/20, 2021/2/20, 2021/3/3
# @Author : Zihan Lin, Yupeng Hou, Yushuo Chen, Shanlei Mu, Xingyu Pan, Hui Wang, Xinyan Fan, Chen Yang, Yibo Li, ... | recbole/trainer/trainer.py | MIT | 41,711 | fdd61f1f6e29f4b8d1d39514aa3756c92e0a3596 | Python | py | |
import gym
from gym import error, spaces, utils
from gym.utils import seeding
import random
random.seed(10)
import torch
from enum import IntEnum, Enum
import numpy as np
np.random.seed(10)
class GameEnv(gym.Env):
metadata = {'render.modes': ['human', 'rgb_array']}
class Actions(IntEnum):
down = 0 ... | egg/zoo/gym-game/gym_game/envs/game_env.py | MIT | 16,527 | f9e1793a327e8bb6a361b063295e72f39da33485 | Python | py | |
"""
Conditional random field
"""
from typing import List, Tuple, Dict
import torch
from allennlp.common.checks import ConfigurationError
import allennlp.nn.util as util
def allowed_transitions(constraint_type: str, labels: Dict[int, str]) -> List[Tuple[int, int]]:
"""
Given labels and a constraint type, ret... | models/modules/conditional_random_field.py | Apache-2.0 | 17,017 | 29b2709ebb860a643983924983119ccf499f1ab1 | Python | py | |
import torch.nn as nn
eps_fea_norm = 1e-5
eps_l2_norm = 1e-10
class SOSNet32x32(nn.Module):
"""
128-dimensional SOSNet model definition trained on 32x32 patches
"""
def __init__(self, dim_desc=128, drop_rate=0.1):
super(SOSNet32x32, self).__init__()
self.dim_desc = dim_desc
s... | ThirdPartyDesc/SOSNet/sosnet_model.py | MIT | 1,966 | 4ba552d7178cadc219696e7addebdf50d8d647d9 | Python | py | |
import mmcv
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import normal_init
from mmdet.ops import DeformConv, roi_align
from mmdet.core import multi_apply, matrix_nms
from ..builder import build_loss
from ..registry import HEADS
from ..utils import bias_init_with_prob, ConvModule
IN... | mmdet/models/anchor_heads/solov2_head.py | BSD-2-Clause | 19,693 | 4b481c69e20cee9b265deaecdf1b825d5f5a9809 | 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/checkpointing/test_model_checkpoint.py | Apache-2.0 | 48,784 | 4b1733c135c3fee27ac3ac73056cd1817ff88a90 | Python | py | |
# Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
import logging
import sys
import os
import torch
import cv2
import numpy as np
from torch.utils.data import D... | pioneer/utils/DataProcess.py | Apache-2.0 | 12,337 | 7c7572ce80d5a2fda22d5557b76ee962fbc45314 | Python | py | |
#!/usr/bin/env python
# coding: utf-8
#
# Author: Kazuto Nakashima
# URL: http://kazuto1011.github.io
# Created: 2017-05-26
# Modified for U^2Net by Ian Nielsen
from collections import Sequence
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
from tqdm import tqdm
... | grad_cam.py | Apache-2.0 | 6,856 | cc33ec7558553e102ab7473c27fe31a274de582d | Python | py | |
from . import SentenceEvaluator
import torch
from torch import Tensor
import logging
from tqdm import tqdm, trange
from ..util import cos_sim, dot_score
import os
import numpy as np
from typing import List, Tuple, Dict, Set, Callable
logger = logging.getLogger(__name__)
class InformationRetrievalEvalu... | sentence_transformers/evaluation/InformationRetrievalEvaluator.py | Apache-2.0 | 12,802 | d7fa5db9071f21786d393943088aebac7349811d | Python | py | |
# Copyright (c) Meta Platforms, Inc. and its affiliates. All Rights Reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import os
import random
import time
import unittest
import numpy as np
import torch
from Crypto.... | test/test_csprng.py | BSD-3-Clause | 28,414 | dfce378f744893255d510079032023b2269a7187 | Python | py | |
"""
# -*- coding: utf-8 -*-
# @File : model.py
# @Time : 2020/11/26 1:55 下午
# @Author : xiaolu
# @Email : luxiaonlp@163.com
# @Software: PyCharm
"""
import torch
import torch.nn as nn
class Siamese(nn.Module):
def __init__(self):
super(Siamese, self).__init__()
self.conv = nn.Sequential(
... | Image_Similarity/siamese-net/model.py | Apache-2.0 | 1,334 | fcd4deeb3dbcff688a7846881b2d65b8c9670de2 | Python | py | |
from model.DFL import DFL_VGG16, DFL_ResNet, DFL_ResNet_for_sample
from utils.util import *
from utils.transform import *
from train import *
from validate import *
from utils.init import *
import sys
import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
im... | main.py | MIT | 8,301 | ff765b3fc29cd5287dc5470fc1c16ec12c696908 | Python | py | |
import torch
from . import _functional as F
from ..optimizer import Optimizer
class ASGD(Optimizer):
"""Implements Averaged Stochastic Gradient Descent.
It has been proposed in `Acceleration of stochastic approximation by
averaging`_.
Args:
params (iterable): iterable of parameters to optimiz... | torch/optim/_multi_tensor/asgd.py | Intel | 3,925 | 529ffc01aa9c10dcd07a1a622938d3cc484b75c9 | Python | py | |
"""
Created on Tue Jun 23 20:15:11 2020
@author: sarroutim2
"""
"""Loads question answering data and feeds it to the models.
"""
import h5py
import numpy as np
import torch
import torch.utils.data as data
class VQGDataset(data.Dataset):
"""Custom Dataset compatible with torch.utils.data.DataLoader.
"""
... | utils/data_loader.py | MIT | 4,526 | 29b3572d81bd93dfaa7278056442822dcca4e391 | Python | py | |
import warnings
from typing import Optional, Tuple
import torch
from kornia.geometry.bbox import bbox_generator3d as _bbox_generator3d
from kornia.geometry.bbox import bbox_to_mask3d as _bbox_to_mask3d
from kornia.geometry.bbox import infer_bbox_shape3d as _infer_bbox_shape3d
from kornia.geometry.bbox import validate... | kornia/geometry/transform/crop/crop3d.py | ECL-2.0,Apache-2.0 | 21,585 | 1e860f79a18194dfce3b243dc2f3b67561b6a038 | Python | py | |
# Copyright 2021 MosaicML. All Rights Reserved.
import functools
import numpy as np
import pytest
import torch
from PIL import Image
from composer.algorithms import ColOut, ColOutHparams
from composer.algorithms.colout.colout import ColOutTransform, batch_colout
from composer.core import Event
from composer.trainer ... | tests/algorithms/test_colout.py | Apache-2.0 | 7,809 | 1022c55184b00aceae3064bf75c0d9dbd06e298d | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal
class ValueNetwork(nn.Module):
def __init__(self, input_dim, output_dim, init_w=3e-3):
super(ValueNetwork, self).__init__()
self.fc1 = nn.Linear(input_dim, 256)
self.fc2 = nn.Linear(2... | Policy-Gradient-Methods/sac/models.py | MIT | 2,716 | e9bd4cfccfe97677506fb656311e651fb3bde078 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.