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 torch
import numpy as np
def convert_rgb_to_y(img):
if type(img) == np.ndarray:
return 16. + (64.738 * img[:, :, 0] + 129.057 * img[:, :, 1] + 25.064 * img[:, :, 2]) / 256.
elif type(img) == torch.Tensor:
if len(img.shape) == 4:
img = img.squeeze(0)
return 16. + (64.... | label_scale_bar_detector/OCR/SRCNN-pytorch/utils.py | MIT | 2,732 | 3a4540a91b4ff756ad8a6d64d89b00e6f75a4dec | Python | py | |
#!/usr/bin/env python3
# This file is covered by the LICENSE file in the root of this project.
import numpy as np
from scipy import signal
import torch
import torch.nn as nn
import torch.nn.functional as F
import __init__ as booger
class LocallyConnectedXYZLayer(nn.Module):
def __init__(self, h, w, sigma, nclasses... | mos_RangeNet/tasks/semantic/postproc/CRF.py | MIT | 4,949 | 24f52d1f625ad4795887c0333d3eb9f306c5315e | Python | py | |
import argparse
import os
import socket
import time
import uuid
from multiprocessing import Queue, Process, Event
from threading import Thread, Semaphore
import torchvision.transforms as transforms
from PIL import Image
from base58 import b58encode
from flask import Flask, request, abort, send_file
from fl... | manager/main.py | MIT | 10,428 | f9631e05f2dc98e7a900b458671c17bd679d8157 | Python | py | |
import torch
import torch.nn.functional as F
from torch import nn
from torch.autograd import Variable, Function
import numpy as np
from . import rerank
import time
from sklearn.cluster import DBSCAN
import random, math
from scipy.spatial.distance import cdist
from .rerank import re_ranking
from .util import cluster
fr... | JVTC/utils/losses_msmt.py | Apache-2.0 | 9,479 | dff0293b042c4a1c4e4704c86d9ebfb6af32b731 | Python | py | |
# take from https://github.com/openai/CLIP/blob/main/clip/simple_tokenizer.py
# to give users a quick easy start to training DALL-E without doing BPE
import torch
import youtokentome as yttm
from tokenizers import Tokenizer
from tokenizers.processors import ByteLevel
from transformers import BertTokenizer
import htm... | dalle_pytorch/tokenizer.py | MIT | 9,432 | 127b5c01f63f74b8226af842651860061b02e0d2 | Python | py | |
import os
import time
from copy import deepcopy
import gym
import torch
import torch.nn as nn
import numpy as np
import numpy.random as rd
class ActorPPO(nn.Module):
def __init__(self, mid_dim, state_dim, action_dim):
super().__init__()
self.net = nn.Sequential(nn.Linear(state_dim, mid_dim), nn.Re... | Example_SingleFilePPO.py | Apache-2.0 | 34,654 | 3a45a43a741ffc601b4ab3bd3b506a094ed7a33f | Python | py | |
import matplotlib.pyplot as plt
import math
import torch
import numpy as np
import scipy.stats as st
def normal_cdf(x, mu=0, sigma=1):
return (1+math.erf((x-mu)/math.sqrt(2)*sigma))/2
small_num = 5000
num = 250
w_sigma = 1.0
b_sigma = 1.0
xs = np.arange(-3, 3, 0.02)
x_all = []
for j in range(num):
w = torch... | domainbed/prob_check.py | MIT | 1,278 | ff82737f6b24aee9bc8265af50d7da78cfc321d4 | Python | py | |
# coding=utf-8
# Copyright 2018 The Microsoft Research Asia LayoutLM Team Authors and the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/... | src/transformers/models/layoutlm/modeling_layoutlm.py | Apache-2.0 | 53,029 | ff35a64d841491ff771f5a96daefa40fa0efdd6e | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from collections import OrderedDict
__all__ = ['DenseNet', 'densenet121', 'densenet169', 'densenet201', 'densenet161']
def densenet121(pretrained=False, **kwargs):
model = DenseNet(num_init_features=64, g... | models/backbones/densenet.py | MIT | 5,806 | 3a463afc4c52d1838eff4c0daedb4ebe49ababc3 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
class BaselineNet(nn.Module):
"""
This class creates a fully connected neural network for classifying traffic signs
from the GTSRB dataset.
Network architecture:
- Input layer
- First hidden... | traffic_signs_detection/traffic_signs_classification/code/cnn.py | MIT | 1,682 | 3a4644dbc6a9f95a3763e4bc22ab539137af6994 | Python | py | |
r"""
A textual head accepts visual features from the visual backbone, and performs
task specific modeling (captioning, classification etc.) to predict an output
distribution over vocabulary tokens for one or multiple time-steps in the batch.
"""
import torch
from torch import nn
from typing import Optional
from virtex... | virtex/modules/textual_heads.py | MIT | 15,211 | 52a451d8fb3b28149a5baab7ad2bc2cdbb1bd998 | Python | py | |
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from net_utils import run_lstm
class Seq2SQLCondPredictor(nn.Module):
def __init__(self, N_word, N_h, N_depth, max_col_num, max_tok_num, gpu):
super(Seq2SQLCondPredictor, se... | sqlnet/model/modules/seq2sql_condition_predict.py | BSD-3-Clause | 4,875 | 4bb34ba1d546b45c11fbb255803f71111603abbe | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def swish(x):
return x * torch.sigmoid(x)
def linear(x):
return x
class EnsembleDenseLayer(nn.Module):
def __init__(self, n_in, n_out, ensemble_size, non_linearity='leaky_relu'):
"""
linear + activation Layer
there are `e... | mjmpc/utils/ensemble_model.py | Apache-2.0 | 3,911 | 5eaf3ff86ba968d8495feed227c38e268466f882 | Python | py | |
import math
import ipdb
import torch
def positionalencoding1d(d_model, length):
"""
:param d_model: dimension of the model
:param length: length of positions
:return: length*d_model position matrix
"""
if d_model % 2 != 0:
raise ValueError("Cannot use sin/cos positional encoding with "... | game_seq_embedder/app/temp_test_pos_embed.py | Artistic-1.0-Perl | 2,340 | 3a46a366f7b799a4461f9ed70af7ec78447bcadb | Python | py | |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace 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 copy... | all_exp/ernie/code/code/knowledge_bert/modeling.py | MIT | 66,864 | 3a46a66b97a800991e29a2f79a812fce58abb506 | Python | py | |
# -*- coding: utf-8 -*- #
"""*********************************************************************************************"""
# FileName [ expert.py ]
# Synopsis [ the phone linear downstream wrapper ]
# Author [ S3PRL ]
# Copyright [ Copyleft(c), Speech Lab, NTU, Taiwan ]
"""******************... | s3prl/downstream/cont_spk/expert.py | Apache-2.0 | 10,890 | 459618ab80f93e6a599886a636bc8f2f344ce02d | Python | py | |
import torch
from torch import nn
class MobileNetEncoder(nn.Module):
def __init__(self, pretrained=True, freeze_weights=False, max_pool=True):
super().__init__()
self.sample_input = torch.randn((1, 1, 128, 130))
mobilenet = torch.hub.load(
"pytorch/vision:v0.8.2", "mobilenet_v2... | modeling/music_metric_learning/modules/mobilenet.py | MIT | 1,257 | b282d8816c5b1556900c62b520456b0161666b7d | Python | py | |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | distributed_training/train_pytorch_single_maskrcnn.py | Apache-2.0 | 10,151 | f947cb9b50f088c4c71ca284808c4d4f22a04cd0 | Python | py | |
import os
import json
import torchvision
from PIL import Image
from torchvision import transforms as T
import cv2
import numpy as np
COCO_INSTANCE_CATEGORY_NAMES = [
'__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', ... | cityscapesStuff/Tools/draw_polygons_mask_rcnn.py | MIT | 3,142 | cc2f2d2610da52ba48f2f82eef7b829e9b3a5f9a | Python | py | |
import unittest
import torch
from torchvision.transforms import Compose, ToTensor
from super_gradients.training.transforms.transforms import Rescale, RandomRescale, CropImageAndMask, PadShortToCropSize
from PIL import Image
from super_gradients.training.datasets.segmentation_datasets.segmentation_dataset import Segmen... | tests/unit_tests/segmentation_transforms_test.py | Apache-2.0 | 8,628 | 3a46e1a302f148f582c245d923950d5b13fa8fc8 | Python | py | |
__all__ = ["PaddingCollator"]
import utils
from dataclasses import dataclass
from typing import FrozenSet
import torch
import numpy as np
@dataclass
class PaddingCollator:
pad_keys: FrozenSet[str] = frozenset()
@staticmethod
def stack(tensors, pad=False):
if pad:
return utils.pad_st... | datasets/collator.py | MIT | 2,084 | 3a46ee1541f61abe958f38df87dcdce26af5d59c | Python | py | |
import numpy as np
import torch.nn.functional as F
from torch import nn
import torch
class ELBO(nn.Module):
def __init__(self, train_size):
super(ELBO, self).__init__()
self.train_size = train_size
def forward(self, input, target, kl, beta):
assert not target.requires_grad
ret... | bayesian/metrics.py | MIT | 1,823 | 3a46f779e4e8c291720d0d55a7f88e079dcd755c | Python | py | |
from torch.utils.data import Dataset
import torchvision.transforms as transforms
import os.path as osp
import os
from transform import *
class FaceMask(Dataset):
def __init__(self, rootpth, cropsize=(640, 480), mode='train', *args, **kwargs):
super(FaceMask, self).__init__(*args, **kwargs)
assert ... | face_dataset.py | MIT | 1,679 | 5e63ad7f54501e4c684f6dce893a922db6d60aa6 | Python | py | |
from __future__ import print_function, division
import os
import sys
from skimage import io
import pandas as pd
import numpy as np
import torch
from torch.nn.modules.module import Module
from torch.utils.data import Dataset
from torch.autograd import Variable
import torch.nn.functional as F
class GeometricTnf(object):... | geotnf/transformation_3d.py | MIT | 15,383 | d72b9004d8ed69d3a7bf8d3c58821ba2c65b17ed | Python | py | |
#
# Copy from https://github.com/Jimexist/conv_lstm_pytorch/blob/master/conv_lstm/conv_lstm.py
# Originally by Jimexist under MIT License
#
import torch
import torch.nn as nn
class ConvLSTMCell(nn.Module):
def __init__(
self,
input_dim: int,
hidden_dim: int,
kernel_size: int,
... | leibniz/nn/net/conv_lstm.py | MIT | 6,552 | 3a474638aac0c0efa3cb2e1ef1e2f4f5bf681026 | Python | py | |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | pytorch_lightning/utilities/seed.py | Apache-2.0 | 5,086 | d79e2047c5b0c5ff143ccb1a1ee324efe450bc21 | 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/classification/test_accuracy.py | Apache-2.0 | 8,015 | 1074d6ce37de07babe217d3fe489e606402e0ddf | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
from components.dataset import Batch
from grammar.transition_system import ApplyRuleAction, GenTokenAction, ActionTree, ReduceAction
from grammar.hypothesis import Hypothesis
import numpy as np
import os
from common.config import update_ar... | torchASN/models/CodeBertASN.py | MIT | 21,713 | 3a475b01b2a7a8002fcc4ee65ae0f658db1715f4 | Python | py | |
import torch.nn as nn
from math import log2
from im2scene.layers import ResnetBlock
class DCDiscriminator(nn.Module):
''' DC Discriminator class.
Args:
in_dim (int): input dimension
n_feat (int): features of final hidden layer
img_size (int): input image size
'''
def __init__... | im2scene/discriminator/conv.py | MIT | 3,041 | 1e07f6969ed74ada058151495f13855066eb473d | Python | py | |
import torch
import torch.nn as nn
class fc(nn.Module):
""" """
def __init__(self,num_channels:int=1,num_classes:int=3, input_shape=(16,14,11),**kwargs):
"""
Parameters
----------
num_channels : int
(Default value = 1)
num_classes : int
(Default... | src/models/fc.py | Apache-2.0 | 1,123 | 3a477c298ad12f0925ac6be80311e4a34c496432 | Python | py | |
import math
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/re... | wideresnet.py | MIT | 6,676 | 1ebfdc5ba8ae4e1cc512d7e16076b31aef14bf93 | Python | py | |
#!/usr/bin/env python
# coding: utf-8
"""Compute centroids of BERT representations for all languages."""
import argparse
import os
import logging
import sys
import joblib
import numpy as np
from sklearn.neural_network import MLPRegressor
import torch
import torch.nn as nn
import torch.optim as optim
from utils impo... | qe_by_regression.py | BSD-3-Clause | 3,936 | 3a47a747728eeb1e26bfa3020002d9b92e46cd4f | Python | py | |
import pytest
import numpy as np
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
from ivadomed import utils as imed_utils
from ivadomed.loader import utils as imed_loader_utils, loader as imed_loader
from unit_tests.t_utils import remove_tmp_dir, create_tmp_dir, __data_testing_dir__
cudn... | testing/unit_tests/test_slice_filter.py | MIT | 3,114 | 24ced867b5d7181f230f7350f26b0773879d01e2 | Python | py | |
import os
import math
import argparse
import pickle as pkl
from tqdm import tqdm
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
import _init_paths
from core.engine import Engine
import datasets
import models
from core.utils import AverageMeter
from core.co... | moment_localization/test.py | MIT | 12,619 | f93362952ac5096923ee4d2fa85536d6df729230 | 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 typing import Any, Dict, List
import random
import os
import torch
from torch.utils.data import Dataset
import numpy as np
im... | vilbert-multi-task/vilbert/datasets/retreival_dataset.py | MIT | 17,844 | 700b44a2ecef96ed8a22629132aa046b7b556f86 | Python | py | |
from __future__ import print_function
import torch.utils.data as data
import os
import sys
sys.path.insert(1, '../alignment')
from alignment import align
import torch
import random
import numpy as np
from torch.autograd import Variable
import torchvision.transforms as transforms
from PIL import Image
import cv2
IMG_EX... | gainmap/dataset.py | MIT | 7,062 | 24f31ce8e2bdb515f583f11e2ce18b16fa389d30 | Python | py | |
from itertools import combinations
import torch
import torch.nn.functional as F
import torch.nn as nn
from pytorch_pretrained_bert import BertTokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
cl_loss_type = nn.CrossEntropyLoss()
gr_loss_type = nn.MSELoss()
def get_encoding(text, bert, device):... | utils/util.py | MIT | 2,884 | 5f97dedd1788160535af8efe0d3246a4bb6b362f | Python | py | |
import torch
import torch.nn as nn
import numpy as np
def pNetwork(x, y, rule, depth, width):
myNet = ''
if(rule == 1):
myNet = nn.Sequential(
nn.Linear(2, 10),
nn.ReLU(),
nn.Linear(10, 1),
nn.Sigmoid()
)
print(myNet)
... | Neural Networks/pytorchPy.py | OLDAP-2.5,OLDAP-2.4 | 2,183 | 3a47f0fff311bf8e40a1756ecbfdf88fe77cc71b | Python | py | |
import math
import re
import logging
from copy import deepcopy
import torch
import torch.nn as nn
import torch.nn.functional as F
from mixnet.registry import register_model
from mixnet.helpers import load_pretrained
from mixnet.adaptive_avgmax_pool import SelectAdaptivePool2d
from mixnet.conv2d_helpers im... | mixnet/model_all.py | BSD-2-Clause | 67,511 | 3a47f71572124c743acff1eeaaf180165c599927 | Python | py | |
import argparse
import math
import time
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from models import LSTNet
import numpy as np;
import importlib
from utils import *;
import Optim
# Passes the data-set as input to the model in small batches
# After the data-set ... | main.py | MIT | 7,478 | 4b2a96db47ef2f5b61f771e0515a4a6250c4d3d4 | Python | py | |
"""
Adapted from huggingface modeling_bert.py. Change the necessary part to use Colossolai.
"""
import torch
import math
from transformers import (PreTrainedModel, BertConfig, load_tf_weights_in_bert,
apply_chunking_to_forward
)
from transformers.activations ... | bert/colossalai_utils/model_zoo/colo_bert.py | Apache-2.0 | 40,038 | 3a480319d1873e9d12cbbbe5c4a8b12b3620bff5 | Python | py | |
# This file contains modules common to various models
import math
import torch
import torch.nn as nn
def autopad(k, p=None): # kernel, padding
# Pad to 'same'
if p is None:
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
return p
def DWConv(c1, c2, k=1, s=1, act=True):
... | models/common.py | MIT | 4,343 | 3a482a5cdd9d2ec0a1720885716ebb92e7affab2 | Python | py | |
# coding=utf-8
# Copyright 2021 The HuggingFace Inc. team. 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 r... | examples/pytorch/text-classification/run_glue_no_trainer.py | Apache-2.0 | 26,745 | d7dbe8426b5094e089177be74dd1d64f2bdba5e0 | Python | py | |
import torch
import torch.nn.functional as F
import torch_geometric.transforms as T
from torch.nn import Sequential as seq, Parameter, LeakyReLU, init, Linear
from torch_geometric.nn import MessagePassing, GCNConv
from torch_geometric.utils import softmax, degree
import os
import numpy as np
class CGNNConv(MessagePas... | model/CGNNConv.py | MIT | 1,137 | dff9892a6a9c9d9362b796ab9dc0ea54f51f1133 | Python | py | |
import argparse
import os, sys, glob
import time
import math
import numpy as np
import torch
import logging
import torch.nn as nn
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from architect import Architect
import gc
import data
import model_search as model
from utils import batchify, get_bat... | rnn/train_search.py | Apache-2.0 | 12,716 | 4b4b5e127a670cf5657ff30c9af1257dc0c6ea9d | Python | py | |
import importlib
from torch.utils.data import Dataset, DataLoader
def CreateDataLoader(opt):
dataset_filename = "data." + opt.model_name + '_dataset'
datasetllib = importlib.import_module(dataset_filename)
dataset = None
target_dataset_name = opt.model_name.replace('_', '') + 'dataset'
for nam... | data/dataloader.py | MIT | 1,056 | 3a4878873610cb6d47d3f76a601490010ded6121 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from rlpyt.utils.tensor import infer_leading_dims, restore_leading_dims
from rlpyt.models.conv2d import Conv2dHeadModel
class ConvEncoder(nn.Module):
def __init__(self, image_shape=(1, 128, 128), z_size=128):
super(ConvEncoder, self).__in... | my-src/models.py | MIT | 2,650 | d7c43befbfc51282e4b319245f1cd98e6481cc13 | Python | py | |
import numpy as np
from torch.utils.data import DataLoader
from torch.utils.data.dataloader import default_collate
from torch.utils.data.sampler import SubsetRandomSampler
import copy
import pdb
class BaseDataLoader(DataLoader):
"""
Base class for all data loaders
"""
def __init__(self, dataset, batch... | base/base_data_loader.py | MIT | 1,982 | 423a9b2dab147f3443788c9f6c8e72eb17bfeb2e | Python | py | |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""CIFAR10 streaming dataset conversion scripts."""
import os
from argparse import ArgumentParser, Namespace
from typing import Any, Dict, Iterable, List, Tuple
import numpy as np
from numpy.typing import NDArray
from torchvision.datase... | scripts/mds/cifar10.py | Apache-2.0 | 2,851 | d78011b5b7d20da4af423c6eb628310189ed4ee7 | Python | py | |
#!/usr/bin/env python
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyrig... | qa/common/inferentia_perf_analyzer_input_data_json/simple_model.py | BSD-3-Clause | 5,827 | 650e5fbdb1740438cc7129f274ac18581ed6e193 | Python | py | |
from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as pl
class judge(nn.Module):
def __init__(self):
super(judge, self).__init__()
# in_channels, out_channels, kerne... | PycharmProjects/VanillaGAN/models/gan_parts.py | MIT | 3,930 | 3a491c1eee2c989066619d8ea45185baec117173 | Python | py | |
import torch
from PIL import Image
import numpy as np
import imageio
# Functions for saving the output of the generator as image
def save_tensor_as_image(data, out_size_image, path):
interpolation = 'nearest'
if isinstance(out_size_image, tuple):
out_size_image = out_size_image[0]
data = torch.cl... | src/PGAN/helper/visualization.py | MIT | 2,245 | 8011d3161557860ae24cf4f93288b2c2e16c0d5b | Python | py | |
from torchvision import datasets, transforms
import torch
from experiments import ADMMRetrain, ADMMIntra, GDTopK, MCGDTopK, MCGDTopKACDK, MCGDTopKAC, Baseline, \
MCGDTopKACDKADMMIntra, REPruningMCGDTopKACDKADMMIntra, REPruningAC, MCGDTopKACDKADMMRetrain, REPruningADMMIntra, \
REPruningACADMMIntra, REPruningACA... | utils/experiment_factory.py | BSD-3-Clause | 4,350 | 7ca5b0a162d826367738cda0ed735c640bdafaf2 | Python | py | |
# -*- coding: utf-8 -*-
import argparse
import os
import sys
import time
import numpy as np
import torch as t
from torch.optim import Adam
import sample
from utils.batch_loader import BatchLoader
from model.parameters import Parameters
from model.paraphraser import Paraphraser
if __name__ == "__main__":
print(sy... | train.py | MIT | 9,298 | d7f4e58c8aab6ad2423a77bb5eab3879ca55e0f8 | Python | py | |
# Programmer info
# Name: Fahad Moidy
# Date: 5/03/2022
# Example command
# python train.py ./flowers --learning_rate 0.001 --hidden_units 5000 --epochs 15 --gpu --save_dir ./saves --arch Densenet
# Python Imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
import cv2
i... | train.py | MIT | 5,527 | 3a493633c86f4d4cbbe3a082ed2b44374e2b0d35 | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule
from mmdet.core import auto_fp16
from ..builder import NECKS
from .fpn import FPN
@NECKS.register_module()
class PAFPN(FPN):
"""Path Aggregation Network for Instance Segmentation.
This is an implementation of the PAFPN in P... | mmdet/models/necks/pafpn.py | Apache-2.0 | 5,394 | 03e77e071bca8600c34c7b6600e8c16cbd5f1c94 | Python | py | |
"""
`Learn the Basics <intro.html>`_ ||
`Quickstart <quickstart_tutorial.html>`_ ||
**Tensors** ||
`Datasets & DataLoaders <data_tutorial.html>`_ ||
`Transforms <transforms_tutorial.html>`_ ||
`Build Model <buildmodel_tutorial.html>`_ ||
`Autograd <autogradqs_tutorial.html>`_ ||
`Optimization <optimization_tutorial.htm... | beginner_source/basics/tensorqs_tutorial.py | BSD-3-Clause | 7,606 | 03b7b1cd70a03fb08533a2f158af933d97df4c66 | Python | py | |
from .. import util
import torch
from torch import nn, Tensor
from typing import Iterable, Dict
import torch.nn.functional as F
class MegaBatchMarginLoss(nn.Module):
"""
Loss function inspired from ParaNMT paper:
https://www.aclweb.org/anthology/P18-1042/
Given a large batch (like 500 or mo... | sentence_transformers/losses/MegaBatchMarginLoss.py | Apache-2.0 | 5,327 | 3a4967b3ab7d66fd83bbc6a348c663280145519f | Python | py | |
# To produce final out in formate desired by WNUT shared Task 2020
# It will read file from data/proto/interactive/sentences for training to keep the information of files
# In training we will providing data from single file containing all the sentences to allow shuffling across domain.
# use for generating out to tes... | inference.py | MIT | 5,159 | 3a498fd07e0e231ac158869a7aef6472692c549a | Python | py | |
"""
LOAD DATA from file.
"""
# pylint: disable=C0301,E1101,W0622,C0103,R0902,R0915
##
import os
import torch
import numpy as np
import torchvision.datasets as datasets
from torchvision.datasets import MNIST
from torchvision.datasets import CIFAR10
from torchvision.datasets import ImageFolder
import torchvision.transf... | lib/data.py | MIT | 14,386 | 101c1004540451c64a3850f787b3f914ec881183 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import inspect
import logging
import numpy as np
import os
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
import cv2
import torch
from torch import nn
from detectron2.config import configurable
from detectron2.layers... | projects/WSL/wsl/modeling/seg_heads/wsjds_heads.py | Apache-2.0 | 29,084 | 3a49b1c1c40e2d532617ab4f62eb6371454fd44e | Python | py | |
from flask import Flask, jsonify, request
from .utils.funcs import top_filtering, nlg, extractor
from .utils.search import search_for
from transformers import GPT2Tokenizer, GPT2LMHeadModel, GPT2Config
from sentence_transformers import SentenceTransformer
from annoy import AnnoyIndex
import pandas as pd
import rando... | model/api/app.py | MIT | 4,680 | 3a49b8a18e4e381615f479530635432e428fd58d | Python | py | |
# Author: Leda Sari
import os
import json
import numpy as np
import pandas as pd
from torch.utils.data import Dataset
from torch.utils.data.dataloader import default_collate
class LibriSpeechDataset(Dataset):
def __init__(self, feat_csv, args_dict):
self.args = args_dict
self.df = pd.read_csv(fea... | dataset.py | Apache-2.0 | 2,041 | 3a49c1090a07f73d8c91ca44a859387d08dde789 | Python | py | |
# -*- coding: utf-8 -*-
"""
This is a simple generalized harness for training a classifier on a coco dataset.
Given a COCO-style dataset data (you can create a sample coco dataset using the
kwcoco CLI), this module trains a classifier on chipped regions denoted by the
coco annotations. These chips are cropped from the... | netharn/examples/classification.py | Apache-2.0 | 32,377 | ff6a1c860254b53cf6246dca5e698e134415e8d5 | Python | py | |
#!/usr/bin/env python3 -u
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
"""
Train... | train.py | BSD-3-Clause | 16,162 | 3a49f5b466e215bdaeb290bbde6f1ecac87427be | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: 11360
# datetime: 2021/4/14 10:25
import torch
import torch.nn as nn
class oneDimenNet(nn.Module):
def __init__(self):
super(oneDimenNet, self).__init__()
self.conv1 = nn.Conv1d(60, 30, 1)
self.pool1 = nn.MaxPool1d(2, 2... | src/model.py | MIT | 5,574 | 3a4a29b029d38a5a1f17122d257301e6e9f95f77 | Python | py | |
import math
import os
import numpy as np
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
from torch.nn.modules.batchnorm import _BatchNorm
# from vgtk.so3conv import Gathering
from vgtk.so3conv.functional import batched_index_select, acos_safe
from vgt... | vgtk/loss.py | MIT | 16,099 | 3a4a7615e3e9bfe2ba22b0210bb35f9a3937a92c | Python | py | |
import torch
from models import BaseVAE
from torch import nn
from torch.nn import functional as F
from .types_ import *
class HVAE(BaseVAE):
def __init__(self,
in_channels: int,
latent1_dim: int,
latent2_dim: int,
hidden_dims: List = None,
... | models/hvae.py | Apache-2.0 | 9,396 | fdd46c684e99c9252357e0beeb75c96a02564eb7 | Python | py | |
"""Pytorch port of the resnet used for CIFAR100 by iCaRL.
https://github.com/srebuffi/iCaRL/blob/master/iCaRL-TheanoLasagne/utils_cifar100.py
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
from continual.cnn import AbstractCNN
class DownsampleStride(nn.Module):
... | continual/cnn/resnet_rebuffi.py | Apache-2.0 | 7,473 | dfc9556b41c00b4c525d6aae534f3b7c7badfddd | Python | py | |
from torch.utils.data.sampler import RandomSampler, BatchSampler
from torch.utils.data.dataloader import DataLoader, default_collate
from yacs.config import CfgNode as CN
from xmuda.common.utils.torch_util import worker_init_fn
from xmuda.data.collate import get_collate_scn
from xmuda.common.utils.sampler import Itera... | xmuda/data/build.py | Apache-2.0 | 3,303 | 3a4aa985c8b1ea34096cc733de67040110627526 | Python | py | |
import torch
from pytorch.common import conv_bn_activation
from torch import nn
"""MobilenetV2 Block with inverted residual structure"""
class MobilenetV2Block(nn.Module):
EXPANSION_FACTOR = 6
def __init__(self, in_channels):
# We only use the stride = 1 block with expansion factor 6
# These... | pytorch/common/blocks/mobilenetv2_block.py | BSD-3-Clause | 1,657 | e95b70dd6d8ba6e74f6801a1f2150d20d4b6131a | Python | py | |
import torch
import os
import math
import numpy as np
import subprocess
import random
import ref
def exec(opt, cacheFile):
assert os.path.exists(opt.data), 'Data directory not found: ' + opt.data
print("=> Generating list of data")
with open(os.path.join(ref.data_root, 'train.txt'), 'r') as f:
tra... | linepx/datasets/indoor-gen.py | MIT | 1,273 | 3a4adaba0688d7a78c7a3c9543fbcc9ed025b439 | Python | py | |
import torch
import torch.nn as nn
import math
class IALSHAttention16(nn.Module):
def __init__(self,
qnf,
m=2,
U=0.75
):
super().__init__()
self.m = m
self.U = U
self.QNF = qnf
def forward(self, qk, bucket_siz... | LSH/IALSH.py | Apache-2.0 | 5,861 | b2595324c2979f8ff6239a8751aad6d3a462d10f | Python | py | |
import io
import itertools
import tarfile
from parameterized import parameterized
from torchaudio.backend import sox_io_backend
from torchaudio._internal import module_utils as _mod_utils
from torchaudio_unittest.common_utils import (
TempDirMixin,
HttpServerMixin,
PytorchTestCase,
skipIfNoExec,
s... | test/torchaudio_unittest/sox_io_backend/load_test.py | BSD-2-Clause | 19,443 | 3a4b0ba8fedb34803c367615dbb7892dc9a306b4 | Python | py | |
import torch
def get_default():
"""get default device for torch.
Returns
-------
device : str
'cuda' if torch.cuda.is_available() is True,
and returns 'cpu' otherwise.
"""
if torch.cuda.is_available():
return "cuda"
else:
return "cpu"
| src/vak/device.py | BSD-3-Clause | 298 | 5e7d506e56aaaefc5d730324f6412a62776fabc2 | Python | py | |
import torch
import numpy as np
from inverter_util import RelevancePropagator
from utils import pprint, Flatten
class InnvestigateModel(torch.nn.Module):
"""
ATTENTION:
Currently, innvestigating a network only works if all
layers that have to be inverted are specified explicitly
and r... | layerwise_relevance_propagation/innvestigator.py | MIT | 10,300 | 3a4b272f5518666c1e3f96a02c8a5585b76591b7 | Python | py | |
# Copyright 2018-2021 Xanadu Quantum Technologies 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... | tests/templates/test_layers/test_particle_conserving_u2.py | Apache-2.0 | 11,274 | 3a4b36122adbe6ec84b80fb88f491433fd99cf4c | Python | py | |
#CUDA_VISIBLE_DEVICES=1
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn import init
import numpy as np
import json
import os.path
import subprocess
import random
from operator import itemgetter
import sklearn.metrics as metri... | lstm_partial_grid_rri.v.16.py | Apache-2.0 | 11,017 | 3a4b4dbf784b2fcb19f957f78884873d39b64b89 | Python | py | |
import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image, ImageDraw
from numpy import asarray
from torchvision import models
from Resnet_GRU.resnet_gru import BasicBlock1, ResLSTMNet
from face_detection.MTCNN.detector import FaceDetector
import ... | test_mtcnn.py | MIT | 6,058 | 3a4b5044b1747e464008181e636a9c6e45f4022d | Python | py | |
"""
The lightning training loop handles everything except the actual computations of your model.
To decide what will happen in your training loop, define the `training_step` function.
Below are all the things lightning automates for you in the training loop.
Accumulated gradients
---------------------
Accumulated g... | pytorch_lightning/trainer/training_loop.py | Apache-2.0 | 31,410 | 3a4b6df2889e32cca68ed41414af875e53506128 | Python | py | |
import numpy as np
import torch
from torch.autograd import Variable
from mtcnn_pytorch_master.src.get_nets import PNet, RNet, ONet
from mtcnn_pytorch_master.src.box_utils import nms, calibrate_box, get_image_boxes, convert_to_square
from mtcnn_pytorch_master.src.first_stage import run_first_stage
def detect_faces(ima... | first-order-motion/mtcnn_pytorch_master/src/detector.py | MIT | 4,243 | 10835f8f79682663511f686bafddaba2d66b8abc | Python | py | |
import json
import torch
import pandas as pd
from pathlib import Path
from itertools import repeat
from collections import OrderedDict
def ensure_dir(dirname):
dirname = Path(dirname)
if not dirname.is_dir():
dirname.mkdir(parents=True, exist_ok=False)
def read_json(fname):
fname = Path(fname)
... | utils/util.py | MIT | 2,120 | ffa1cecd59f6fb7ebd4a73ff1876ad67e5875e56 | Python | py | |
# -*- coding:utf-8 -*-
import configparser
import torch
from lib.utils import scaled_Laplacian, cheb_polynomial, get_adjacency_matrix
def get_backbones(config_filename, adj_filename, device):
config = configparser.ConfigParser()
config.read(config_filename)
K = int(config['Training']['K'])
num_of_... | model/model_config.py | MIT | 2,192 | f96b8e96c644a95d36140d9882b005f688a3695d | Python | py | |
from pathlib import Path
from os.path import exists
import torch
import torch.nn as nn
from copy import deepcopy
from typing import Literal, Optional, List
from torchtyping import TensorType
from transformers.file_utils import ModelOutput
from magma.config import MultimodalConfig
from magma.utils import get_tokenizer
... | magma/magma.py | MIT | 11,307 | e646f0b9d770f162abd72c1a77017b9f99045451 | Python | py | |
import torch
import matplotlib.pyplot as plt
def plot_testcase_1d(testcase, tol):
X = testcase.plot_X
#plot functions
for i, func in enumerate(testcase.true_functions):
f = plt.plot(X, func(X), 'k--', label=f"true function \#{i}")
#plot threshold s
for thr in testcase.thresholds:
... | excursion/plotting/__init__.py | Apache-2.0 | 739 | 3a4bc146b844d99945ab48a6df8d85b4ff0aae09 | Python | py | |
import unittest
import numpy
import torch
from torch import nn
import pytorch_trainer
from pytorch_trainer import dataset
from pytorch_trainer import iterators
from pytorch_trainer import testing
from pytorch_trainer.training import extensions
class DummyModel(nn.Module):
def __init__(self, test):
supe... | tests/training_tests/extensions_tests/test_evaluator.py | MIT | 9,280 | 1e403994f89fbf20e91db18225e22812fa8f4b5b | Python | py | |
"""
This includes: LossComputeBase and the standard NMTLossCompute, and
sharded loss compute stuff.
"""
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
import onmt
from onmt.modules.sparse_losses import SparsemaxLoss
from onmt.modules.sparse_activations... | onmt/utils/loss.py | MIT | 19,688 | 24d5f7e4aaed538bc7741ea90fe16d5b6fbd24bf | Python | py | |
import torch as th
import torch.nn as nn
import torch.nn.functional as F
def onehot_encode(tensor, target_dim):
y_onehot = tensor.new(*tensor.shape[:-1], target_dim).zero_()
y_onehot.scatter_(-1, tensor.long(), 1)
return y_onehot.float()
class IACritic(nn.Module):
def __init__(self, scheme, args):
... | src/modules/critics/iac_critic.py | MIT | 1,796 | 1e2a2203eefb23558159aab9f84870594c994613 | Python | py | |
import copy
import torch
from torch import nn
class Sin(torch.nn.Module):
def forward(self, x, inverse=False):
if not inverse:
return torch.sin(x)
else:
return torch.asin(x)
class MLP(torch.nn.Module):
def __init__(
self,
input_size,
num_layer... | nntransfer/models/mlp.py | MIT | 1,652 | 101c601074fe538281aae35ef0f8e72cbdd43c95 | Python | py | |
'''
This software is derived from the OpenNMT project at
https://github.com/OpenNMT/OpenNMT.
Modified 2017, Idiap Research Institute, http://www.idiap.ch/ (Xiao PU)
'''
import math
import torch.optim as optim
import torch.nn as nn
from torch.nn.utils import clip_grad_norm
import itertools
class Optim(object):
d... | onmt/Optim.py | MIT | 2,125 | 7c77376e25626be1e9a8221a2a857ba5ce45aef9 | Python | py | |
# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
import numpy as np
import torch
from aepsych.server import AEPsychServer
from psychopy import core, data, event, gui, monitors, visual
from contrast_discrimination import config
from contrast_discrimination.helpers import HalfGrating
class Se... | human_data_collection/experiment.py | MIT | 4,851 | 3a4bfb3a7b91e9b1db8a657b8b31d2ddd6a48633 | Python | py | |
import glob
from os.path import join
import numpy as np
from PIL import Image
from torch.utils.data import Dataset, DataLoader
class UnpairedI2IDataset(Dataset):
def __init__(self, A_dir, B_dir, transform=None):
self.imgs_A = self._get_images(A_dir)
self.imgs_B = self._get_images(B_dir)
s... | datasets.py | MIT | 1,670 | d73f7430dcaaf59fe0c7ca8abe1a3d1b625feb7b | Python | py | |
from argparse import ArgumentParser
import os
import cv2
import numpy as np
import torch
import pytorch_lightning as pl
from pytorch_lightning import Trainer, loggers
from torchsummary import summary
import torch.nn.functional as F
from autoencoder import Autoencoder
from harbour_datamodule import list_frames_in_dir
... | pytorch/old/lightning-autoencoder/main.py | MIT | 7,350 | dfc12c45a62836757c8e428b12ee63b00bfd9e16 | Python | py | |
import math
import numpy as np
import torch
from scipy.linalg import expm
from torch import nn
import torch.nn.functional as F
from torch.nn.modules.transformer import TransformerEncoderLayer
from einops import rearrange, repeat
from torchvision.transforms.functional import _get_inverse_affine_matrix
from functools im... | orbit_transfer/models/learned_equiv.py | MIT | 18,056 | 3a4c5228b56c65696ca53027a71706a71b07cb5a | Python | py | |
# Based on Detectron.pytorch/lib/core/config.py
# --------------------------------------------------------
# Detectron.pytorch
# Licensed under The MIT License [see LICENSE for details]
# Written by roytseng-tw
# --------------------------------------------------------
from __future__ import absolute_import
from __fut... | lib/core/config.py | MIT | 44,372 | 24cb2f8d8519e238766572a455198d71dbf17e62 | Python | py | |
import torch.nn as nn
class Discriminator(nn.Module):
def __init__(self, num_gpu: int, num_channels: int, feat_maps_size: int, image_size: int, use_sigmoid: bool):
super(Discriminator, self).__init__()
self.num_gpu = num_gpu
self.use_sigmoid = use_sigmoid
self.is_wgan = False
... | GANs/DCGAN/discriminator.py | MIT | 2,633 | 3a4c6aba7d8d5425591fc7ecf8218fbb47628eac | Python | py | |
# MIT License
# Copyright (c) 2018 the NJUNMT-pytorch authors.
# 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, m... | src/models/base.py | MIT | 2,872 | a9667f17cfa86412d2568370be1d1fe693acfe81 | Python | py | |
"""
3D scattering transform benchmark
=================================
We compute scattering transforms for volume maps of size `128`-by-`128`-by-
`128`, with averaging scale `2**2 = 4` and maximum spherical harmonic
order `L = 2`. The volumes are stacked into batches of size `batch_size = 8`
and the transforms are co... | examples/3d/compute_speed.py | BSD-3-Clause | 4,949 | 3a4c6f3a7ea5af56acbd4fcb62c9c2b342ffff46 | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
from copy import deepcopy
import mmcv
import torch
import torch.nn as nn
from mmcv.cnn import normal_init, xavier_init
from mmcv.cnn.bricks import build_activation_layer
from mmcv.runner import load_checkpoint
from mmcv.runner.checkpoint import _load_checkpoint_with_pref... | mmgen/models/architectures/biggan/generator_discriminator.py | Apache-2.0 | 31,575 | e90dbf23950df2f5522a004cf260c63aaf9c6157 | Python | py | |
import copy
import os
import numpy as np
import torch
import torch.nn.functional as F
from monai.transforms import Transform, MapTransform, LoadImaged, Lambdad
from monai.inferers import SlidingWindowInferer
from .io import SaveImaged
class Renamed(Transform):
def __call__(self, data):
if "image" in dat... | factorizer/data/transforms.py | Apache-2.0 | 5,485 | 3a4c8076d5ebdbc4d764301dc57cfcb9ba09f329 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.