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 numpy as np
import scipy.ndimage as nd
import torch
import torch.nn as nn
from torch.nn import functional as F
from .utils import dequeue_and_enqueue
def compute_rce_loss(predict, target):
from einops import rearrange
predict = F.softmax(predict, dim=1)
with torch.no_grad():
_, num_cls, ... | u2pl/utils/loss_helper.py | Apache-2.0 | 18,485 | 3aa2ac9d64112365c5dd684d56d2f04cd44bf987 | Python | py | |
"""
connection.py module
Implements the `layer` class, representing a single input-output layer.
"""
import torch
from typing import Union
from .module import AdelieModule
class AdelieConnection(AdelieModule):
def __init__(
self,
source,
target,
sign: int,
gain: float = ... | adelie/core/connection.py | MIT | 3,829 | 7cd3dcfd7982ba09a912b51e416e28ffeff3cc6b | Python | py | |
import torch
import torch.nn as nn
from torch.nn.init import kaiming_normal_
from . import model_utils
from utils import eval_utils
import torch.nn.functional as F
from .transformers import TransformerEncoderLayer
import argparse
from time import time
import math
import torch.optim
import torch.utils.data
import torchv... | models/LCCVTNet.py | MIT | 14,411 | 3aa2c57aed77908e6245776adbe67c2f08921e8e | Python | py | |
import os
from tqdm import tqdm
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import pickle
import json
import argparse
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from networks.modules.architecture import StackedHour... | code/eval_landmark.py | MIT | 4,125 | 3aa2d42bef49a67be5b3301b61ab42ec540c4a24 | Python | py | |
from unityagents import UnityEnvironment
import numpy as np
from collections import deque
import os
from maddpg import MADDPGAgent
import matplotlib.pyplot as plt
import datetime
import torch
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")
def plot(scores=[], yla... | main.py | MIT | 4,290 | ff464502806ba89d4504bf1c9a7f1633eaa5438c | Python | py | |
"""
Use mention encoder to create embeddings.
NOTE: Right now mainly useful for doing inference with a pretrained RELIC w/out needing to load
entity embeddings.
"""
import argparse
import logging
import os
import random
import sys
import tempfile
import numpy as np
import torch
import transformers
from tqdm import tq... | meercat/encode_mentions.py | Apache-2.0 | 4,734 | 7cf57ef4156ef36570618bd9df36151b7212080d | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from opacus.grad_sample import GradSampleModule
from opacus.utils.module_inspection import ModelInspector, get_layer_type
from torch import nn
class IncompatibleModuleException(Exception):
r"""
Exception class to be... | opacus/dp_model_inspector.py | Apache-2.0 | 7,503 | 10646932028f1218834d81bc9bd02e1415e26cc2 | Python | py | |
import torch.nn as nn
import torch
import torch.nn.functional as F
from mmcv.cnn import ConvModule, xavier_init
from mmdet.core import auto_fp16
from ..builder import NECKS
@NECKS.register_module()
class FPNDualSpatial(nn.Module):
"""
Feature Pyramid Network.
This is an implementation of - Feature Pyram... | mmdet/models/necks/fpn_dual_spatial.py | Apache-2.0 | 10,653 | e9d9f938a8c2785a6f5b5febf2ae75a15bbb06e2 | Python | py | |
# Model validation metrics
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import torch
from . import general
def fitness(x):
# Model fitness as a weighted combination of metrics
w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
return (x[:,... | lib/core/evaluate.py | MIT | 11,412 | 3aa31c4bb9ee853b8a2b65ebf91c2e0c8095f145 | Python | py | |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors, Facebook AI Research 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 L... | src/transformers/modeling_utils.py | Apache-2.0 | 88,409 | fdc2ea1dc7b32c53c555758c46ce1c33eef0aea1 | Python | py | |
import logging
import math
import os
from typing import Callable, Optional, Tuple
import torch
from pl_bolts.datasets import LightDataset
from pl_bolts.utils import _TORCHVISION_AVAILABLE
from pl_bolts.utils.warnings import warn_missing_pkg
from torch import Tensor
from torch.utils.data import Dataset
if _TORCHVISION... | src/trackseg/datasets.py | Apache-2.0 | 6,307 | 24c33d8fc7186767495ed5b5931dae932a388715 | Python | py | |
# coding: utf-8
# # 4.1 Fashion MNIST 데이터셋 알아보기
get_ipython().run_line_magic('matplotlib', 'inline')
from torchvision import datasets, transforms, utils
from torch.utils import data
import matplotlib.pyplot as plt
import numpy as np
# ## [개념] Fashion MNIST 데이터셋 설명
transform = transforms.Compose([
transforms.... | 04-Neural-Network-For-Fashion/01-fashion-mnist.py | MIT | 2,057 | 4212b0885727a4a0394f28191c6bdf1a79d67083 | Python | py | |
import torch
import torch.nn as nn
from fastNLP.core.metrics import MetricBase
from fastNLP.core.utils import _get_func_signature
from sklearn.metrics import f1_score, accuracy_score
from transformers import RobertaTokenizer
from hinge_loss import hinge_loss
class SST2Metric(MetricBase):
def __init__(self, pred=N... | metrics_fast.py | MIT | 18,468 | f9db1534e580782cbc4e0b59fdfcb99cc0cb8d87 | Python | py | |
import torch
import torch.nn as nn
class DeepLog(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_keys, device):
super(DeepLog, self).__init__()
self.device = device
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input... | src/models/deeplog.py | MIT | 747 | 28f9caf4f2a1eaf169974bea8f06079c30a03bdd | Python | py | |
"""Train to guess which mole is which in a rotomap image.
It can be helpful to pre-train a model on a reasonable amount of fake data
before fine-tuning it on your own data. This is especially helpful when you
don't have much data of your own yet. For example:
mkdir temp
cd temp
mel-debug gen-repo --num-ro... | mel/cmd/rotomapidentifytrain.py | Apache-2.0 | 8,384 | 3aa357979b65a01fa908d16c56d17effaf7715d1 | Python | py | |
"""
A deep MNIST classifier using convolutional layers.
This file is a modification of the official pytorch mnist example:
https://github.com/pytorch/examples/blob/master/mnist/main.py
"""
import os
import argparse
import logging
import nni
import torch
import torch.nn as nn
import torch.nn.functional as F
import tor... | examples/trials/mnist-pytorch/mnist_tensorboard.py | MIT | 6,351 | 3aa373a75d4c3c831381c052a0cc42d2b0da9d77 | Python | py | |
from flask import Flask, render_template, request, redirect, url_for, session
from transformers import AutoTokenizer, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, pipeline, AutoModelForCausalLM
from haystack.reader.farm import FARMReader
from haystack import Finder
from haystack.document_store... | app.py | MIT | 12,283 | 343b6c4b3b595572e637412466d5ea500dce8eda | Python | py | |
import itertools
import torch.utils.data
class dataset(torch.utils.data.Dataset):
def __init__(self, p_src, p_trg, src_max_len=None, trg_max_len=None):
p_list = [p_src]
if isinstance(p_trg, str):
p_list.append(p_trg)
else:
p_list.extend(p_trg)
lines = []
... | dataset.py | MIT | 1,036 | fde147fa335f125a0e6441d655ab99a76044b7a6 | Python | py | |
#
# Copyright (c) 2021 Idiap Research Institute, https://www.idiap.ch/
# Written by Andreas Marfurt <andreas.marfurt@idiap.ch>
#
""" SentSumm model for sentence-level planning of summaries. """
import torch
import itertools
from torch import nn
from transformers import BertModel, BertConfig, BertForMaskedLM
from tra... | src/sentsumm/model.py | MIT | 29,481 | 28eb71618799982b9a3ef5dd5c09d7da82944bdc | Python | py | |
#!/usr/bin/env python
# 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/LI... | examples/pytorch/language-modeling/run_clm_no_trainer.py | Apache-2.0 | 19,956 | fd69abe4a41e358119b65f18578dd1369a12be23 | Python | py | |
"""
This file contains an implementation of the Dual-Path RNN [1]
References:
[1]: Luo, Yi, Zhuo Chen, and Takuya Yoshioka. “Dual-Path RNN: Efficient
Long Sequence Modeling for Time-Domain Single-Channel Speech
Separation.” ArXiv Preprint ArXiv:1910.06379, 2019.
https://arxiv.org/pdf/1910.0... | padertorch/modules/dual_path_rnn.py | MIT | 24,503 | 3aa39e6afedc455161c5a8f5b3ae7d52c6981bf0 | Python | py | |
from abc import ABCMeta, abstractmethod
from typing import Optional
import torch
from torch import nn
from perceiver_io.attention import CrossAttention
class BasePerceiverDecoder(nn.Module, metaclass=ABCMeta):
"""Abstract decoder class."""
@abstractmethod
def forward(
self,
*,
qu... | perceiver_io/decoders.py | MIT | 3,414 | b2cfcce1b5dd35e37ab994ef876ce0582f3a722e | Python | py | |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Potsdam dataset."""
import os
from typing import Callable, Dict, Optional
import matplotlib.pyplot as plt
import numpy as np
import rasterio
import torch
from matplotlib.figure import Figure
from PIL import Image
from to... | torchgeo/datasets/potsdam.py | MIT | 8,866 | 3aa3b85c2f433b07677b76b8a1625f764cf5a2e8 | Python | py | |
from machin.frame.helpers.servers import model_server_helper
from machin.frame.algorithms import IMPALA
from machin.parallel.distributed import World
from machin.utils.logging import default_logger as logger
from torch.nn.parallel import DistributedDataParallel
from torch.multiprocessing import spawn
from torch.distrib... | examples/framework_examples/impala.py | MIT | 5,896 | 3aa3c431313197e5e4e768a9950e149533cd95f7 | 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.
from typing import Optional, Tuple
import torch
from torch import Tensor
from torch import nn as nn
from torch import o... | habitat_baselines/il/env_based/algos/agent.py | MIT | 5,128 | 3aa3e449d2cc6a6202b6d22a0833a32da5c75609 | Python | py | |
"""
Adapted from
https://github.com/Jackson-Kang/Pytorch-VAE-tutorial/blob/master/01_Variational_AutoEncoder.ipynb
A simple implementation of Gaussian MLP Encoder and Decoder trained on MNIST
"""
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from... | s4_debugging_and_logging/exercise_files/vae_mnist_bugs.py | Apache-2.0 | 4,294 | d7f83d045b4482e86acbf7713e3a00b943fefbd8 | Python | py | |
import torch.nn as nn
class Hard_Distillation_Loss(nn.Module):
def __init__(self):
super(Hard_Distillation_Loss, self).__init__()
self.CE_teacher = nn.CrossEntropyLoss()
self.CE_student = nn.CrossEntropyLoss()
def forward(self, teacher_y, student_y, y):
loss = (1/2) * (self.... | src/models/loss.py | MIT | 409 | 802fbf04ce3c6e48f6dc347529502beb74059e83 | Python | py | |
import numpy as np
import pytest
import torch
from music_metric_learning.losses.contrastive import (
SelectivelyContrastiveLoss,
cosine_similarity_matrix,
keyed_cosine_similarity_matrix,
keyed_same_label_mask,
mine_easy_positives,
mine_hard_negatives,
same_label_mask,
)
from music_metric_lea... | modeling/music_metric_learning/tests/test_loss.py | MIT | 6,205 | e923bf214339108e27cddc2008de23369f78fd8f | Python | py | |
# 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 a network across multipl... | fairseq/trainer.py | BSD-3-Clause | 20,283 | 3aa4274ad0d1c606cfb75dfb7a90b33533cc147a | Python | py | |
#!/usr/bin/env python3
import sys
import time
import argparse
import cv2
import numpy as np
import gym_minigrid
import gym
from gym_minigrid.wrappers import *
from gym_minigrid.window import Window
def redraw(img):
if not args.agent_view:
img = env.render('rgb_array', tile_size=args.tile_size)
windo... | manual_control.py | Apache-2.0 | 4,413 | 3aa4579e8daf96d04ac501998ed2036462c2af44 | Python | py | |
#!/usr/bin/env python3
import torch
import unittest
from test._utils import approx_equal
from gpytorch.utils.cholesky import tridiag_batch_potrf, tridiag_batch_potrs
class TestTriDiag(unittest.TestCase):
def test_potrf(self):
chol = torch.tensor([[1, 0, 0, 0], [2, 1, 0, 0], [0, 1, 2, 0], [0, 0, 2, 3]], d... | test/utils/test_cholesky.py | MIT | 867 | 3aa466eafdd6116edb513cb445f72e7c7cc5ef13 | Python | py | |
# -*- coding: utf-8 -*-
"""
Integration tests for running the sampler with different configurations.
"""
import os
import torch
import pytest
import numpy as np
from nessai.flowsampler import FlowSampler
from nessai.livepoint import numpy_array_to_live_points
from nessai.model import Model
torch.set_num_threads(1)
... | tests/test_sampling.py | MIT | 7,906 | 3aa467a38e2b50e3c1a5d1fccaf89dba7d212b61 | Python | py | |
# Copyright (c) 2020, Huawei Technologies.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 License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law... | test/test_npu/test_network_ops/test_format_cast.py | BSD-3-Clause | 7,848 | 3aa4857f5a7e8799f90f6d9d4482ca09e0b66188 | Python | py | |
import torch
import torch.nn as nn
from Layers import EncoderLayer, DecoderLayer
from Embed import Embedder, PositionalEncoder
from Sublayers import Norm
import copy
def get_clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
class Encoder(nn.Module):
def __init__(self, vocab_s... | src/Transformer/Models.py | MIT | 2,569 | 3aa48a633934fda322f7e3ad27d6d99f9cf28536 | Python | py | |
import copy
import datetime as dt
import os
import shutil
import typing
from argparse import Namespace
from pathlib import Path
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
import optuna
import optuna.visualization as optv
import pandas as pd
import pytorch_lightning as pl
impor... | mise/dl/rnn_uni_attn.py | MIT | 52,134 | f94a4eb169b1f6144965dc5b250c37e5651981b0 | Python | py | |
import numpy as np
import torch.nn as nn
def train_test_split_sem(dataset, data_dir, im_size=(256, 256), device='cuda'):
train_dataset = dataset(data_dir, im_size=im_size, device=device)
val_dataset = dataset(data_dir, im_size=im_size, device=device)
np.random.seed(11)
indices = np.arange(len(train_d... | bpartis/utils/pretrain.py | MIT | 659 | 7ca7bbc8da93b67cb6548d4f40981dbf351b83e0 | Python | py | |
from argparse import ArgumentParser
import pytorch_lightning as pl
from lit_model import IMDBTransformer
from lit_data import IMDBDataModule
import datasets
datasets.set_caching_enabled(False)
def parse_args(args=None):
parser = ArgumentParser()
# add all the available trainer options to argparse
parse... | defences/dp/classification/lit/lit_main.py | MIT | 7,462 | 3aa4c81c1a439ccc7a4d890ceaa4aae6562579f0 | Python | py | |
import torch
from torch import optim
import argparse
import os
import time
from datetime import datetime
from model import PoincareFM
from model.loss import bpr_loss
from model.metric import AUC
from utils.utils import load_data, batcher, construct_features, set_random_seed, save_results, hit_eval
def train(model, d... | poincarefm_rank.py | MIT | 7,861 | e9bc9337d31a7766061c591c2af09510b4c7a9b0 | Python | py | |
import logging
from torch.optim.lr_scheduler import StepLR, MultiStepLR, ExponentialLR, CosineAnnealingLR
from schedulers.schedulers import WarmUpLR, ConstantLR, PolynomialLR
key2scheduler = {
"constant_lr": ConstantLR,
"poly_lr": PolynomialLR,
"step": StepLR,
"multi_step": MultiStepLR,
"cosine_an... | schedulers/__init__.py | MIT | 1,598 | 3aa4e556bab7ebf81b02402e436089fb3f3acf4f | Python | py | |
import math
import torch
from torch import nn
from anhp.model.xfmr import EncoderLayer, MultiHeadAttention
class XFMRNHPFast(nn.Module):
def __init__(self, dataset, d_model, n_layers, n_head, dropout, d_time, d_inner=128, use_norm=False,
sharing_param_layer=False):
# d_inner only used i... | anhp/model/xfmr_nhp_fast.py | MIT | 13,167 | 3aa4ee5b8b05af447b78eed0a9acad1b7cb023dd | Python | py | |
# Dataloader of Gidaris & Komodakis, CVPR 2018
# Adapted from:
# https://github.com/gidariss/FewShotWithoutForgetting/blob/master/dataloader.py
from __future__ import print_function
import os
import os.path
import numpy as np
import random
import pickle
import json
import math
import torch
import torch.utils.data as ... | data/FC100.py | MIT | 17,150 | dfeb865205d55103460ea97f83bb782069142e36 | Python | py | |
from base import BaseModel
from model.bert import BertModel
from model.lstm import LSTMModel
from model.net_vlad import NetVLAD
from model.txt_embeddings import TxtEmbeddings
from transformers.modeling_bert import BertModel as TxtBertModel
import torch as th
import re
class TxtExtract(BaseModel):
"""extract te... | model/txt_extract.py | Apache-2.0 | 8,502 | 8010763618e084c4acafc8059347b5664d385729 | Python | py | |
import torch
from torch import nn
import torch.nn.functional as F
from torchvision import models
class SegUNetConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, num_layers):
super(SegUNetConvBlock, self).__init__()
layers = [
# nn.UpsamplingBilinear2d(scale_factor=2),
#... | train/networks/DilatedSegUNet_new_version.py | Unlicense | 5,341 | 3aa4fd9ce891b290b4ed4b3fae2ffb0939e3f73e | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from distributions import Categorical, DiagGaussian
from utils import init, init_normc_
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), -1)
class Policy(nn.Module):
def __init__(self, obs_shape, action_spac... | pytorch-a2c-ppo-acktr/model.py | Apache-2.0 | 23,248 | 52c216ca6f43a4befa22082e2533d9cd409003ae | Python | py | |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
"""
A main training script.
This scripts reads a given config file and runs the training or evaluation.
It is an entry point that is made to train standard models in detectron2.
In order to let one script support training of many models,
this sc... | train_net.py | Apache-2.0 | 10,828 | 12980572abe4248c3bbac95d33148c3849e4ef23 | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import operator
from collections import Counter
from distutils.version import LooseVersion
from typing import List
import torch
import torchtext
from pytext.common.constants import VocabMeta
from pytext.utils.data... | pytext/fields/char_field.py | BSD-3-Clause | 4,113 | 24baae631a1ebc1c83d69712660cf6c0faac440a | Python | py | |
from __future__ import print_function
from six.moves import range
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
from PIL import Image
from miscc.config import cfg
from miscc.utils import mkdir_p
from miscc.utils import build_su... | code/trainer.py | MIT | 22,808 | 10397cc3f145154a339cd8489cc8b5cca0792bbf | Python | py | |
import torch
import torch.nn as nn
import numpy as np
from torch.utils.model_zoo import load_url
__all__ = ['VGG', 'VGGAtrous', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn',
'vgg16', 'vgg16_bn', 'vgg19', 'vgg19_bn', 'ssd300_vgg',
'ssd512_vgg']
cfgs = {
11: [64, 'M', 128, 'M', 256, 256, 'M', 51... | cortex/modules/backbones/vgg.py | MIT | 9,230 | 7097018d11fa92512dd2c1d42823020615542cd3 | Python | py | |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Common data processing utilities that are used in a
typical object detection data pipeline.
"""
import logging
import numpy as np
import torch
from fvcore.common.file_io import PathManager
from PIL import Image, ImageOps... | detectron2/data/detection_utils.py | Apache-2.0 | 14,782 | a94b1e273ed03b6b0f76df9160faa19076a886c1 | Python | py | |
#!/usr/bin/env python3
import torch
from ..constraints import Positive
from ..distributions import base_distributions
from .likelihood import _OneDimensionalLikelihood
class BetaLikelihood(_OneDimensionalLikelihood):
r"""
A Beta likelihood for regressing over percentages.
The Beta distribution is param... | gpytorch/likelihoods/beta_likelihood.py | MIT | 2,547 | 3aa5fc1783e00648f4abff9d2b8cb5347e36001c | Python | py | |
# -*- coding: utf-8 -*-
"""
聊天机器人教程
================
**翻译者**: `Antares博士 <http://www.studyai.com/antares>`_
"""
######################################################################
# 在本教程中,我们将探索一个有趣而有意思的用例-递归序列到序列模型(recurrent sequence-to-sequence models)的用例。
# 我们将训练一个简单的聊天机器人使用康奈尔电影剧本-对话语料库
# (`Cornell Movie-Dialo... | beginner_source/chatbot_tutorial.py | BSD-3-Clause | 42,442 | 29f509237c93e15f24997f47ae970a74b267fed4 | Python | py | |
from typing import Optional, Tuple, Union
import torch
from torch.autograd import Function
from torch.cuda.amp import custom_bwd, custom_fwd
import torchsparse.backend
from torchsparse import SparseTensor
from torchsparse.nn import functional as F
from torchsparse.nn.utils import get_kernel_offsets
from torchsparse.u... | torchsparse/nn/functional/conv.py | MIT | 6,255 | 3409d4eafdcbcdfba60b0701a033a13f4b0d391f | Python | py | |
import os
import time
import argparse
import json
import yaml
import torch
from torch.utils.data import DataLoader
from model.tacotron import Tacotron, TacotronLoss
from model.tacotron2 import Tacotron2, Tacotron2Loss
from model.semantic_tacotron2 import Semantic_Tacotron2, Semantic_Tacotron2Loss
from utils.dataset i... | train.py | MIT | 10,981 | 4b32e6740886dd311f3d872524033cdd56735d25 | 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 | 5,002 | 3aa62683dfc89c513dd8b7006033784c83b29d1a | Python | py | |
import torch
import torchio as tio
from ...utils import TorchioTestCase
class TestMask(TorchioTestCase):
"""Tests for :class:`tio.Mask` class."""
def test_single_mask(self):
negated_mask = self.sample_subject.label.data.logical_not()
masked_voxel_indices = negated_mask.nonzero(as_tuple=True)
... | tests/transforms/preprocessing/test_mask.py | Apache-2.0 | 2,399 | f996bafa3bf724ddb917eef60a642f5428cbe8ab | Python | py | |
#!/usr/bin/env python
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
def smooth_l1_loss(bbox_preds, bbox_targets, bbox_inside_weights, bbox_outside_weights, sigma=3.0):
"""as caffe implementation, the bbox_preds and bbox_t... | libs/nets/smooth_l1_loss.py | Apache-2.0 | 824 | 1024e7f49d03b31cd5b68ad17f788315b6987c2d | Python | py | |
from maskrcnn_benchmark.utils.env import setup_environment # noqa F401 isort:skip
import argparse
import os
import torch
from maskrcnn_benchmark.config import cfg
from maskrcnn_benchmark.data import make_data_loader
from maskrcnn_benchmark.solver import make_lr_scheduler
from maskrcnn_benchmark.solver import make_op... | drone_demo/ttrain.py | MIT | 2,132 | a9198d3e8641611d2e69a33e44fccc15dad7cce9 | Python | py | |
__author__ = 'Jiri Fajtl'
__email__ = 'ok1zjf@gmail.com'
__version__= '3.6'
__status__ = "Research"
__date__ = "1/12/2018"
__license__= "MIT License"
import torch
from torchvision import transforms
import numpy as np
import time
import glob
import random
import argparse
import h5py
import json
import torch.nn.init as ... | main_transformer_cat.py | MIT | 18,358 | 3aa6ad9c391125afb7ab5ea455807b3ecd70b081 | Python | py | |
"""
This file will contain the metrics of the framework
"""
import numpy as np
import torch
from scipy import stats
import itertools
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn import metrics
import matplotlib.pyplot as plt
class IOUMetric:
"""
Class to calculate mean-iou us... | utils/metrics.py | MIT | 11,898 | 3aa6aec92055cd6a69ee9e57565f40652b487abb | Python | py | |
import os, sys
import torch
from torch.backends import cudnn
from mmcv import Config
from mmcv.runner import load_checkpoint, save_checkpoint
from tqdm import tqdm
import json
from model import Model
from common.dataset import dataset
from common.models import losses
if __name__ == "__main__":
cfg = ... | image+name_caption_infonce/train.py | Apache-2.0 | 3,102 | 3aa6c97c227c74c6333fe66dde5060d76f5d46b2 | Python | py | |
import torch
import torch.nn as nn
from torch import autograd
from torch.autograd import Variable
def calculate_gradient_penalty(real_imgs, fake_imgs, d, device, lam):
"""Calculates the Wasserstein gradient penalty loss."""
# Get batch size
batch_size = real_imgs.shape[0]
# Generate a random number ... | src/util.py | MIT | 1,174 | 1e0584a2cdecfc3a84b7a5264bbf6687716c3e49 | Python | py | |
# Activation functions
import torch
import torch.nn as nn
import torch.nn.functional as F
# Swish https://arxiv.org/pdf/1905.02244.pdf ---------------------------------------------------------------------------
class Swish(nn.Module): #
@staticmethod
def forward(x):
return x * torch.sigmoid(x)
cla... | lib/core/activations.py | MIT | 2,212 | 24f5a30f021fdf0b639116a8c32d6135a2d16750 | Python | py | |
import numpy as np
import os
del os.environ['MKL_NUM_THREADS']
import torch
import torch.nn as nn
import torch.optim as optim
import sys
''' Device configuration '''
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
''' HYPERPARAMETERS'''
num_steps_to_predict=5
num_steps = 3
modelep = 110... | testbed/lstm_inference.py | Apache-2.0 | 2,257 | 3aa6f231227379a4c6f319f3fdea66f288517b20 | Python | py | |
"""
Module containing all vae losses.
"""
import abc
import math
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch import optim
from .discriminator import Discriminator
from disvae.utils.math import (log_density_gaussian, log_importance_weight_matrix,
ma... | disvae/models/losses.py | MIT | 23,639 | 3aa70e5245f6b44254521a71206efa45d8189141 | Python | py | |
import os
import numpy
import numpy as np
# import open3d as o3d
import torch
import torch.utils.data
import transforms3d
from torch.utils.data import DataLoader
from tqdm import tqdm
from pcrnet.data_utils import ModelNet40Data, RegistrationData
from pcrnet.losses import ChamferDistanceLoss
from pcrnet.models import... | test_pcrnet.py | MIT | 6,275 | a920f55fe2074a68d206da2eb3ebbd3d99fd95a1 | Python | py | |
# coding: utf-8
# Copyright 2019 Hirofumi Inaguma
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import importlib
import logging
import numpy
import pytest
import torch
from test.test_e2e_asr_transformer import run_transformer_copy
from test.test_e2e_asr_transformer import subsequent_mas... | test/test_e2e_st_transformer.py | Apache-2.0 | 5,791 | ff90f83dcb313b789ba6e9e5ea511c390228ce72 | Python | py | |
import torch
import torch.nn as nn
from functools import partial
import torch.nn.functional as F
class Conv2D(nn.Module):
"""
2D convolution with GroupNorm and ELU
Parameters
----------
in_channels : int
Number of input channels
out_channels : int
Number of output channels
... | configs/layers/packnet/layer01.py | MIT | 2,149 | fcee0716b07e3678d1a67cfa6224e9e55acd43f1 | Python | py | |
import os
import glob
import json
import torch
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
from .builder import DATASETS
class DTU(Dataset):
def __init__(self, name, split, data_dir, img_wh, pipeline, sort_key=None):
super(DTU, self).__init__()
self.name=name
... | deep3dmap/datasets/dtu.py | Apache-2.0 | 3,541 | e64c71c5cf2438d556053a9a87475b87c317e359 | Python | py | |
"""
Reproduces RegionLoss from Darknet:
https://github.com/pjreddie/darknet/blob/master/src/region_layer.c
Based off RegionLoss from Lightnet:
https://gitlab.com/EAVISE/lightnet/blob/master/lightnet/network/loss/_regionloss.py
Speedups
[ ] - Preinitialize anchor tensors
"""
import torch
import torch.nn a... | netharn/models/yolo2/light_region_loss.py | Apache-2.0 | 22,934 | 7c90bb4a3d7a08667157b590893443c475bc881e | Python | py | |
"""
perform FGSM-20 attack on AT model
"""
from __future__ import print_function
import os
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torch.autograd import Variable
import torch.optim as optim
from torchvision import datasets, transforms
from models.widere... | pgd_attack_cifar10_copy.py | Apache-2.0 | 6,679 | 6b3019ee960794165211b71b3ae3b1973c81aaab | Python | py | |
import numpy as np
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from scipy.spatial import ConvexHull
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
baselines = ["DP_Kmeans_b... | code/K-means/plots.py | BSD-3-Clause | 1,083 | 3aa7aaf61ef4f41ed8264e6c818753b0a6a14c3c | Python | py | |
# coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | Megatron-LM-v1.1.5-3D_parallelism/megatron/data/gpt2_dataset.py | MIT | 13,326 | 3aa7b705a6d4481b96b361df64b9379387f18b2e | Python | py | |
# This code is built from the PyTorch examples repository: https://github.com/pytorch/vision/tree/master/torchvision/models.
# Copyright (c) 2017 Torch Contributors.
# The Pytorch examples are available under the BSD 3-Clause License.
#
# =================================================================================... | backend/app/server/ml_models/networks/resnet_lpf.py | MIT | 13,202 | f9e34254eadc00e701245d03ffd86c25c114ce3f | Python | py | |
import math
import six
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
# from ..core.workspace import register, serializable
def mish(x):
return x * torch.tanh(F.softplus(x))
def batch_norm(ch,
norm_type='bn',
norm_decay=0.,... | ptstructure/layout/ptppyolov2/ppyolo_utils.py | Apache-2.0 | 8,814 | 4b256771ce0a8752af4be1a5d2a224121a92af59 | Python | py | |
import os
import os.path as osp
import glob
from setuptools import setup, find_packages
import torch
from torch.utils.cpp_extension import BuildExtension
from torch.utils.cpp_extension import CppExtension, CUDAExtension, CUDA_HOME
WITH_CUDA = torch.cuda.is_available() and CUDA_HOME is not None
if os.getenv('FORCE_CUD... | setup.py | MIT | 2,494 | e6434bad7d66e1d5f4a5d893e67edcff59295aa6 | 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... | examples/question-answering/run_squad.py | Apache-2.0 | 39,995 | 3aa7f829362c4b21b7ebd7a4c4a9dbb21517fbf2 | Python | py | |
# *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. 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... | src/waveglow/inference.py | Apache-2.0 | 3,520 | 5f611c137934804e7e4c9f722e9959ba65b8c383 | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import warnings
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import build_conv_layer, build_norm_layer, build_plugin_layer
from mmcv.runner import BaseModule
from mmcv.utils.parrots_wrapper import _BatchNorm
from ..builder import BACKBONES
fro... | mmseg/models/backbones/resnet.py | Apache-2.0 | 25,578 | f9a1ceb4e0a8dee2d8577613cf891f7fde3d37cc | 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
class GumbelVectorQuantizer(nn.Module):
def __init__(
self,
... | fairseq/modules/gumbel_vector_quantizer.py | MIT | 6,773 | e93af6dfb1034af8d3c8eb63a0dcc9e56ff71daf | Python | py | |
import random
import torch
from torch.utils.data import Dataset
class ABCDataset(Dataset):
def __init__(self, data,
context_bars_num=8,
target_bars_num=8,
bos_id=2,
eos_id=3,
is_test=False):
self.notes = []
... | dataset.py | MIT | 1,782 | 70468394c3f19d856e48a361cf2ab0252e56aa34 | Python | py | |
import argparse
import json
import os
import datasets
import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import ModelCheckpoint
from torch.utils.data import DataLoader, Dataset
from transformers import AutoTokenizer, AutoConfig, AutoModelForSeq2SeqLM, set_seed, get_linear_s... | summarization.py | Apache-2.0 | 16,772 | 45f62a65f540c25499b190f56f8c65b8a8282949 | Python | py | |
import torch
import numpy as np
import sklearn.metrics.pairwise
def assign_by_euclidian_at_k(distances, T, k):
"""
X : [nb_samples x nb_features], e.g. 100 x 64 (embeddings)
k : for each sample, assign target labels of k nearest points
"""
# get nearest points
indices = np.argsort(distances,... | evaluation/recall.py | MIT | 1,064 | 1ed32a0aa9fcfdddfd7522cfd4e285a2eac2435e | Python | py | |
import torch
import torch.nn as nn
from torch.autograd import Variable
from torchvision import models
class UpsamplingLayer(nn.Module):
def __init__(self, channels):
super(UpsamplingLayer, self).__init__()
self.layer = nn.Upsample(scale_factor=2)
def forward(self, x):
return self.laye... | isa.p/models.py | MIT | 13,589 | 5e518eecfa640b860aa68e62e2dc0244ac4725ff | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from abc import ABCMeta, abstractmethod
import torch.nn as nn
from detectron2_ofa.layers import ShapeSpec
__all__ = ["Backbone"]
class Backbone(nn.Module, metaclass=ABCMeta):
"""
Abstract base class for network backbones.
"""
de... | detectron2_ofa/modeling/backbone/backbone.py | Apache-2.0 | 2,018 | 5f4ca00653fb47ecfa8af44f01ef007cea19606a | Python | py | |
"""
Generic type & functions for torch.Tensor and np.ndarray
"""
import torch
from torch import Tensor
import numpy as np
from numpy import ndarray
from typing import Tuple, Union, List, TypeVar
TensArr = TypeVar('TensArr', Tensor, ndarray)
def convert(a: TensArr, astype: type) -> TensArr:
if astype == Tenso... | generic.py | MIT | 3,076 | 5eba399454063fa0dd805f75a44aa0a369dbfa0d | Python | py | |
from __future__ import print_function
import argparse
import os
import pickle
import sys
import cv2
import numpy as np
import torch
import vlfeat # calls constructor
from sklearn.cluster import MiniBatchKMeans
from code.utils.cluster.eval_metrics import _hungarian_match, _original_match, \
_acc
from code.utils.se... | code/scripts/segmentation/baselines/kmeans_and_sift.py | MIT | 11,135 | 3aa8a758cf0b7ad165b96cafd3f18d2578d2b98d | Python | py | |
import os
import pdb
import math
import random
import numpy as np
import pickle
import torch
from PIL import Image
from torch.utils.data import Dataset
from pyquaternion import Quaternion
def search_fit(points):
min_x = points[:, 0].min()
max_x = points[:, 0].max()
min_y = points[:, 1].min()
max_y = po... | dataset/dataset_hammer.py | MIT | 9,366 | 3aa8a7cc857212f2c64fbdf79922d37344fb7d2f | Python | py | |
import colorsys
import copy
import os
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
from torch import nn
from torch.autograd import Variable
from torchsummary import summary
from nets.deeplab import DeepLab as deeplab
np.set_printoptions(threshold=np.inf)
#--------------------... | deeplab_predict.py | MIT | 5,589 | 3aa8d345fbeeee7eac6cb11bb1e9ad7e9d2f4df1 | Python | py | |
import torch
import torch.nn as nn
from libs.net.unet_se_ocnet.unet import UNet, BASENET_CHOICES, deep_supervised_criterion
def create(model, basenet, pretrained='imagenet'):
if model == 'unet':
net = UNet(basenet=basenet, pretrained=pretrained)
else:
raise NotImplementedError(model)
net... | libs/net/unet_se_ocnet/__init__.py | MIT | 842 | 3aa8de24f93238e5cbb2dd0f84153ce699785076 | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
def cross_entropy(y, target, mask=None):
if target.ndim == 1: # for hard label
loss = F.cross_entropy(y, target, reduction="none")
else:
loss = -(target * F.log_softmax(y, 1)).sum(1)
if mask is not None:
loss = mask * loss
... | kf_d3m_primitives/semi_supervised/tabular_semi_supervised/cross_entropy.py | Apache-2.0 | 488 | 422ebb2b932a016fcaef47949d29b006371a0a6d | Python | py | |
__all__ = ["StateNoveltyEvaluator"]
from dataclasses import dataclass
from typing import Sequence, Optional, Set
import torch
import utils
from datasets import DialogDataset
from utils import TensorMap
from ...evaluator import DialogEvaluator
@dataclass
class StateNoveltyEvaluator(DialogEvaluator):
dataset: Di... | evaluators/dialog/state/novel.py | MIT | 1,493 | 5fbd4e5cafed2f9d565da901c7def5fbf0ac3a6f | Python | py | |
import json
import os
import torch
import pprint
import numpy as np
import pandas as pd
from importlib import import_module
from scipy.sparse import csr_matrix
from common.eval_tools import (train_classifier, fetch_scores_gradually, fetch_scores)
from common import encode, util
from ..train import init_models, embe... | src/models/vq-byol/evaluate/linear_probe.py | MIT | 5,392 | 3aa8f4c620a8b403a11bd4205e0da8182ec40f88 | Python | py | |
import argparse
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
import pickle
import numpy as np
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence
from torchvision import transforms
from data_loader import get_loader
from model import EncoderCNN, DecoderRNN
from build_vocab imp... | STREAM/train.py | MIT | 4,681 | 6b3a5c11d4794c1bb0d338fad9188498d6bd7966 | Python | py | |
import torch
import torch.nn as nn
from collections import OrderedDict
class ProtoConvNet(nn.Module):
def __init__(self):
super(ProtoConvNet, self).__init__()
self.act = nn.ReLU(inplace=True)
self.conv1 = nn.Conv2d(in_channels=3, out_channels=64, kernel_size=(3, 3), stride=1, padding=1)
... | models.py | MIT | 1,652 | 1e8da95b31ad2b409c121ff1e774932a13c95de9 | Python | py | |
from typing import Union
from torch import nn
from torch.utils import data
from torchutils.param import Param
__all__ = [
"DataLoader",
"Dataset",
"Module",
"get_dataloader",
"get_dataset",
"get_module",
"get_named_dataloaders",
"get_named_datasets",
"get_named_modules",
]
_datal... | torchutils/factory.py | MIT | 4,551 | 3aa91c7574cabfe04869054f9898204c04467efe | Python | py | |
import torch
from torch.utils.data import Dataset, DataLoader, Sampler
import openslide
import random
import numpy as np
from read_roi import read_roi_zip
from skimage.draw import polygon
from PIL import Image, ImageSequence
class RoiImage(Dataset):
def __init__(self, path, size=(226, 226), transform=lambda x: x):
... | torchsupport/data/roi_image.py | MIT | 918 | 459301e5d7c2c248a3e925589fd6b7bece5669bd | Python | py | |
# coding=utf-8
# Copyright 2021 The I-BERT Authors (Sehoon Kim, Amir Gholami, Zhewei Yao,
# Michael Mahoney, Kurt Keutzer - UC Berkeley) and The HuggingFace Inc. team.
# Copyright (c) 20121, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use t... | src/transformers/models/ibert/modeling_ibert.py | Apache-2.0 | 55,171 | 3aa936ba6acf4e2fdf303428916f9fde7862e07c | Python | py | |
from torch.utils.model_zoo import load_url
from ..core import FaceDetector
from ...utils import load_file_from_url
from .net_blazeface import BlazeFace
from .detect import *
models_urls = {
'blazeface_weights': 'https://github.com/hollance/BlazeFace-PyTorch/blob/master/blazeface.pth?raw=true',
'bla... | face_alignment/detection/blazeface/blazeface_detector.py | BSD-3-Clause | 1,984 | 802852a5ae7a0578555d6942c8549aee483852ee | Python | py | |
"""
Based on rllab's logger.
https://github.com/rll/rllab
"""
from enum import Enum
from contextlib import contextmanager
import numpy as np
import os
import os.path as osp
import sys
import datetime
import dateutil.tz
import csv
import json
import pickle
import errno
import torch
from rlkit.core.tabulate import tabu... | rlkit/core/logging.py | MIT | 10,305 | 3aa9497051a140ed8bdc5de04be0b06cd7261669 | Python | py | |
from typing import Iterable
import torch
def polyak_update(
params: Iterable[torch.nn.Parameter],
target_params: Iterable[torch.nn.Parameter],
tau: float,
):
with torch.no_grad():
# zip does not raise an exception if length of parameters does not match.
for param, target_param in zip(... | code/agent/deep/polyak_update.py | MIT | 475 | f9e5709a7b41f869ba0bc3e13e23b2b4073f6764 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.