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 |
|---|---|---|---|---|---|---|---|
#######################################################
#
# train_model.py
# Train and save models
############################################################
from learning_module import train, test, adjust_learning_rate, to_log_file, now, get_model
from learning_module import get_transform, plot_fig
import torch
im... | train_model.py | MIT | 8,411 | 12beb7009247d28eebe8bba12622264b034791cb | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class ResBlock(nn.Module):
def __init__(self, Dilation=1):
super(ResBlock, self).__init__()
self.conv1 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=Dilation, dilation=Dilation)
se... | models/DilatedUGANModel.py | MIT | 6,461 | 3a07a3f740c3e57825d2ad5554cb05b9277ebda2 | Python | py | |
#!/usr/bin/env python3.6
import warnings
import sys
sys.path.append("..")
from utils.utils_main import main_stem, get_parser, is_ood, process_continue_run, get_models, da_methods, ResultsContainer, ood_methods
from utils.preprocess import data_loader
from utils.utils import boolstr
from distr import edic
from arch imp... | code/deep/CSG/a-domainbed/visual.py | MIT | 17,190 | 3a07ada34ede2e72b24ae1e28608f61926f3faf8 | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiHeadAttention(nn.Module):
def __init__(self, heads, d_model, dropout=0.1):
super().__init__()
self.d_model = d_model
self.d_k = d_model // heads
self.h = heads
self.q_linear = nn.Line... | models/MultiHeadAttention.py | MIT | 1,939 | 3a07aeb901db4a26f365da65a568c0c6e83cd128 | Python | py | |
# Please run convert_longformer_to_onnx.py to get onnx model before running this script.
# Tested with python 3.7, onnxruntime-gpu 1.6.0 (or nightly), PyTorch 1.7.0, transformers 4.0, CUDA 10.2, CUDNN 8.0
# Example step by step command lines for benchmarking longformer base model (without/with optimizer) in Linux:
# ... | onnxruntime/python/tools/transformers/longformer/benchmark_longformer.py | MIT | 15,270 | a98d2330343d8ef81a3bf2af9677f55de1818b92 | Python | py | |
import cv2
import math
import numpy as np
import torch
import random
import string
from random import randrange
from config import system_configs
from utils import crop_image, normalize_, color_jittering_, lighting_
from .utils import random_crop, draw_gaussian, gaussian_radius
def _full_image_crop(image, detection... | sample/coco.py | MIT | 19,368 | a9899a5534e0d269315a38cbb108f66f3ad997bc | Python | py | |
from typing import List, Optional, Tuple, Union
import torch
from torch import nn, Tensor
def _cat(tensors: List[Tensor], dim: int = 0) -> Tensor:
"""
Efficient version of torch.cat that avoids a copy if there is only a single element in a list
"""
# TODO add back the assert
# assert isinstance(t... | torchvision/ops/_utils.py | BSD-3-Clause | 2,288 | 3a07c747f5850a35f31e1512a14e030d3e8ca8b8 | Python | py | |
import open3d as o3d
import sys
import os
code_dir = os.path.dirname(os.path.realpath(__file__))
from multiprocessing import cpu_count
import argparse
import torch
from torch import optim
from torch.utils import data
import numpy as np
import yaml
import glob
import random
from trainer_grasp import *
from Utils import ... | train_grasp.py | Apache-2.0,MIT | 1,041 | 3a07cf4d30e6177b0e088d26d3fb643955d7be2a | Python | py | |
import time
from torch.autograd import Variable
from util import AverageMeter
from rankingloss import *
def train(train_loader, train_loader1, train_loader2, train_loader3, args, model, criterion, optimizer,
epoch, num_epochs):
print(len(train_loader),len(train_loader1), len(train_loader2), l... | train.py | MIT | 6,989 | 3a07d2e815854ffb029b1d4c1fbe5fe04d646182 | Python | py | |
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
import torch
from torch.nn import functional as F
from torch import Tensor
import argparse
from typing import Tuple, Dict
from utils.tensor_utils import tensor_to_python_float
from utils import logger
from utils.dd... | loss_fn/detection_loss_fns/ssd_multibox_loss.py | AML | 6,580 | d7d89e6b7495b7ceb986b9f83077ae2f173940c3 | Python | py | |
import os.path as osp
from typing import Dict, List, Union
import torch
import torch.nn.functional as F
from torch import nn
import torch_geometric.transforms as T
from torch_geometric.datasets import IMDB
from torch_geometric.nn import HANConv
path = osp.join(osp.dirname(osp.realpath(__file__)), '../../data/IMDB')
... | examples/hetero/han_imdb.py | MIT | 2,723 | 3a07ed55944556a29d7b7e702040ad687143dbda | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import copy
import logging
from typing import Dict, List
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as ... | fairseq/models/bart/hub_interface.py | MIT | 7,302 | 03d766b1396b2208675676fdcef55bc0f1aa53d9 | Python | py | |
import torch
import torch.nn as nn
NUMBER_OF_ACTIONS = 5
class Dueling_DQN(nn.Module):
def __init__(self):
super(Dueling_DQN,self).__init__()
self.feature = nn.Sequential(
nn.Linear(20, 128),
nn.ReLU()
)
self.advantage = nn.Sequential(
nn.Linear(... | AI/RL_Model.py | MIT | 1,432 | 28ba6a4c7b28f595f95c647629bc1027fb9ea1e1 | Python | py | |
import sys
import os
from pathlib import Path
sys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))
from training_structures.unimodal import train, test
from fusions.common_fusions import Concat
from datasets.avmnist.get_data_robust import get_dataloader
from unimodals.common_models import LeNet,MLP,Constant,L... | deprecated_examples_robust/multimedia/avmnist_pretraining_robust.py | MIT | 1,048 | 1eb56482905ce191363a1a2e319cc407090d28cf | Python | py | |
import torch
import torch.nn as nn
class MLP_score(nn.Module):
def __init__(self, in_channel, out_channel):
super(MLP_score, self).__init__()
self.activation_1 = nn.ReLU()
self.layer1 = nn.Linear(in_channel, 256)
self.layer2 = nn.Linear(256, 64)
self.layer3 = nn.Linear(64, ... | models/MLP.py | MIT | 509 | f92f712ac19994367b6c5273c3d9ae1128c90395 | Python | py | |
import torch
import torch.nn as nn
class NegativeSampling(nn.Module):
"""Negative sampling loss as proposed by T. Mikolov et al. in Distributed
Representations of Words and Phrases and their Compositionality.
"""
def __init__(self):
super(NegativeSampling, self).__init__()
self._log_si... | paragraphvec/loss.py | MIT | 974 | ff1dfce94d5fb1007d8f5cbd7794c619ceb035f5 | Python | py | |
# Copyright 2020 Dakewe Biotech 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... | wgandiv_pytorch/utils.py | Apache-2.0 | 7,232 | 3a08458d68fb3d0488e5e0dafa02ad7a74d1f7c0 | Python | py | |
import copy
import functools
import os
import blobfile as bf
import numpy as np
import torch as th
import torch.distributed as dist
from torch.nn.parallel.distributed import DistributedDataParallel as DDP
from torch.optim import AdamW
from . import dist_util, logger
from .fp16_util import (
make_master_params,
... | improved_diffusion/train_util.py | MIT | 12,793 | 3a084ec55a811ea98ca6d5d1f805c2bdebe8e6b2 | Python | py | |
"""
A :class:`~allennlp.training.trainer.Trainer` is responsible for training a
:class:`~allennlp.models.model.Model`.
Typically you might create a configuration file specifying the model and
training parameters and then use :mod:`~allennlp.commands.train`
rather than instantiating a ``Trainer`` yourself.
"""
# pylint... | allennlp/training/trainer.py | Apache-2.0 | 52,006 | 3a084f5a93b281b1068fe8400cc9ab0f519a0b28 | Python | py | |
import gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
from common.layers import NoisyLinear
from common.replay_buffer import ReplayBuffer
#from torch.utils.tensorboard import SummaryWriter
from unityagents impor... | Chapter11/Chapter_11/Chapter_11_Unity_Rainbow.py | MIT | 7,065 | 5f3f3ca69e53656aa6d01a0accd0a00ff71dfec8 | Python | py | |
# This file is to demo the usage of multi-trial NAS in the usage of SPOS search space.
import click
import nni.retiarii.evaluator.pytorch as pl
import nni.retiarii.nn.pytorch as nn
import nni.retiarii.strategy as strategy
import torch
from nni.retiarii import serialize
from nni.retiarii.nn.pytorch import LayerChoice
f... | examples/nas/oneshot/spos/multi_trial.py | MIT | 7,240 | 5fa6af43d354024532dc9de33d6f511d8cd0497e | Python | py | |
import torch.nn as nn
import torchvision.models as models
import torchvision.transforms as transforms
__all__ = ['resnet50_1c']
def resnet50_1c(**kwargs):
model = models.resnet50(**kwargs)
model.conv1 = nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
model.preprocess = tran... | nn_analysis/models/archs/bw_resnets.py | MIT | 432 | 423714a72dbd4a9f80c199d6b488a68256157105 | Python | py | |
import logging
import sys
import os
import torch.distributed as dist
log_levels = {
"debug": logging.DEBUG,
"info": logging.INFO,
"warning": logging.WARNING,
"error": logging.ERROR,
"critical": logging.CRITICAL,
}
class LoggerFactory:
@staticmethod
def create_logger(name=None, level=logg... | deepspeed/utils/logging.py | MIT | 3,389 | 3a089b3dd1b8b37fc256d81b895de4cd11b3f0cd | Python | py | |
from __future__ import print_function
import torch.optim as optim
import torch.backends.cudnn as cudnn
from torch.autograd import grad
import torchvision
import torchvision.transforms as transforms
import os
import json
import argparse
from tqdm import tqdm
from torch.utils.tensorboard import SummaryWriter
from models ... | noisy_student.py | MIT | 18,714 | f93503ab4d7ee04d93ead9db94c7e4fc154676e8 | Python | py | |
import torch.nn as nn
import torch
import torch.nn as nn
import torch.nn.functional as F
from .common import *
class ListModule(nn.Module):
def __init__(self, *args):
super(ListModule, self).__init__()
idx = 0
for module in args:
self.add_module(str(idx), module)
id... | senior/RetinexDIP/net/unet.py | MIT | 7,318 | 3a08e19f33485fa7f0390eccd3976cdcbd6557f0 | Python | py | |
# Tencent is pleased to support the open source community by making ncnn available.
#
# Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the... | tools/pnnx/tests/ncnn/test_nn_SELU.py | BSD-3-Clause | 1,733 | 3a08ee31ee5b3744f258957c18fd7691e5292a85 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import cv2
import torch
import time
from torchvision import transforms as T
from torchvision.transforms import functional as F
from maskrcnn_benchmark.modeling.detector import build_detection_model
from maskrcnn_benchmark.utils.checkpoint import De... | demo/predictor.py | MIT | 17,459 | dfa3fc513224e1d03cb67c78e371d20438087e78 | Python | py | |
import torch
import torch.nn as nn
from torchvision import models
from NeuralModels import SILU, Perceptron
from DeepImagePrediction import DIMENSION, CHANNELS
LATENT = 512
REDUCTION = 7
FEATURES = 64
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes,... | ResidualPredictor.py | Apache-2.0 | 8,341 | 3a0917f01fd5a31bdb5ed398db09dc32848379d4 | Python | py | |
import random
import time
import ray
import torch
import numpy as np
import models
from self_play import MCTS
@ray.remote(num_cpus=1)
class ReanalyzeQueueWorker:
def __init__(self, initial_weights, shared_storage, replay_buffer, config, queue):
self.shared_storage = shared_storage
self.replay_buf... | reanalyze.py | MIT | 8,081 | 4b615804b53c23fa6468bdf48d3dd2b1f16f1bf9 | 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
from .submodule import *
class hourglass(nn.Module):
def __init__(self, inplanes):
super(hourglass, self).__init__()
self... | lightmodels/uniform_compression/stackhourglass.py | MIT | 7,730 | dfd640a52288919bbb57efa259c79ac5b9ad8ed8 | Python | py | |
# -*- coding: utf-8 -*-
"""
PyTorch: 제어 흐름(Control Flow) + 가중치 공유(Weight Sharing)
---------------------------------------------------------------
PyTorch 동적 그래프의 성능을 보여주기 위해, 매우 이상한 모델을 구현해보겠습니다:
각각의 순전파 단계에서 많은 은닉 계층을 갖는 완전히 연결(Fully-connected)된 ReLU
신경망이 무작위로 1 ~ 4 사이의 숫자를 선택하고, 동일한 가중치를 여러 번 재사용하여
가장 안쪽(Innermost)에... | docs/_downloads/f8a836ab228b9bf5606c9283dbda878f/dynamic_net.py | BSD-3-Clause | 2,213 | 1e7d1353c3cfbe4d4f773bbfcc5db500470ece2b | Python | py | |
import torch
from bgflow.nn.flow.transformer.gaussian import TruncatedGaussianTransformer
from bgflow.distribution.normal import TruncatedNormalDistribution
def test_constrained_affine_transformer(ctx):
tol = 5e-4 if ctx["dtype"] == torch.float32 else 5e-7
mu_net = torch.nn.Linear(3, 2, bias=False)
sigma... | tests/nn/flow/transformer/test_gaussian.py | MIT | 1,945 | 3a094072ddd036485571223769305263fb81d357 | Python | py | |
import time
import torch
import subprocess
import os
from model import EAST
from detect import detect_dataset
import numpy as np
import shutil
def eval_model(model_name, test_img_path, submit_path, save_flag=True):
if os.path.exists(submit_path):
shutil.rmtree(submit_path)
os.mkdir(submit_path)
device = torch.... | eval.py | MIT | 1,133 | 5f1fd9371e645887bea85ce1955824ed401f9eea | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
# NOTE: This is a mirror of the code in
# https://github.com/facebookresearch/fairscale/tree/master/fairscale/nn/moe
imp... | fairseq/fairseq/modules/moe/moe_layer.py | Apache-2.0 | 11,866 | fcf4f68d125d3610f2d593fc0885d70c64450b5f | Python | py | |
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, in_planes, planes, stride=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
... | src/stage2/cascade_pyramid_network_v14.py | Apache-2.0 | 5,952 | 3a098dce313dba3029481d006e4f9be77d32ddc2 | Python | py | |
import pytest
import numpy as np
import torch
from pugh_torch.utils.tensorboard import SummaryWriter
@pytest.fixture
def mock_add_image(mocker):
return mocker.patch.object(SummaryWriter, "add_image")
@pytest.fixture
def mock_add_text_under_img(mocker):
return mocker.patch(
"pugh_torch.utils.tensorbo... | pugh_torch/tests/utils/test_tensorboard.py | MIT | 5,509 | 10a0bd713b374d9d37790c754d45a7d1d8c51ac5 | Python | py | |
import torch.nn as nn
from mmcv.cnn import ConvModule, bias_init_with_prob, normal_init
from ..builder import HEADS
from .anchor_head import AnchorHead
@HEADS.register_module()
class RetinaSepBNHead(AnchorHead):
""""RetinaHead with separate BN.
In RetinaHead, conv/norm layers are shared across di... | mmdet/models/dense_heads/retina_sepbn_head.py | Apache-2.0 | 4,401 | 3a09c3640eb37b7a8b7fea093eac773fdb827db2 | Python | py | |
import argparse
import numpy as np
import os
from sys import exit
import shutil
import torch
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
import warnings
# from lib.dataset import MegaDepthDataset
# from lib.dataset2 ... | train2.py | BSD-3-Clause-Clear | 8,438 | 3a09d3061e8125c4d7923eeac52250a54120e5eb | Python | py | |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import logging
from typing import Dict
import torch
from iopath.common.file_io import g_pathmgr
from torch import nn
logger: loggin... | torchrecipes/vision/core/utils/model_weights.py | BSD-3-Clause | 2,255 | 3a09ef7ca91a2be6435a07768ddeb2b9f48aad3b | Python | py | |
import torch
import torch.nn as nn
from torch.autograd import Variable
class MyLinearLayer(nn.Module):
def __init__(self, h_in, w_in, size_channel):
super().__init__()
self.h_in, self.w_in, self.size_channel = h_in, w_in, size_channel
weight = torch.Tensor(h_in * w_in, size_channel)
... | cifar/my_fc.py | MIT | 1,067 | 3a09f0ee3498320f99e56ee202c341e92ab33a4d | Python | py | |
# Copyright (c) Runpei Dong, ArChip Lab.
# This source code is licensed under the Apache 2.0 license found in the
# LICENSE file in the root directory of this source tree.
import torch
import argparse
import time
import os
import sys
import math
import torch.nn as nn
import config as cfg
from tqdm import tqdm
from ... | main.py | Apache-2.0 | 15,715 | ff6f58f26b18d1504500747ee470f544425ecf53 | Python | py | |
import types
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def get_mask(in_features, out_features, in_flow_features, mask_type=None):
"""
mask_type: input | None | output
See Figure 1 for a better illustration:
https://arxiv.org/pdf/1502.03509.pdf
"""
... | flows.py | MIT | 11,532 | 4b9b71400d8ae1ba1f11d5e3df1631140fe34509 | Python | py | |
from pathlib import Path
from typing import Union
import h5py
from pydantic import BaseModel, Field
from torch.utils.data import DataLoader, Dataset as TorchDataset
from datasets.something_something import (
SomethingSomethingV2Dataset,
SomethingSomethingV2FeaturesDataset,
)
from .base import ClassConfig
from... | src/config/data.py | Apache-2.0 | 1,903 | 3a0a42b4f368e60f8592bc317d661add02d803b3 | Python | py | |
import os.path as osp
import pandas as pd
import shutil
import torch
import numpy as np
from torch_geometric.data import Data, Dataset
from sklearn.metrics.pairwise import euclidean_distances
from scipy import sparse
from utils_dataset import graph_from_series, graph_from_series_inverted, graph_from_series_ABIDE
def... | dataset.py | MIT | 19,897 | 1ea1b1b0fbfa811e1b18b84c6298d084a47a2737 | Python | py | |
# MIT License
#
# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021
#
# 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
# r... | tests/preprocessing/expectation_over_transformation/natural_corruptions/test_contrast.py | MIT | 5,922 | 3a0a7ba1d6f631efb69f747486cfdbd8ea0d220e | Python | py | |
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
import torch
from model.utils.config import cfg
if torch.cuda.is_availab... | model/nms/nms_wrapper.py | MIT | 854 | 4b76aadebb7292fff5613ecbbd92712a713620f2 | Python | py | |
import time
from collections import defaultdict
from torch import optim
from torch.utils.data import DataLoader, Dataset
from autocorrection.dataloader import *
from autocorrection.model.model import *
from autocorrection.utils import *
from sklearn.metrics import classification_report
class ModelTrainer:
def __... | autocorrection/model/trainer.py | MIT | 13,065 | 5f7b46187183532468ddbe458317234ab38494a1 | Python | py | |
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# MIT License
#
# 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 u... | nni/algorithms/feature_engineering/gradient_selector/learnability.py | MIT | 19,347 | 3a0ab4b39e7bef15101c793f3ec522395c05cd94 | Python | py | |
# Copyright (C) 2020-2021, François-Guillaume Fernandez.
# This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
import torch
from torch import nn
from torch import Tensor
from typing import Optional, Tuple, Any,... | torchcam/cams/gradcam.py | Apache-2.0 | 15,336 | 3a0abba0ace7e56bf5dd8dcce6c6507ecd63238b | Python | py | |
import numpy as np
import torch
import math
from deep_privacy.data_tools import data_utils
def image_to_numpy(images, to_uint8=False, denormalize=False):
single_image = False
if len(images.shape) == 3:
single_image = True
images = images[None]
if denormalize:
images = data_utils.de... | deep_privacy/torch_utils.py | MIT | 2,391 | dfe0aad911875f968ef8d586639e95678478a7ea | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch.utils.data as data
import pycocotools.coco as coco
import numpy as np
import torch
import json
import cv2
import os
import math
import torch.utils.data as data
class KITTI(data.Dataset):
num_c... | src/lib/datasets/dataset/kitti.py | MIT | 3,060 | a98b44e4e542d19a28d94a424e4afbb762bc2b4f | Python | py | |
# This module is adapted from https://github.com/pytorch/examples/blob/master/imagenet/main.py
import init_paths
import argparse
import os
import time
import sys
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim
import torchvision
import torchvision.transforms as transforms
impo... | main_free.py | MIT | 10,423 | 45731c77543e513d8ef2c437f82d06c16f695a31 | Python | py | |
import numpy as np
import random
import copy
from collections import namedtuple, deque
from model import Actor, Critic
import torch
import torch.nn.functional as F
import torch.optim as optim
BUFFER_SIZE = int(1e6) # replay buffer size
BATCH_SIZE = 128 # minibatch size
GAMMA = 0.95 # discount fact... | agent.py | MIT | 7,989 | 34552dbea81c5cd8c6b97efa25040296eaf87719 | Python | py | |
# coding=utf-8
# Copyright 2019 HuggingFace Inc.
#
# 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 ag... | tests/test_modeling_common.py | Apache-2.0 | 44,314 | fde8b34bf48e07c8eb9649765d810c1a0a87d73d | Python | py | |
import os
import shutil
import time
import csv
import numpy as np
import pandas as pd
import sklearn
import torch
from sklearn.model_selection import train_test_split
from deepoffense.classification import ClassificationModel
from deepoffense.language_modeling.language_modeling_model import LanguageModelingModel
from ... | examples/english/english_deepoffense.py | Apache-2.0 | 3,860 | 3a0affd49e23b78062f4f2b7e942b51a618f4b26 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def hidden_init(layer):
in_size = layer.weight.data.size()[0]
lim = 1./np.sqrt(in_size)
return (-lim, lim)
class Actor(nn.Module):
def __init__(self, state_size, action_size, seed=0, fc1_size=128, fc2_size=128):... | model.py | MIT | 2,173 | 3a0b0de39a757d39880890fe40cb88733268f5d8 | Python | py | |
import argparse
import os
import os.path as osp
import pprint
import warnings
from torch.utils import data
from advent.model.deeplabv2 import get_deeplab_v2
from advent.dataset.cityscapes import CityscapesDataSet
from advent.dataset.mapillary import MapillaryDataSet
from advent.domain_adaptation.config import cfg, cf... | advent/scripts/esl.py | Apache-2.0 | 3,011 | 3a0b254611a79b857c46180d95d3a7c8dc5abb6f | Python | py | |
"""
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import sys
sys.path.append("..")
import os
import time
import json
import logging
import argparse
import numpy as np
import torch
import tor... | code/dmcnet_I3D/test/evaluate_video_hmdb_i3d.py | MIT | 11,306 | 3a0b4ba7a38854352cd7cb109d34c1b6b475350f | Python | py | |
"""
This file defines the actual torch model that we use for image compression and indexing
@Jaeho Bang
"""
import torch
import torch.nn as nn
class UNet_compressed(nn.Module):
def __init__(self, middle_neural_count):
super(UNet_compressed, self).__init__()
self.K = 10
self.output_ch... | eva_storage/models/UNet_compressed.py | Apache-2.0 | 3,283 | d7210f8ef98df449f03710779f18fa39f4ba4121 | Python | py | |
import argparse
import glob
import logging
import os
import pickle
import random
import re
import shutil
from os.path import join
import json
from cytoolz import curry
from utils.reward import *
from utils.statistics import RewardStatistics, LagrangianStatistics
import time
from utils.time_log import time_since
#from u... | gpt2_summarization_rl_finetuning.py | MIT | 72,964 | f9f298b554e1e94e9c9d73c9b2bca6f425a1e849 | Python | py | |
from __future__ import division
import os
import torch
import torchvision.transforms as transforms
from torch.utils.data.dataset import Dataset
from PIL import Image, ImageDraw
import numpy as np
import json
from .registry import DATASETS
@DATASETS.register_module
class CPVTONDataset(Dataset):
CLASSES = None
... | build/lib/mmfashion/datasets/CP_VTON.py | Apache-2.0 | 5,238 | 459f71f669e02b1f7a9fb61c2768870e2eca5132 | Python | py | |
import torch
import argparse
import os
import json
import logging
from allennlp.models import BidirectionalAttentionFlow
from allennlp.common.checks import ConfigurationError
from allennlp.common.params import Params
from allennlp.models.model import Model
from allennlp.predictors import Predictor
from allennlp.data im... | allennlp/nlp_meta_task/extract_inter_base_model_dataset.py | Apache-2.0 | 11,251 | e94d6a98ee46ee9149a86e98ef5db775923de018 | Python | py | |
import torch
import torch.nn as nn
class BaseSolver(object):
def __init__(self, opt):
self.opt = opt
self.is_train = opt['is_train']
# GPU verify
self.use_gpu = torch.cuda.is_available()
self.Tensor = torch.cuda.FloatTensor if self.use_gpu else torch.FloatTensor
# ... | DNCNN/solvers/base_solver.py | Apache-2.0 | 2,159 | f958ef309bf23db1b880a602a2ba19f7a2285ee5 | Python | py | |
# -*- coding: utf-8 -*-
"""Miniproject 4
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1r2fl_-CoKWA_vUzbxDAuYly9oXduDR0B
"""
import numpy as np
from string import punctuation
import torch
from sklearn.model_selection import train_test_split
import to... | Projects/Project4/code.py | MIT | 7,924 | 426fef1fd60bea160f3226246decf706eb780728 | Python | py | |
import torch
from torch_geometric.transforms import ToUndirected
from torch_geometric.data import Data, HeteroData
def test_to_undirected():
assert ToUndirected().__repr__() == 'ToUndirected()'
edge_index = torch.tensor([[2, 0, 2], [3, 1, 0]])
edge_weight = torch.randn(edge_index.size(1))
edge_attr =... | test/transforms/test_to_undirected.py | MIT | 2,562 | 247a85bc275aa4173cf6397f765bcc4418442a90 | Python | py | |
import torch, tqdm, numpy, os
import src
from . import datasets, get_type
class Dataset:
def __init__(self, X, Y, folds):
self.X = X
self.Y = Y
self.k = folds
def create_train_valid_iterator(self):
return self.split_train_valid(self.X, self.Y, self.k)
def split_train_va... | src/src/toy/GlobalOptim.py | MIT | 9,995 | 3a0bfaa2fba330b498ff3dddaa4d8d346dea6940 | Python | py | |
"""Combine pred_sscore_v2.py and gt_cluster_score.py
"""
import os
import sys
import numpy as np
import torch
import random
import tqdm
import time
import logging
from easydict import EasyDict
from pathlib import Path
from os.path import join
sys.path.append(join(os.path.dirname(os.path.abspath(__file__)), "../"))
from... | eval/output_ds.py | MIT | 10,726 | 3a0c145c67c0fa664be5dc2bd81ea0242c83b63c | Python | py | |
from types import MethodType
import cv2
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from scipy.misc import imresize
from ..functions import pr_conv2d, peak_stimulation
class PeakResponseMapping(nn.Sequential):
def __init__(self, *args, **kargs):
super(PeakRespo... | prm/modules/peak_response_mapping.py | MIT | 11,763 | 651f404e14d793072072cd02a3c4f6bb75307839 | Python | py | |
import gym
import numpy as np
import railrl.misc.hyperparameter as hyp
import railrl.torch.pytorch_util as ptu
from railrl.data_management.obs_dict_replay_buffer import ObsDictReplayBuffer
from railrl.launchers.launcher_util import run_experiment
from railrl.samplers.data_collector.path_collector import ObsDictPathCol... | experiments/brandon/end2end_sac/sawyer_reach_xy_baseline.py | MIT | 8,340 | 3a0c2f881fe2f8cbbc33e632beb108e7efcc47ee | Python | py | |
import pytorch_lightning as pl
import numpy as np
import torch
import random
from contextlib import contextmanager
class LightningMelGAN(pl.LightningModule):
def __init__(self, vocoder):
super().__init__()
self.mel2wav = vocoder.mel2wav
def inverse(self, mel):
with torch.no_grad():
... | lightning/utils.py | MIT | 1,667 | 7c205d87ff079d9266e3dedd50d500242ed49a15 | Python | py | |
"""PyTorch-compatible Data Augmentation."""
import sys
import cv2
import torch
import numpy as np
from importlib import import_module
cv2.setNumThreads(1)
def to_normalized_tensor(config, ts, mode, image, mask=None):
assert mode == "train" or mode == "predict"
assert len(ts) == 2
assert image is not None... | robosat_pink/da/core.py | MIT | 1,847 | 4b16da618f3b44d2bc6159d67aeb56cc301531cb | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..ops import emulate_int
class IntLinear(nn.Module):
"""
Qu... | fairseq/modules/quantization/scalar/modules/qlinear.py | MIT | 3,960 | a961a5aa0c0cb98c782c9080be55e299c48f32e4 | Python | py | |
"""
This file contains specific functions for computing losses of FCOS
file
"""
import torch
from torch import nn
import os
from ....layers import IOULoss
from ....layers import SigmoidFocalLoss
INF = 100000000
def get_num_gpus():
return int(os.environ["WORLD_SIZE"]) if "WORLD_SIZE" in os.environ... | fcos/core/modeling/rpn/fcos/loss.py | BSD-3-Clause | 11,847 | 1ecfedfd67f35acba94fbe11f0cd55a8d6271f9c | Python | py | |
# -*- coding: utf-8 -*-
""" Code for training and evaluating Self-Explaining Neural Networks.
Copyright (C) 2018 David Alvarez-Melis <dalvmel@mit.edu>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, ... | SENN/SENN/trainers.py | MIT | 41,109 | 3a0c5600604491e5e0d42e757779a48995249c61 | Python | py | |
"""
written by ryanreadbooks
date: 2021/11/3
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class DoubleConv(nn.Module):
"""Two conv. layers with batch norm."""
def __init__(self, in_channels, out_channels):
"""Initialize_layers."""
super().__init__()
self.dou... | models/unet/unet_backend.py | BSD-3-Clause | 2,811 | 12eafcc8743a490a1faf5c5035fda0c7c2b89e6e | Python | py | |
import cv2
import numpy as np
from build_utils import utils
import torch
from build_utils import img_utils
from matplotlib import pyplot as plt
from PIL import Image
from misc_functions import *
class GradCAM(object):
"""
1: the network does not update gradient, input requires the update
2: u... | grad_CAM.py | MIT | 7,667 | 45c8dcdda3819e0e0e91a28edeb7dc59e761531d | Python | py | |
import json
import os
from torch.utils.data import Dataset
from tools.dataset_tool import dfs_search
from tools.ft_tools import get_ft_id
class JsonFromFilesDataset(Dataset):
def __init__(self, config, mode, encoding="utf8", *args, **params):
self.config = config
self.mode = mode
self.fil... | dataset/nlp/JsonFromFiles.py | MIT | 1,764 | 3a0c66b40a8935f0453297ac49289a69f4d48055 | Python | py | |
from datetime import datetime
from torch import optim, nn
import torch
import numpy as np
import os
import yaml
import csv
import logging
import pickle
from vocabulary import Vocabulary
from data import get_data, pad_data, get_df
from batched_iterator import BatchedIterator
from models.encoder import Encoder
from mode... | sigmorphon-2021/experiment.py | MIT | 8,060 | 3a0c68cb665b527c0581503294e877d4128b5d43 | Python | py | |
from pathlib import Path
from torch.utils.data import DataLoader
from fairseq.data.dictionary import Dictionary
from fairseq.data.data_utils import collate_tokens
from torchtext.data import BucketIterator
from torchtext import data
from torchtext import datasets
def build_data_iterator(args,path,dataset=... | hoogberta/trainer/utils/dataloader.py | MIT | 3,477 | 3a0c75417c760b8cf52be7de3a1d74585dcc7150 | Python | py | |
import math
from copy import deepcopy
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn.modules.module import Module
from torch.nn.parameter import Parameter
from tqdm import tqdm as tqdm
from utils import utils
class GraphConvolution(Module):
"""
S... | utils/gcn.py | MIT | 8,372 | fdb51e410e0507dfce2a68784df66e97c62867b2 | Python | py | |
"""
Backbone modules.
"""
from collections import OrderedDict
import torch
import torch.nn.functional as F
import torchvision
from torch import nn
from torchvision.models._utils import IntermediateLayerGetter
from typing import Dict, List
from util.misc import NestedTensor, is_main_process
from .position_encoding im... | models/backbone.py | MIT | 5,326 | 8018a88e8afe15cc4c062c930b67aa183df4a52d | Python | py | |
import torch
from torchvision import datasets, transforms, models
class Transform(object):
"""Transform class.
"""
def __init__(self):
"""Initialize Transform
"""
self.__train_transform = transforms.Compose([
transforms.RandomRotation(40),
transforms.RandomR... | my/data_set.py | MIT | 2,814 | 7c51d6a006906820f543fafcc198ad5eebb5f431 | Python | py | |
import math
import torch
from torch.optim.optimizer import Optimizer
from .types import Betas2, OptFloat, OptLossClosure, Params
__all__ = ('RAdam',)
class RAdam(Optimizer):
r"""Implements RAdam optimization algorithm.
It has been proposed in `On the Variance of the Adaptive Learning
Rate and Beyond`_... | torch_optimizer/radam.py | Apache-2.0 | 6,395 | 10b2c03d1157866aa770117cb648e5db703a760e | Python | py | |
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from collections import OrderedDict
from torch import Tensor
from torch.jit.annotations import List
from moex_resnet import moex
__all__ = ['MoExDenseNet', 'moex_densenet121', 'moex_densenet169', 'moex_den... | ImageNet/moex_densenet.py | BSD-3-Clause | 13,198 | 3a0cc7ac316a410f3f4bb1ba15ad7838ab2e81fe | Python | py | |
import os
import time
import datetime
import numpy as np
from matplotlib import pyplot as plt
from collections import namedtuple
from progress.bar import Bar
from apex import amp
from PIL import Image
from tensorboardX import SummaryWriter
import utils.metrics as metrics
from utils.args import Args
from utils.utils i... | train.py | MIT | 9,542 | 3a0ce8bf5b0a8fdaef9524afd3e3dcbef2412f7c | Python | py | |
"""
Large-scale Point Cloud Semantic Segmentation with Superpoint Graphs
http://arxiv.org/abs/1711.09869
2017 Loic Landrieu, Martin Simonovsky
"""
from __future__ import division
from __future__ import print_function
from builtins import range
import torch
import torch.nn as nn
import torch.nn.f... | learning/modules.py | MIT | 8,153 | ff78b54df27a2da48b641067a8d5d8ab54f0008d | Python | py | |
import numpy as np
import torch
import gathering as cuda_gather
# promote input in batch
def promote_input(x, n_dim, device=None):
x_dim, x_shape = x.ndim, x.shape
dims = (1,) * (n_dim - x_dim)
x = x.view(dims+x_shape)
if device is not None:
x = x.to(device)
return x
def promote_input_n... | vgtk/utils.py | MIT | 2,855 | b27ef24841410f638a034a982f18da5813506788 | Python | py | |
# original code from https://github.com/SwinTransformer/Video-Swin-Transformer
# modified by Zilliz.
import torch
import os
try:
import torchvision
except ModuleNotFoundError:
os.system("pip install torchvision")
import torchvision
try:
import transformers
except ModuleNotFoundError:
os.system("pip ... | towhee/models/violet/violet.py | Apache-2.0 | 3,825 | 5ecdfa0e2f16eea917d021da214c46cc40b4fcdc | Python | py | |
import logging
from typing import Type, List, Union, Tuple, Optional
import torch
import numpy as np
from pathlib import Path
from farm.infer import Inferencer
from haystack.database.base import Document, BaseDocumentStore
from haystack.database.elasticsearch import ElasticsearchDocumentStore
from haystack.retriever.... | haystack/retriever/dense.py | Apache-2.0 | 15,162 | 3a0d0a4f32266eca06fbdf49d901bbd3a002eac2 | Python | py | |
from typing import Sequence
from itertools import chain
import torch
import torch.nn as nn
from torchvision import models
from criteria.lpips.utils import normalize_activation
def get_network(net_type: str):
if net_type == 'alex':
return AlexNet()
elif net_type == 'squeeze':
return SqueezeN... | criteria/lpips/networks.py | Apache-2.0,BSD-2-Clause,MIT | 2,667 | 3a0d13ad2d560278f16586da68d3a5eadb26e746 | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
import torch
import numpy as np
from tqdm import tqdm, trange
import copy
import math
import pdb
import sys
from models.model_utils.encoder_layer import EncoderLayer
from models.model_utils.scaled_dot_product_attention import ScaledDotProductAttention
from models.m... | models/hypersagnn.py | Apache-2.0 | 6,111 | 24d4e985dd49a8f3682f76a07154d6a3d4a22369 | Python | py | |
import os
import gym
import numpy as np
import torch
from baselines import bench
from baselines.common.atari_wrappers import make_atari, wrap_deepmind
from baselines.common.vec_env import VecEnvWrapper
from baselines.common.vec_env.dummy_vec_env import DummyVecEnv
from baselines.common.vec_env.shmem_vec_env import Shm... | a2c_ppo_acktr/envs.py | MIT | 7,757 | d7b569fcf273f3b779c1283436369b2ebb8c97d0 | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CS224N 2019-20: Homework 4
sanity_check.py: sanity checks for assignment 4
Sahil Chopra <schopra8@stanford.edu>
Michael Hahn <>
Vera Lin <veralin@stanford.edu>
If you are a student, please don't run overwrite_output_for_sanity_check as it will overwrite the correct o... | notebooks/a4/sanity_check.py | Apache-2.0 | 12,047 | 103632e7cc5577987e7adaa92e2f785409612ec6 | Python | py | |
import torch
from torch import nn
import dgl.function as fn
import torch.nn.functional as F
from copy import deepcopy
class Decoder(nn.Module):
def __init__(self, args, nfeat_dim):
super().__init__()
self.args = args
dropout = args.dropout
if 'LP' in args.tasks:
self.lin... | model/decoder.py | MIT | 5,459 | fdeabec8a3e1a2fbca2b3e76d969674200a3cb41 | Python | py | |
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Union
import copy
import os
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
from torch.nn.parallel import DistributedDataParallel
from catalyst.core.engine import IEngine
from catalyst.typing import (
D... | catalyst/engines/torch.py | Apache-2.0 | 17,804 | 425df64f2fb45964079a126b8ee147e181094812 | Python | py | |
#!/usr/bin/env python3
# encoding: utf-8
import torch as th
import torch.nn.functional as F
from rls.algorithms.multi.vdn import VDN
from rls.common.decorator import iton
from rls.nn.mixers import Mixer_REGISTER
from rls.nn.modules.wrappers import TargetTwin
from rls.utils.torch_utils import n_step_return
class QPL... | rls/algorithms/multi/qplex.py | Apache-2.0 | 4,830 | 03ff788f09f82665855a40805dbdc809236569ea | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
from torchvision import models
import net.resnet_atrous as atrousnet
import net.xception as xception
def build_backbone(backbone_name, pretrained=True, os=16):
if backbone_name == 'res50_atrous':
net = a... | net/backbone.py | Apache-2.0 | 865 | e9cdcf4bf25d743f6508635de6138d522d1cc2e3 | Python | py | |
import argparse
from torch.optim import AdamW
from torch.utils.data import DataLoader
import logging
from transformers import (
AutoConfig,
AutoModelForTokenClassification,
AutoTokenizer,
set_seed,
)
from ner.utils import (
NerDataset, Split, PadSequence
)
from ner.train_utils import learning_lo... | train_ner.py | MIT | 3,935 | 3a0d4984bf41a57423685fdf0bdcabc013791a7a | 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/models/layers/test_layer_utils.py | MIT | 3,020 | 52c82ad7a6bc9c3d23fed7e858199b1a96fde42e | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import json
from pathlib import Path
import torch
import egg.core as core
from egg.zoo.emcom_as_ssl.data import get_dataloader
from egg.zoo.e... | egg/zoo/emcom_as_ssl/train.py | MIT | 4,603 | 425e4562f4c6a507cf54ba18a0f21bb2c6efe6aa | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.