content stringlengths 200 198k | repo stringlengths 4 186 | path stringclasses 1
value | license stringclasses 101
values | size int64 200 198k | sha stringlengths 40 40 | lang stringclasses 1
value | ext stringclasses 1
value |
|---|---|---|---|---|---|---|---|
import pandas as pd
import pytorch_lightning as pl
import sastvd as svd
import sastvd.helpers.datasets as svdd
import sastvd.ivdetect.evaluate as ivde
import torch
import torch.nn.functional as F
import torchmetrics
from torch.utils.data import DataLoader
from transformers import AutoModel, AutoTokenizer
class BigVul... | sastvd/codebert/main.py | MIT | 7,676 | d71a630aee2de6d13f37e688058b6581fdb81bbd | Python | py | |
# -*- Python -*-
# This file is licensed under a pytorch-style license
# See LICENSE.pytorch for license information.
import torch
from torch_mlir.dialects.torch.importer.jit_ir import ModuleBuilder
# RUN: %PYTHON %s | torch-mlir-opt | FileCheck %s
mb = ModuleBuilder()
# CHECK-LABEL: @__torch__.f
@mb.import_functio... | test/python/importer/jit_ir/node_import/elif.py | Apache-2.0 | 778 | 3a9d3a3211e242d5159b5bef6edc1875c9ccfdf9 | Python | py | |
import torch
from torch import nn
class BinaryClassifier(nn.Module):
default_config = None
def __init__(self, embedding, encoder, aggregator, mlp, out, lossfunc):
super().__init__()
self.embedding = embedding
self.encoder = encoder
self.aggregator = aggregator
self.ml... | qiqc/modules/classifier.py | MIT | 1,380 | 3a9d43d6f245afd075c5c8f7c703d68ed0926f93 | Python | py | |
#!/usr/bin/env python3
# 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 torch
import torch.nn as nn
from layers import StackedAttention, StackedAttention1D, convn... | daqa-mod/models.py | CC-BY-4.0 | 21,031 | 3a9d4c708703d17450256a19ab1be00a311d5d73 | Python | py | |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors, The HuggingFace Inc. Team and deepset 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 m... | farm/modeling/language_model.py | Apache-2.0 | 81,723 | 3a9d4cec0f75b2e19ba94a94b68cfa126f1ddc51 | Python | py | |
""" Recurrent model training """
import argparse
from functools import partial
from os.path import join, exists
from os import mkdir
import torch
import torch.nn.functional as f
from torch.utils.data import DataLoader
from torchvision import transforms
import numpy as np
from tqdm import tqdm
from utils.misc import sav... | world-models/trainmdrnn.py | MIT | 8,081 | 3a9d6b6f3cb21b09d0a6ece0d6e53f8ebb2d7fe0 | Python | py | |
# ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# -------------------------------------------------------------------... | Tests/ML/utils/test_checkpoint_handling.py | MIT | 21,775 | 5ea8d75bfc8f539d825f293f6f31810a4a659c0e | Python | py | |
import torch, os
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as datasets
import torch.utils.data as data
import torchvision.transforms as transforms
import torchvision.models as models
from models.train_model import train_model
from models.AlexNet3 import alexnet
from models.CNN_3 impo... | Decon_edit.py | MIT | 31,215 | 1e78e84dc76e892a2eb8a2570a33b7e5beace845 | Python | py | |
"""
Train and validate with distributed data parallel
Fred Zhang <frederic.zhang@anu.edu.au>
The Australian National University
Australian Centre for Robotic Vision
"""
import os
import torch
import argparse
import torchvision
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.utils.data ... | main.py | BSD-3-Clause | 7,252 | 3a9d873571e136eb9a3069e0411419ece128c30d | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""DenseNet with Detection-Batch Normalization models.
"""
from __future__ import annotations
from collections import OrderedDict
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from onevision.fact... | src/onevision/models/classification/densenet/densenet_ibn.py | MIT | 15,709 | f98cefa70fe91ab7416dc3440dc935ed9c218707 | Python | py | |
#######################################################################
# Copyright (C) 2017 Shangtong Zhang(zhangshangtong.cpp@gmail.com) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
################################... | deep_rl/agent/PPO_recurrent_2_agent.py | MIT | 13,303 | 5e19cacea28fa9b960cb191e5e5cf861fbc127ee | Python | py | |
import imghdr
import numpy as np
import pandas as pd
import torch
import torch.utils.data as data
from pathlib import Path
from tqdm import tqdm
from data_loader import ImageLoader
from models import ClassificationModel
# Input image size to your model
IMAGE_SIZES = 488
# Folder containing the test images
TEST_FOLDE... | PyTorchClassification/snakes/test_snakes.py | MIT | 4,168 | a93d98a5d2810c516e6ce3918870ffcaeac9bd09 | Python | py | |
"""Datasets."""
import os
import numpy as np
import torch
from torch.utils.data import Dataset
from torchvision import datasets
from torchvision import transforms
BASEPATH = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', '..', '..', '..', '..', 'data'))
class MNIST(datasets.MNIST):
"""MNIS... | evaluation/models/topoae/src/datasets/mnist.py | MIT | 1,005 | 3a9daf53fdf03f554367c830a600dc1dbd9f1a6c | Python | py | |
import torch
from torch import nn
from utils.bbox_utils import get_iou, bbox_format_transform
class Yolov1_loss(nn.Module):
"""
这个类是根据yolov1训练机制编写的,包含了四个主要loss:
1.使用MSE对分类进行loss计算;
2.使用bbox回归对有物体的边界框进行损失计算;
3.对无物体的边界框进行损失计算——只算置信度;
4.使用MSE对bbox置信度进行损失计算;
inputs:pred 和 lab... | model/loss.py | Apache-2.0 | 9,285 | 7cc2e5c7884f83cc14eccc061f74df8ef2726767 | Python | py | |
#!/usr/bin/env python
"""Training on a single process."""
import os
import torch
from onmt.inputters.inputter import build_dataset_iter, \
load_old_vocab, old_style_vocab, build_dataset_iter_multiple
from onmt.model_builder import build_model
from onmt.utils.optimizers import Optimizer
from onmt.utils.misc import... | onmt/train_single.py | MIT | 4,781 | e65002b9e9a4c0662b9dcb3b12f084d55d1d60d7 | Python | py | |
import torchvision
from torch import nn
import torch.onnx
from models.faceboxes import FaceBoxes
def remove_prefix(state_dict, prefix):
''' Old style model is stored with all names of parameters sharing common prefix 'module.' '''
f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x
retur... | make_onnx_copy.py | MIT,Unlicense | 2,583 | 5f5b5bea7e1c635e392a40b6b617abe3334ddea9 | Python | py | |
import torch
import torch.nn as nn
class PasticheModel(torch.nn.Module):
def __init__(self, num_styles):
super(PasticheModel, self).__init__()
self.conv_layer1 = nn.Sequential(
nn.ReflectionPad2d(4),
nn.Conv2d(3, 32, (9, 9))
)
self.conv_layer2 = nn.Sequenti... | Pastiche.py | BSD-3-Clause | 3,064 | b243252cb7c883a8e0d1116df672052ed7680c89 | Python | py | |
from __future__ import print_function
import argparse
import random
import numpy as np
import torch
import sys
sys.path.append('./auxiliary/')
from dataset import *
from model import *
from my_utils import *
from ply import *
import os
import json
import pandas as pd
# =============PARAMETERS==========================... | inference/run_SVR_AtlasNet.py | MIT | 7,248 | 3a9dd945c2cb1c76b38c5fd92a14624d02573e5e | Python | py | |
import os
import os.path as osp
import sys
import time
import torch
import torch.nn as nn
import numpy as np
import _init_paths
import utils as utl
from configs.thumos import parse_second_args as parse_args
from models import build_model
def to_device(x, device):
return x.unsqueeze(0).to(device)
def main(args):... | thumos_second_eval.py | MIT | 4,367 | 3a9de3aa072e1145afc4b7a0b0c1abc6efd28f1b | Python | py | |
import os
import os.path as osp
import numpy as np
from torch.utils import data
from PIL import Image, ImageFile
import pickle
import torch
ImageFile.LOAD_TRUNCATED_IMAGES = True
class GTAVDataSet(data.Dataset):
def __init__(self,
data_root,
data_list,
max_iters... | core/datasets/gtav.py | MIT | 4,746 | 4b72c0247636eb52c97cc07ddac4154c7576bbf3 | Python | py | |
import os
import sys
import time
import argparse
import glob
import math
import csv
import numpy as np
import random
from shutil import copy2
import torch
from torch.autograd import Variable
import torch.nn as nn
from data_attention_bottom import get_train, get_batch, build_vocab, get_word_dict, get_target_expl_batch... | attention/train_attention_bottom.py | MIT | 20,896 | e92d5367ce4545f87739f4c874806f66dde95b68 | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import torch
from progress.bar import Bar
from models.data_parallel import DataParallel
from utils.utils import AverageMeter
from typing import List, Optional, Dict
from argparse import Namespace
fr... | src/lib/trains/base_trainer.py | MIT | 4,914 | 5fbdc5218452cb5e449b6e89b508d2c5adea91e9 | Python | py | |
import torch.nn as nn
from .decoder import Decoder
from .encoder import Encoder
class Transformer(nn.Module):
"""An encoder-decoder framework only includes attention.
"""
def __init__(self, encoder=None, decoder=None):
super(Transformer, self).__init__()
self.encoder = encoder
se... | transformer/transformer.py | Apache-2.0 | 1,750 | 3a9e473002307d23d3871961eeaf208de0e174bb | Python | py | |
import json
import os
from argparse import ArgumentParser
import pandas as pd
import time
import torch
from torch.utils.data import DataLoader
from torch import nn, optim
import learn2learn as l2l
from common.metrics import display
from common.data_preparation import parser_add_data_arguments, data_preparation
from .... | src/MetaSearch/run.py | MIT | 6,995 | 3a9e555027098b726d38a46c379b5e9aae90d55c | 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/logging_/test_logger_connector.py | Apache-2.0 | 23,514 | 3a9e56018c26713b100f77a82993073aa088a839 | Python | py | |
import argparse
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
sample_corpus = [
'he is a king',
'she is a queen',
'she is a man',
'she is a woman',
'warsaw is poland capital',
'berlin is germany cpital',
'paris is france capital',
]
de... | deep_learning/nlp/word2vec.py | MIT | 3,461 | 70529017ad735ffcbde828632ec9a121f8fe2f26 | Python | py | |
#!/usr/bin/env python
# pylint: disable=W0201
import sys
import argparse
import yaml
import numpy as np
# torch
import torch
import torch.nn as nn
import torch.optim as optim
# torchlight
import torchlight
from torchlight import str2bool
from torchlight import DictAction
from torchlight import import_class
from .io ... | processor/processor.py | BSD-2-Clause | 7,839 | 3a9e5f693412a75e415fa92822ed3ce03c3514bc | Python | py | |
from __future__ import print_function, division, absolute_import
import torch
import torch.nn as nn
from torch.utils import model_zoo
__all__ = ['PolyNet', 'polynet']
pretrained_settings = {
'polynet': {
'imagenet': {
'url': 'http://pretorched-x.csail.mit.edu/models/polynet-f71d82a5.pth',
... | src/deps/pretorched/models/polynet.py | MIT | 17,276 | d7e52e6b0f4cae1ec3e5b38f38f6ed0aad8e1a5d | Python | py | |
import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as data
from torch.utils.data import Dataset
import numpy as np
import time
import os
from torch.nn import BCEWithLogitsLoss,MSELoss
from processing import roll_to_midi
USE_CUDA = t... | Muse.py | MIT | 7,283 | 45b3056913f02eabb8dd6f8bd5d20a330f0202fd | Python | py | |
import torch
import os
import copy
import matplotlib.pyplot as plt
from torch.utils.tensorboard import SummaryWriter
from collections import deque
from torch.utils.data import Subset
#from datasetv1 import hierarchical_dataset, AlignCollate, Batch_Balanced_Dataset
#from fastNLP import logger
device = torch.device('cud... | Recognition/utils.py | Apache-2.0 | 13,123 | 4553d4f551df67c0683e8e10ca254ab317f73264 | Python | py | |
import torch
import torch.nn as nn
def loss_ssim(img1, img2):
'''
Inputs:
- img1 torch.Tensor (B, 3, H, W)
- img2 torch.Tensor (B, 3, H, W)
Returns:
- loss_ssim torch.Tensor (B)
Examples:
- For img1 and img2 both shaped (H, W, 3), you could use
- 'loss_ssim(img1.permute(2,0,1)[None... | core/utils/pytorch_ssim/ssim.py | MIT | 1,040 | 6b455e7780c14c0de9c27347146530c32817c50e | Python | py | |
from typing import List
import torch
import torch.nn as nn
from .core import EncoderSpec, _take
from ..blocks.unet import EncoderDownsampleBlock
class UnetEncoder(EncoderSpec):
def __init__(
self,
in_channels: int,
num_channels: int,
num_blocks: int,
layers_indices: List[... | catalyst/contrib/models/segmentation/encoder/unet.py | Apache-2.0 | 1,867 | 4b6b961ed5d289b8ffb9ead16fb8e55eb0a8c1be | Python | py | |
"""
PointPillars fork from SECOND.
Code written by Alex Lang and Oscar Beijbom, 2018.
Licensed under MIT License [see LICENSE].
"""
import torch
from torch import nn
from torch.nn import functional as F
from pfeparser.voxel_encoder import get_paddings_indicator, register_vfe
from torchplus.nn import Empty
from torchp... | ai/quantization/onnx/src/pfeparser/pfe.py | Apache-2.0 | 8,025 | 3a9e978b92d1f2d964619bfdc2d538b7fe90032e | Python | py | |
#!/usr/bin/env python
# coding: utf-8
# * https://pytorch.org/tutorials/beginner/data_loading_tutorial.html
# * https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html
# * https://pytorch.org/tutorials/beginner/saving_loading_models.html
# In[1]:
# In[2]:
import numpy as np
import os
import pandas as pd... | token_cnn_experiments.py | MIT | 14,441 | 3a9e9cfafdf7a96403498179fef85c552b41cc1f | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import contextlib
import os
import tempfile
import unittest
from unittest.mock import patch
import torch
from mmf.trainers.callbacks.checkpoint import CheckpointCallback
from mmf.trainers.callbacks.early_stopping import EarlyStoppingCallback
from mmf.trainers.lightni... | tests/trainers/lightning/test_checkpoint.py | BSD-3-Clause | 21,593 | 4b4f753339da9f3aa924c0e3e95107756afafe64 | Python | py | |
# coding: utf-8
"""
Synthesis waveform from trained model.
usage: synthesis.py [options] <checkpoint> <text_list_file> <dst_dir>
options:
--hparams=<parmas> Hyper parameters [default: ].
--preset=<json> Path of preset parameters (json).
--checkpoint-seq2seq=<path> Lo... | synthesis.py | MIT | 6,571 | 52b596ac02cb10c5c46fea8a3bfd9f5f5ade76ee | Python | py | |
import src.model
from src.dataloader import MaskData, KeypointData
import src.transforms as t
import src.utils
import torch.optim
import numpy as np
import time
from torch.utils.data import DataLoader
import torchvision
import matplotlib.pyplot as plt
def train_mask_rcnn(data=None, epochs: int = None, lr: float = No... | src/train.py | MIT | 5,233 | cc31333addf4ab60e0a28defa1bc924166c42dcd | Python | py | |
import torch, operator, msgpack, nltk, math, os, copy, pytz, sys, re
import dateutil.parser
import scipy.stats
import visdom
import numpy as np
from gensim.models import Word2Vec, FastText
from gensim.models.callbacks import CallbackAny2Vec
from nltk.corpus import stopwords
from datetime import datetime
from random ... | make_splits.py | MIT | 17,813 | 6b28b7b36d003768f1b97454129952f05f069ea0 | Python | py | |
"""
PixelSNAIL implementation following https://github.com/neocxi/pixelsnail-public
References:
1. Xi Chen, PixelSNAIL: An Improved Autoregressive Generative Model
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
# --------------------
# Helper functions
# --------------------
def down_s... | generative_models_toolbox/algos/pixelcnn/pixelsnail.py | MIT | 6,961 | 52f07cfcde3ee6bb7e25b3a6c44455e805643f50 | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
# --------------... | parlai/agents/drqa/layers.py | MIT | 8,755 | 3a9ec78658085b9c618705fd5a9b05dd1a4fbdb0 | Python | py | |
"""Test script for Time Predictor Network (TPN).
Once you have trained your model with train_time.py, you can use this script to test the model.
It will load a saved model from --checkpoints_dir and print out the results.
It first creates model and dataset given the option. It will hard-code some parameters.
It then ... | test_time.py | MIT | 3,083 | cc0318d7b522da89d2476a2f96262c4ac612ecc2 | Python | py | |
from typing import Callable, List, Union
import pytest
from tests.text.helpers import INPUT_ORDER, TextTester
from tests.text.inputs import _inputs_error_rate_batch_size_1, _inputs_error_rate_batch_size_2
from torchmetrics.utilities.imports import _JIWER_AVAILABLE
if _JIWER_AVAILABLE:
from jiwer import compute_m... | tests/text/test_mer.py | Apache-2.0 | 2,087 | 3a9f126648afc51c4bda61fdca00424168324acf | Python | py | |
#!/usr/bin/env python
import os
from io import open
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
try:
import builtins
except ImportError:
import __builtin__ as builtins
# https://packaging.python.org/guides/single-sourcing-package-version/
# http://blog.ionelmc.ro/201... | setup.py | Apache-2.0 | 3,780 | dfcaf29a5990e9c5d89763c5d295c4cc7fe33737 | Python | py | |
# coding=utf-8
# 导入自己的函数包d2lzh_pytorch,注意要先将目标包的父路径添加到系统路径中
import sys
sys.path.append(r".")
from d2lzh_pytorch import data_process
from d2lzh_pytorch import layers
from d2lzh_pytorch import train
from d2lzh_pytorch import plot
import torch
import pandas as pd
import torch.nn as nn
import numpy as np
"""
这一节是这一章的总结... | Chapter3/Chapter3_16.py | BSD-2-Clause | 6,552 | 3a9f129f73567fcb7e5cb251a724356c1958d0ae | Python | py | |
"""MidashNet: Network for monocular depth estimation trained by mixing several datasets.
This file contains code that is adapted from
https://github.com/thomasjpfan/pytorch_refinenet/blob/master/pytorch_refinenet/refinenet/refinenet_4cascade.py
"""
import torch
import torch.nn as nn
from .base_model import BaseModel
f... | MultiObjectiveModel_YMPNet_Pavan/midasnet_encoder.py | MIT | 2,701 | f9bd62aed74021a555be3aa1698d259e36e7575f | Python | py | |
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from cmws import util
from cmws.examples.csg import render
from tqdm import tqdm
class Model(nn.Module):
def __init__(self):
super().__init__()
self.mlp = util.init_mlp(2, 1, 100, 3)
@property
def device(self):
ret... | cmws/examples/csg/train_occupancy.py | MIT | 2,907 | f9cb0fdc8c32bc19e54adc87645e144f47e2aea4 | Python | py | |
"""Training GCMC model on the MovieLens data set.
The script loads the full graph to the training device.
"""
import os, time
import argparse
import logging
import random
import string
import pandas as pd
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from data import DataS... | IMC_GAE_random_sample/train.py | Apache-2.0 | 25,190 | 3a9f175b0466629a6a99d6940e7479d40e99c559 | Python | py | |
import os
import torch
from argparse import Namespace
from torch.utils.data.dataloader import DataLoader, default_collate
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data.sampler import RandomSampler, SequentialSampler
from torchblocks.optims import AdamW
from torchblocks.opt... | torchblocks/trainer/base.py | MIT | 19,363 | 7c3a5160288a595e52ebe26cb77e24b14681ede4 | Python | py | |
import torch.nn as nn
import torch
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
class cnn_lstm(nn.Module) :
def __init__(self,seq_len=128, ini_len=18, final_len=1) :
super().__init__()
self.d_model = 20
self.seq_len = seq_len
self.hidden_size = 32
... | Models/CNN_LSTM.py | BSD-3-Clause | 1,296 | 12a7850c7379d7f19668d2f06f8cadafc4f5284d | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) IBM Corporation 2018
#
# 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
#
# U... | problems/seq_to_seq/algorithmic/serial_recall_simplified.py | Apache-2.0 | 5,681 | 1e10733a67477a99d64173c01422c65c57464603 | Python | py | |
import torch
from torch import Tensor
import torch.nn as nn
from torchvision.models.utils import load_state_dict_from_url
from typing import Type, Any, Callable, Union, List, Optional
from models.masked_psg_conv import PredictiveConv2d
from masked_layers import layers as masked_layers
# __all__ = ['ResNet', 'resnet1... | models/masked_psg_imagenet_resnet.py | MIT | 23,441 | 703cbb12ff12dd73af93ea87fc2d44027889cd65 | Python | py | |
import torch
class AnchorGenerator(object):
def __init__(self, base_size, scales, ratios, scale_major=True, ctr=None):
self.base_size = base_size
self.scales = torch.Tensor(scales)
self.ratios = torch.Tensor(ratios)
self.scale_major = scale_major
self.ctr = ctr
self... | mmdet/core/anchor/anchor_generator.py | Apache-2.0 | 3,209 | 34680e01a307547254f8af5e5535f78f0fb468c0 | Python | py | |
# -----------------------------------------------------
# Copyright (c) Shanghai Jiao Tong University. All rights reserved.
# Written by Jiefeng Li (jeff.lee.sjtu@gmail.com)
# -----------------------------------------------------
from torch import nn
class SELayer(nn.Module):
def __init__(self, channel, reductio... | AlphaPose/alphapose/models/layers/SE_module.py | MIT | 784 | 3a9f940b7635fae0661b25a2129c799b7c9454a8 | Python | py | |
def main():
#gen coco pretrained weight
import torch
num_classes = 11
model_coco = torch.load("/media/liuxin/DATA/CV/Project/TianChi/mmdetection-master/checkpoints/cascade_rcnn_r50_fpn_1x_20190501-3b6211ab.pth") # weight
model_coco["state_dict"]["bbox_head.0.fc_cls.weight"] = \
model_coco["... | checkpoints/modify.py | Apache-2.0 | 1,291 | b2ba94c7acbb856e8b27364bef08f665d9fb6297 | Python | py | |
# This code is from
# Pareto Multi-Task LearningLin
# Xi Lin, Hui-Ling Zhen, Zhenhua Li, Qingfu Zhang, Sam Kwong
# Neural Information Processing Systems (NeurIPS) 2019
# https://github.com/Xi-L/ParetoMTL
import numpy as np
import torch
from torch.autograd import Variable
from .base import Solver
from .min_norm_solver... | multiMNIST/solvers/mgda.py | MIT | 2,649 | d74de6912cecc580e26a66854b317aee2d6b709b | Python | py | |
# Copyright 2019 The Texar Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | BIT_DL/pytorch/core/attention_mechanism.py | MIT | 41,716 | 3a9fcb831e9ea3405dc4a430c0f146e341b46a23 | Python | py | |
import abc
from abc import abstractmethod
from torch import nn
'''
Every implemented Autoencoder should inherit this base class
'''
class BaseAutoencoder(nn.Module,abc.ABC):
def __init__(self):
super(BaseAutoencoder, self).__init__()
@abstractmethod
def encode(self, input):
'''
... | naturalnets/autoencoder/BaseAutoencoder.py | MIT | 1,608 | 3a9fcf9e46d0065ce5711a5f017cc083ce8e3eb3 | Python | py | |
import argparse
import cv2 as cv
import torch
from cvtk.io import load_json, save_pkl
from mmcv.parallel import collate
from mmcv.parallel import scatter
from mmdet.apis import init_detector
from mmdet.datasets.pipelines import Compose
################################################################
from mmdet.datase... | references/mmdetection/dev/py_app.py | MIT | 3,528 | 10a0811e3c15c34f89bcda76dddc2e0f3f130d55 | Python | py | |
"""Freezing
This is not intended to be imported directly; please use the exposed
functionalities in `torch.jit`.
"""
from typing import Optional, List
import torch
from torch.jit._script import RecursiveScriptModule, ScriptModule
def freeze(mod, preserved_attrs: Optional[List[str]] = None, optimize_numerics: bool ... | torch/jit/_freeze.py | Intel | 9,212 | 45b9747662644541dd8e1c76a5f3ff1c7e57bc72 | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import torch
from archai.nas.model import Model
from archai.nas.model_desc_builder import ModelDescBuilder
from archai.common.common import common_init
def test_darts_zero_model():
conf = common_init(config_filepath='confs/algos/dar... | tests/zero_model_test.py | MIT | 1,131 | 3a9ff69e5c8efa5ed541c47a041135ab3449b0b6 | Python | py | |
# provide a t-sne vis for the embedded features
import os
import copy
import numpy as np
import torch
import torch.nn.functional as F
import dgl
import argparse
from gat import GAT
from utils import evaluate, collate
from utils import get_data_loader, save_checkpoint, load_checkpoint
from utils import evaluate_model,... | visualization.py | MIT | 7,546 | 3aa00597d046f7ad6743000d5b5bf3d9a7cf7f98 | Python | py | |
# Testing for script 32
import pickle
from sys_simulator.channels import BANChannel
from sys_simulator import general as gen
from sys_simulator.q_learning.environments.completeEnvironment5dB\
import CompleteEnvironment5dB
from sys_simulator.dqn.agents.dqnAgent import ExternalDQNAgent
from sys_simulator.dqn.externa... | scratch_dql/scratch35.py | MIT | 4,944 | 3aa016eefabe91af2a4bdd9b71cb7333c0eaf11d | Python | py | |
import torch
class MlpModel(torch.nn.Module):
"""Multilayer Perceptron with last layer linear.
Args:
input_size (int): number of inputs
hidden_sizes (list): can be empty list for none (linear model).
output_size: linear layer at output, or if ``None``, the last hidden size will be th... | rlpyt/models/mlp.py | MIT | 1,761 | 28da868b2ca0777a87b9ffda746f27eea61549a9 | Python | py | |
import glob
import math
import os
import os.path as osp
import random
import time
from collections import OrderedDict
import cv2
import json
import numpy as np
import torch
import copy
from torch.utils.data import Dataset
from torchvision.transforms import transforms as T
from cython_bbox import bbox_overlaps as bbox... | src/lib/datasets/dataset/jde_yolov5.py | MIT | 35,332 | ff807f9c767a5998fe41b88ebf98612a9abb38c3 | Python | py | |
import itertools
import json
from dataclasses import dataclass
import numpy as np
import pandas as pd
import seqeval.metrics as seqeval_metrics
import torch
from scipy.stats import pearsonr
from scipy.stats import spearmanr
from sklearn.metrics import f1_score
from sklearn.metrics import matthews_corrcoef
from typin... | jiant/tasks/evaluate/core.py | MIT | 42,746 | 5e07224eb35880e872e52b989864487f207276f1 | Python | py | |
'''CUB-200-2011 Pytorch dataset.'''
# pylint: disable=no-member
# pylint: disable=not-callable
__all__ = ['CUBDataset', 'CUBDatasetLazy']
import os
import string
import torch
# import torchvision.transforms as transforms
import torchfile
import h5py
class CUBDataset(torch.utils.data.Dataset):
# pylint: disable... | crnns4captions/utils/dataset.py | MIT | 11,412 | 707e779163022130759b85c4d8eef6cd467c14a6 | Python | py | |
#AUTOGENERATED! DO NOT EDIT! File to edit: dev/03_torch_core.ipynb (unless otherwise specified).
__all__ = ['progress_bar', 'master_bar', 'tensor', 'set_seed', 'unsqueeze', 'unsqueeze_', 'apply', 'to_detach',
'to_half', 'to_float', 'default_device', 'to_device', 'to_cpu', 'to_np', 'TensorBase', 'TensorCateg... | dev/local/torch_core.py | Apache-2.0 | 14,868 | 249ecdf93c6c7c45472b4a6b911a2a76b9be27bd | Python | py | |
import pytest
import librosa
import torch
import matplotlib.pyplot as plt
from scipy.signal import chirp, sweep_poly
from nnAudio.Spectrogram import *
from parameters import *
gpu_idx=0
# librosa example audio for testing
example_y, example_sr = librosa.load(librosa.util.example_audio_file())
@pytest.mark.parametri... | Installation/tests/test_spectrogram.py | MIT | 16,850 | 3aa074c1e549be802d2f2c2c7182ea42340c9c89 | Python | py | |
import pytest
import torch
from torch import nn
from pfrl.nn import Branched
from pfrl.testing import torch_assert_allclose
@pytest.mark.parametrize("batch_size", [1, 2])
def test_branched(batch_size):
link1 = nn.Linear(2, 3)
link2 = nn.Linear(2, 5)
link3 = nn.Sequential(
nn.Linear(2, 7),
... | tests/nn_tests/test_branched.py | MIT | 698 | 3aa07c4730c030f6aae9a68361181207317020e2 | Python | py | |
#!/usr/bin/env python3
# encoding: utf-8
import torch as th
from rls.algorithms.single.dqn import DQN
from rls.common.decorator import iton
from rls.utils.torch_utils import n_step_return
class CQL_DQN(DQN):
"""
Conservative Q-Learning for Offline Reinforcement Learning, http://arxiv.org/abs/2006.04779
... | rls/algorithms/single/offline/cql_dqn.py | Apache-2.0 | 2,040 | 42113353ee6353abb3c602ca4e260bfa38da7f81 | Python | py | |
import copy
import torch
import torch.nn as nn
from mmcv.cnn import ConvModule, constant_init, normal_init
from torch.nn.modules.batchnorm import _BatchNorm
from mmpose.utils import get_root_logger
from ..builder import BACKBONES
from .base_backbone import BaseBackbone
from .utils import load_checkpoint
class CpmBl... | mmpose/models/backbones/cpm.py | Apache-2.0 | 5,921 | 3aa09523ed7aa448f09321b5359779583f8ee7d9 | Python | py | |
from typing import Any
import torch as th
from ..agent import MARLAgent
class ActorCriticAgent(MARLAgent):
def __init__(self, discount_factor: float, init_q_lr: float, init_exploration: float,
init_policy_lr: float, ac_net_factory, q_lr_decay=None, exploration_decay=None,
policy_lr_decay=None, lo... | mltk/marl/algorithms/actor_critic.py | MIT | 1,422 | 6542b6c484189474cdba1367511c63301d5ed555 | Python | py | |
# -*- coding: utf-8 -*-
import math
import warnings
import torch
from torch import Tensor
from torch.nn.parameter import Parameter, UninitializedParameter
from .. import functional as F
from .. import init
from .lazy import LazyModuleMixin
from .module import Module
from .utils import _single, _pair, _triple, _reverse... | torch/nn/modules/conv.py | Intel | 72,222 | 3aa0cab8601dbf5852997e2de87ecddd78df66f6 | Python | py | |
import numpy as np
import argparse
from glob import glob
from copy import copy
import random
import pickle
# network
import torch
import torch.nn.functional as F
torch.manual_seed(0)
# GPU config
GPU = False
device = torch.device("cuda" if GPU else "cpu")
hidden_dim = 128
mb = 32
opt = "Adam" # SGD, Adam
C = 3 # w... | Question_nlp/answers/word2vec_pytorch.py | MIT | 8,978 | 7086a15c288fc276de31b09ccdd84c140b794ff4 | Python | py | |
import torch
import numpy as np
from tqdm import tqdm
import time
def norm_comparison(queries, obj_guess_raw):
lhs_norm, guess_norm = None, None
try:
if not torch.is_tensor(queries):
queries = queries[0]
if len(list(queries.shape)) == 0:
lhs_norm = queries
els... | codes/kbc/metrics.py | MIT | 4,290 | f94d35451d3c090e518fb2b798052d4119b784aa | Python | py | |
""" Full assembly of the parts to form the complete network """
import torch.nn.functional as F
import torch.nn as nn
import torch
from .unet_parts import *
class UNet(nn.Module):
def __init__(self, n_channels=3, n_classes=3, bilinear=True):
super(UNet, self).__init__()
self.n_channels = n_channe... | unet/unet.py | BSD-3-Clause | 1,395 | 1edba7a2459b78eaeff19a1315da7c8baab667f1 | Python | py | |
"""
Code to train a neural network to identify whether a given word image is struck through or not.
"""
import logging
import time
from pathlib import Path
from typing import List, Tuple
import numpy as np
import torch
from sklearn.metrics import f1_score, accuracy_score
from torch.utils.data import DataLoader
from .... | strikethrough_identification/src/train.py | MIT | 6,866 | 3aa121dc17c16c386ea75a7f301b9268f1d5a581 | Python | py | |
#takes a log file, returns a list of the total time - from start to finish - required to train each critic
import torch
import pandas as pd
import pickle
import os
def get_training_time(log):
num_crit = len(log['steps'])#one step for each critic
time_reqd = torch.zeros(num_crit)
steps = log['steps']
ti... | TTC_utils/get_training_time.py | MIT | 1,371 | dfeab16b265ded77293d7f034c47195aecf936aa | Python | py | |
import torch
import torch.nn as nn
from timm.models.helpers import load_pretrained
from timm.models.registry import register_model
from timm.models.layers import trunc_normal_
from timm.models.resnet import resnet26d, resnet50d, resnet101d
import numpy as np
import math
from .layers import *
from utils imp... | lvvit/models/lvvit.py | Apache-2.0 | 17,723 | a98a6614e0848bd680993d2b4f2b13b3264e39b7 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.utils.model_zoo as model_zoo
__all__ = ['SqueezeNet', 'squeezenet1_0', 'squeezenet1_1']
model_urls = {
'squeezenet1_0': 'https://download.pytorch.org/models/squeezenet1_0-a815701f.pth',
'squeezenet1_1': 'https://download.pytorch.or... | torchvision/models/squeezenet.py | BSD-3-Clause | 4,924 | 3aa14345aa565c1f953ee3700cf476a8bc601cd7 | Python | py | |
import torch
from torch.autograd import Variable
import os, errno
def to_var(x,requires_grad=True):
if torch.cuda.is_available():
x = x.cuda()
return Variable(x,requires_grad=requires_grad)
def denorm(x):
out = (x+1)/2
return out.clamp(0,1)
def make_dir_if_not_exists(path):
"""Make dire... | utils.py | MIT | 533 | f9a94c849f1c516563ff9aae4e6096ed5912b6d1 | Python | py | |
import collections
from operator import itemgetter
import torch
import torch.nn as nn
import data_loader
LENGTH_PENALTY = .2
MIN_LENGTH = 5
class SingleBeamSearchSpace():
def __init__(self,
device,
prev_status=None, # list of tuple, (status_name, status, batch_dim)
... | kh-kim models/simple_nmt/search.py | Apache-2.0 | 7,319 | dfbb16a9277522317d0b65b343f4a64f43afdda7 | Python | py | |
from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.aut... | pointnet.py | MIT | 5,365 | 6522aad7c6150abbfbaf568d96c733647794834d | Python | py | |
import torch.nn as nn
import torch
class MLP(nn.Module):
def __init__(self, input_dim, hidden_dims=(128, 128),
activation='tanh', use_bias=True):
super().__init__()
if activation == 'tanh':
self.activation = torch.tanh
elif activation == 'relu':
... | models/mlp.py | MIT | 810 | 3aa1605e5ffb671cc8557c137810ea931c609a6f | Python | py | |
from __future__ import print_function, division
import os
import numpy as np
from PIL import Image
import glob
#import SimpleITK as sitk
from torch import optim
import torch.utils.data
import torch
import torch.nn.functional as F
import torch.nn
import torchvision
import matplotlib.pyplot as plt
import natsort
from to... | pytorch_run.py | MIT | 17,834 | 3aa16c8c7c1a881c35c8d0b2c45a6e658d83b255 | 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... | deepoffense/classification/classification_utils.py | Apache-2.0 | 32,405 | 3aa173680171d06a2b695556008a74f21fad4a92 | Python | py | |
import torch
import torch.optim as opt
from models.base_models import PUModelRandomBatch
from classifier import Net
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class PAN(PUModelRandomBatch):
def __init__(self, model=Net, clf=Net, lamda=1e-3):
"""
:param model: classifie... | models/reference/pan.py | MIT | 2,741 | 3aa1754ad5f5a76f5f17d0bb893a6bd136dfd2ee | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import DetectionHub._C as _C
import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
class _PSROIPool(Function):
@staticmethod
... | DetectionHub/layers/psroi_pool.py | MIT | 2,550 | 5f60f257affbba64ef7e4592ba5a564f3e6db88f | Python | py | |
# coding=utf-8
from __future__ import absolute_import, division, print_function
import logging
import argparse
import os
import random
import numpy as np
import pickle as pkl
from datetime import timedelta
import torch
import torch.distributed as dist
from tqdm import tqdm
from torch.utils.tensorboard import Summar... | visualize.py | MIT | 9,362 | 3aa19d8fdcb910d68453497044a5073f010ef421 | Python | py | |
from setuptools import setup
from torch.utils.cpp_extension import CppExtension, BuildExtension
import copy
import os
class MpiBuildExtension(BuildExtension):
def __init__(self, *args,**kwargs):
super(MpiBuildExtension,self).__init__(*args,use_ninja=False,**kwargs)
def build_extensions(self):
... | setup.py | MIT | 3,540 | 3aa1a33983de53ed37d5badda8b012d6e92cda31 | Python | py | |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import unittest
import pytest
import sys
import copy
from numpy.testing import assert_allclose, assert_array_equal
import onnx
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision imp... | onnxruntime/test/python/onnxruntime_test_ort_trainer.py | MIT | 24,805 | 5fce2e1374a832d8d1866877296067e864e6d3ca | Python | py | |
"""
Python 3.6
PyTorch 0.4
"""
import logging
import itertools
import random
import torch
import torch.nn.functional as F
import torch.optim as optim
import utils
from Models.AbstractModel import AbstractModel, Models
from Models.Beta_VAE import Beta_VAE
class AnaVAE(Beta_VAE):
# ================ init p... | Models/AnaVAE.py | MIT | 5,534 | 3aa1f0fc4afdf22f1bbb573533024a3dfc82ee86 | Python | py | |
import torch
import torch.nn as nn
from torch.nn import Parameter
import torch.nn.functional as F
from torch_scatter import scatter_add
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.utils import add_remaining_self_loops, softmax
from torch_geometric.nn.inits import glorot, zeros
from graphgym... | graphgym/contrib/layer/generalconv.py | MIT | 7,471 | 129c5a679955b63a361b394f17544275aa0f4538 | Python | py | |
#-*- coding: utf-8 -*-
"""
what : Single Encoder Model for text - bidirectional
data : IEMOCAP
"""
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_sequence, pad_packed_sequence
from model_attention_pytorch import luong_attention
from random import shuffle
import num... | model/model_text.py | MIT | 4,829 | 2499949550aa086bb83edeb8a3c76b6bc7b0dab1 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch.utils.data as Data
import torchvision
import matplotlib.pyplot as plt
import numpy as np
import gym
env = gym.make("CartPole-v0")
N_S = env.observation_space.shape[0]
N_A = env.action_space.n
GAMMA = 0.... | ac_discrete.py | MIT | 3,254 | 3aa250cbbcef65319a1e2834fb6e3897628a539f | Python | py | |
"""Prepare PASCAL Context dataset"""
import click
import shutil
import tarfile
import torch
from tqdm import tqdm
from pathlib import Path
from segm.utils.download import download
def download_pcontext(path, overwrite=False):
_AUG_DOWNLOAD_URLS = [
(
"https://www.dropbox.com/s/wtdibo9lb2fur7... | segm/scripts/prepare_pcontext.py | MIT | 3,147 | 3aa27bceea3426cf4b2a229b7523ceb155905016 | Python | py | |
import torchvision.transforms as transforms
from torchvision.datasets import ImageFolder
from torch.utils.data import DataLoader
import torch
import torch.nn as nn
from torch.autograd import Variable
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import numpy as np
import time
im... | Code/4_cnn_model_4.py | MIT | 10,427 | 3aa27d3d974e4fe538fa33f73a229bc2b49db803 | Python | py | |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.utils.data
from torch.autograd import Variable
import torch.nn.functional as F
import math
import numpy as np
def convbn(in_planes, out_planes, kernel_size, stride, pad, dilation):
return nn.Sequential(nn.Conv2d(in_planes, out_p... | lightmodels/bounded_stackhourglass/submodule.py | MIT | 5,623 | 3aa289340c6557b143b3a9fdcb8e811bf75de15e | Python | py | |
#/usr/bin/env python3
# Taken from here: https://github.com/huggingface/pytorch-pretrained-BigGAN
# MIT License
#
# Copyright (c) 2019 Thomas Wolf
#
# 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... | biggan.py | MIT | 24,364 | 3aa28e90c11ff9e51949d7206f20d57d8d1405bd | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/15 11:26
# @Author : xiezheng
# @Site :
# @File : regularizer.py
import numpy as np
import math
import torch
from torch import nn
from utils.util import get_conv_num, get_fc_name, concat_gpu_data
from quantization.google_quantization import q... | models/regularizer.py | BSD-3-Clause | 4,290 | 3aa29a496e3bd31d2074d0aa93cf9970046fef08 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.