repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
sharpDARTS | sharpDARTS-master/cnn/genotypes.py | from collections import namedtuple
Genotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat layout')
# Primitives for the dilation, sep_conv, flood, and choke 3x3 only search space
PRIMITIVES = [
'none',
'max_pool_3x3',
# 'avg_pool_3x3',
'skip_connect',
'sep_conv_3x3',
# 's... | 81,512 | 126.165367 | 5,998 | py |
sharpDARTS | sharpDARTS-master/cnn/operations.py | import torch
import torch.nn as nn
# Simplified new version based on actual results, partially adapted from PNASNet https://github.com/chenxi116/PNASNet.pytorch
OPS = {
'none': lambda C_in, C_out, stride, affine, C_mid=None: Zero(stride),
'avg_pool_3x3': lambda C_in, C_out, stride, affine, C_mid=None: ResizablePoo... | 9,428 | 46.38191 | 161 | py |
sharpDARTS | sharpDARTS-master/cnn/genotype_extractor.py | '''
This file includes code from the DARTS and sharpDARTS https://arxiv.org/abs/1903.09900 papers.
'''
import numpy as np
import genotypes
def parse_cell(weights, primitives, steps=4, skip_primitive='none'):
""" Take a weight array and turn it into a list of pairs (primitive_string, node_index).
"""
gene... | 7,601 | 54.086957 | 148 | py |
sharpDARTS | sharpDARTS-master/rnn/test.py | import argparse
import os, sys
import time
import math
import numpy as np
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import data
import model
from utils import batchify, get_batch, repackage_hidden, create_exp_dir, save_checkpoint
parser = argparse.ArgumentParser(description='PyTorch Pen... | 5,048 | 40.385246 | 118 | py |
sharpDARTS | sharpDARTS-master/rnn/architect.py | import torch
import numpy as np
import torch.nn as nn
from torch.autograd import Variable
def _concat(xs):
return torch.cat([x.view(-1) for x in xs])
def _clip(grads, max_norm):
total_norm = 0
for g in grads:
param_norm = g.data.norm(2)
total_norm += param_norm ** 2
total_norm = total_... | 4,003 | 34.122807 | 132 | py |
sharpDARTS | sharpDARTS-master/rnn/utils.py | import torch
import torch.nn as nn
import os, shutil
import numpy as np
from torch.autograd import Variable
def repackage_hidden(h):
if type(h) == Variable:
return Variable(h.data)
else:
return tuple(repackage_hidden(v) for v in h)
def batchify(data, bsz, args):
nbatch = data.size(0) // ... | 2,955 | 30.446809 | 137 | py |
sharpDARTS | sharpDARTS-master/rnn/model.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from genotypes import STEPS
from utils import mask2d
from utils import LockedDropout
from utils import embedded_dropout
from torch.autograd import Variable
INITRANGE = 0.04
class DARTSCell(nn.Module):
def __init__(self, ninp, nhid, dro... | 5,148 | 30.981366 | 102 | py |
sharpDARTS | sharpDARTS-master/rnn/data.py | import os
import torch
from collections import Counter
class Dictionary(object):
def __init__(self):
self.word2idx = {}
self.idx2word = []
self.counter = Counter()
self.total = 0
def add_word(self, word):
if word not in self.word2idx:
self.idx2word.append(... | 4,005 | 30.054264 | 80 | py |
sharpDARTS | sharpDARTS-master/rnn/model_search.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from genotypes import PRIMITIVES, STEPS, CONCAT, Genotype
from torch.autograd import Variable
from collections import namedtuple
from model import DARTSCell, RNNModel
class DARTSCellSearch(DARTSCell):
def __init__(self, ninp, nhid, dropouth, dropou... | 3,278 | 32.804124 | 125 | py |
sharpDARTS | sharpDARTS-master/rnn/train_search.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... | 12,639 | 43.041812 | 132 | py |
sharpDARTS | sharpDARTS-master/rnn/train.py | import os
import gc
import sys
import glob
import time
import math
import numpy as np
import torch
import torch.nn as nn
import logging
import argparse
import genotypes
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import data
import model
from torch.autograd import Variable
from utils import ba... | 13,900 | 42.037152 | 141 | py |
lenspack | lenspack-master/docs/source/conf.py | # -*- coding: utf-8 -*-
#
# package_name documentation build configuration file, created by
# sphinx-quickstart on Mon Oct 24 16:46:22 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
... | 12,182 | 30.158568 | 100 | py |
RCA | RCA-main/data_process.py | from six.moves import cPickle as pickle
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.impute import SimpleImputer
import torch as torch
from torch.utils.data import Dataset
def load_dict(filename_):
with open(filename_, "rb") as f:
ret_di = pickle.load(f)
return ret_di... | 1,721 | 27.7 | 75 | py |
RCA | RCA-main/train_DAGMM.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import os
import argparse
import time
import datetime
import torch.utils.data as data
from torch.autograd import grad
from torch.autograd import Variable
from models.DAGMM import DaGMM
from data_process import RealDataset
import matpl... | 12,923 | 39.012384 | 138 | py |
RCA | RCA-main/trainSVDD.py | import torch as torch
import os
import torch.utils.data as data
import numpy as np
from tqdm import tqdm
import argparse
from models.SVDD import SVDD, SVMLoss
from data_process import RealDataset
"""Deep One Class SVM"""
class Solver_SVDD:
def __init__(
self,
data_name,
start_ratio=0.0,... | 9,095 | 32.441176 | 112 | py |
RCA | RCA-main/loss.py | import torch.nn as nn
import torch as torch
import torch.nn.functional as F
class Loss_Knn(nn.Module):
def __init__(self, margin):
self.margin = margin
super(Loss_Knn, self).__init__()
def forward(self, z, z_nn):
n_batch, n_nn, d = z_nn.shape
z = z.unsqueeze(dim=1).repeat(1, n... | 2,952 | 32.179775 | 73 | py |
RCA | RCA-main/utils.py | import os
import torch
from torch.autograd import Variable
def to_var(x, volatile=False):
if torch.cuda.is_available():
x = x.cuda()
return Variable(x, volatile=volatile)
def mkdir(directory):
if not os.path.exists(directory):
os.makedirs(directory)
| 282 | 17.866667 | 41 | py |
RCA | RCA-main/trainRCAMulti.py | import torch as torch
import os
import random
import torch.utils.data as data
import numpy as np
from tqdm import tqdm
import argparse
from models.RCA import SingleAE
from data_process import RealDataset
class Solver_RCA_Multi:
def __init__(
self,
data_name,
n_member=2,
start_rati... | 12,857 | 36.817647 | 113 | py |
RCA | RCA-main/trainRCA.py | import torch as torch
import os
import torch.utils.data as data
import numpy as np
from tqdm import tqdm
import argparse
from models.RCA import AE
from data_process import RealDataset
class Solver_RCA:
def __init__(
self,
data_name,
hidden_dim=128, # number of hidden neurons in RCA
... | 9,369 | 35.177606 | 152 | py |
RCA | RCA-main/models/SVDD.py | import torch.nn as nn
import torchvision.models as models
import torch.nn.functional as F
import torch as torch
class SVDD(nn.Module):
def __init__(self, input_dim, hidden_dim, z_dim):
super(SVDD, self).__init__()
self.c1 = torch.zeros(z_dim)
self.R1 = None
self.encoder = nn.Sequen... | 1,701 | 26.901639 | 64 | py |
RCA | RCA-main/models/AE_Coteaching.py | import torch.nn as nn
import torchvision.models as models
import torch.nn.functional as F
import torch as torch
class SingleAE(nn.Module):
def __init__(self, input_dim, hidden_dim, z_dim):
super(SingleAE, self).__init__()
self.encoder1 = nn.Sequential(
nn.Linear(input_dim, hidden_dim),... | 2,680 | 29.123596 | 53 | py |
RCA | RCA-main/models/RCA.py | import torch.nn as nn
import torchvision.models as models
import torch.nn.functional as F
import torch as torch
class SingleAE(nn.Module):
def __init__(self, input_dim, hidden_dim, z_dim):
super(SingleAE, self).__init__()
self.encoder1 = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
... | 2,686 | 27.284211 | 53 | py |
RCA | RCA-main/models/DAGMM.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import torchvision
from torch.autograd import Variable
import itertools
from utils import *
class Cholesky(torch.autograd.Function):
def forward(ctx, a):
l = torch.cholesky(a, False)
ctx.save_for_backward(l)
... | 6,589 | 31.623762 | 120 | py |
LKD-Net | LKD-Net-main/test.py | import os
import argparse
import torch
import torch.nn.functional as F
from pytorch_msssim import ssim
from torch.utils.data import DataLoader
from collections import OrderedDict
from utils import AverageMeter, write_img, chw_to_hwc
from datasets.loader import PairLoader
from models import *
parser = argparse.Argumen... | 4,023 | 33.689655 | 102 | py |
LKD-Net | LKD-Net-main/train.py | import os
import argparse
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.cuda.amp import autocast, GradScaler
from torch.utils.data import DataLoader
from tensorboardX import SummaryWriter
from tqdm import tqdm
import logging
import time
import shutil
import torch.backends.cud... | 8,740 | 35.881857 | 116 | py |
LKD-Net | LKD-Net-main/models/LKD.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from torch.nn.init import _calculate_fan_in_and_fan_out
from timm.models.layers import trunc_normal_
class LayerNorm(nn.Module):
def __init__(self, dim, eps=1e-5):
super(LayerNorm, self).__init__()
self.eps = eps
... | 9,738 | 30.115016 | 119 | py |
LKD-Net | LKD-Net-main/datasets/loader.py | import os
import random
import numpy as np
import cv2
from torch.utils.data import Dataset
from utils import hwc_to_chw, read_img
import torchvision.transforms as tfs
def augment(imgs=[], size=256, edge_decay=0., only_h_flip=False):
H, W, _ = imgs[0].shape
Hc, Wc = [size, size]
# simple re-weight for th... | 3,568 | 31.445455 | 122 | py |
LKD-Net | LKD-Net-main/utils/data_parallel.py | from torch.nn.parallel import DataParallel
import torch
from torch.nn.parallel._functions import Scatter
from torch.nn.parallel.parallel_apply import parallel_apply
def scatter(inputs, target_gpus, chunk_sizes, dim=0):
r"""
Slices tensors into approximately equal chunks and
distributes them across given GP... | 4,069 | 38.514563 | 84 | py |
LKD-Net | LKD-Net-main/utils/utils.py | from pathlib import Path
import os
import logging
import shutil
import time
import torch
from thop import profile
from fvcore.nn import FlopCountAnalysis
import numpy as np
def setup_logger(final_output_dir, phase):
time_str = time.strftime('%Y-%m-%d-%H-%M')
log_file = '{}_{}.txt'.format(phase, time_str)
... | 4,149 | 30.923077 | 100 | py |
UA-MT | UA-MT-master/code/train_LA.py | import os
import sys
from tqdm import tqdm
from tensorboardX import SummaryWriter
import shutil
import argparse
import logging
import time
import random
import numpy as np
import torch
import torch.optim as optim
from torchvision import transforms
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
fr... | 6,569 | 41.115385 | 139 | py |
UA-MT | UA-MT-master/code/test_util.py | import h5py
import math
import nibabel as nib
import numpy as np
from medpy import metric
import torch
import torch.nn.functional as F
from tqdm import tqdm
def test_all_case(net, image_list, num_classes, patch_size=(112, 112, 80), stride_xy=18, stride_z=4, save_result=True, test_save_path=None, preproc_fn=None):
... | 4,596 | 38.290598 | 157 | py |
UA-MT | UA-MT-master/code/train_LA_meanteacher_certainty.py | import os
import sys
from tqdm import tqdm
from tensorboardX import SummaryWriter
import shutil
import argparse
import logging
import time
import random
import numpy as np
import torch
import torch.optim as optim
from torchvision import transforms
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
fr... | 12,308 | 47.652174 | 129 | py |
UA-MT | UA-MT-master/code/train_LA_meanteacher_certainty_unlabel.py | import os
import sys
from tqdm import tqdm
from tensorboardX import SummaryWriter
import shutil
import argparse
import logging
import time
import random
import numpy as np
import torch
import torch.optim as optim
from torchvision import transforms
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
fr... | 12,471 | 47.529183 | 130 | py |
UA-MT | UA-MT-master/code/test_LA.py | import os
import argparse
import torch
from networks.vnet import VNet
from test_util import test_all_case
parser = argparse.ArgumentParser()
parser.add_argument('--root_path', type=str, default='../data/2018LA_Seg_Training Set/', help='Name of Experiment')
parser.add_argument('--model', type=str, default='vnet_superv... | 1,576 | 36.547619 | 115 | py |
UA-MT | UA-MT-master/code/networks/vnet.py | import torch
from torch import nn
import torch.nn.functional as F
class ConvBlock(nn.Module):
def __init__(self, n_stages, n_filters_in, n_filters_out, normalization='none'):
super(ConvBlock, self).__init__()
ops = []
for i in range(n_stages):
if i==0:
input_cha... | 9,073 | 35.58871 | 110 | py |
UA-MT | UA-MT-master/code/dataloaders/utils.py | import os
import torch
import numpy as np
import torch.nn as nn
import matplotlib.pyplot as plt
from skimage import measure
import scipy.ndimage as nd
def recursive_glob(rootdir='.', suffix=''):
"""Performs recursive glob with given suffix and rootdir
:param rootdir is the root directory
:param su... | 6,729 | 30.302326 | 144 | py |
UA-MT | UA-MT-master/code/dataloaders/la_heart.py | import os
import torch
import numpy as np
from glob import glob
from torch.utils.data import Dataset
import h5py
import itertools
from torch.utils.data.sampler import Sampler
class LAHeart(Dataset):
""" LA Dataset """
def __init__(self, base_dir=None, split='train', num=None, transform=None):
self._bas... | 7,965 | 37.483092 | 130 | py |
UA-MT | UA-MT-master/code/utils/losses.py | import torch
from torch.nn import functional as F
import numpy as np
def dice_loss(score, target):
target = target.float()
smooth = 1e-5
intersect = torch.sum(score * target)
y_sum = torch.sum(target * target)
z_sum = torch.sum(score * score)
loss = (2 * intersect + smooth) / (z_sum + y_sum + s... | 3,141 | 31.061224 | 99 | py |
UA-MT | UA-MT-master/code/utils/util.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.
#
import os
import pickle
import numpy as np
import torch
from torch.utils.data.sampler import Sampler
import networks
def load... | 3,449 | 27.75 | 85 | py |
pymdptoolbox | pymdptoolbox-master/docs/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Python Markov Decision Process Toolbox documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 26 16:15:31 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration ... | 10,423 | 31.073846 | 112 | py |
OpenAttack | OpenAttack-master/examples/adversarial_training.py | '''
This example code shows how to conduct adversarial training to improve the robustness of a sentiment analysis model.
The most important part is the "attack()" function, in which adversarial examples are easily generated with an API "attack_eval.generate_adv()"
'''
import OpenAttack
import torch
import datasets
imp... | 7,284 | 35.243781 | 164 | py |
OpenAttack | OpenAttack-master/examples/multiprocess_eval.py | '''
This example code shows how to using multiprocessing to accelerate adversarial attacks
'''
import OpenAttack
import datasets
def dataset_mapping(x):
return {
"x": x["sentence"],
"y": 1 if x["label"] > 0.5 else 0,
}
def main():
victim = OpenAttack.loadVictim("BERT.SST")
# V... | 1,217 | 37.0625 | 122 | py |
OpenAttack | OpenAttack-master/examples/workflow.py | '''
This example code shows how to how to use the PWWS attack model to attack BERT on the SST-2 dataset.
'''
import OpenAttack
import datasets
def dataset_mapping(x):
return {
"x": x["sentence"],
"y": 1 if x["label"] > 0.5 else 0,
}
def main():
victim = OpenAttack.loadVictim("BER... | 1,266 | 38.59375 | 149 | py |
OpenAttack | OpenAttack-master/docs/source/conf.py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | 2,248 | 33.075758 | 98 | py |
OpenAttack | OpenAttack-master/OpenAttack/metric/algorithms/sentence_sim.py | from .base import AttackMetric
from ...tags import *
class SentenceSim(AttackMetric):
NAME = "Sentence Similarity"
TAGS = { TAG_English }
def __init__(self):
"""
:Pakcage Requirements:
* sentence_transformers
:Language: english
"""
from sentence_t... | 1,142 | 29.078947 | 109 | py |
OpenAttack | OpenAttack-master/OpenAttack/metric/algorithms/levenshtein.py | from typing import List
from .base import AttackMetric
import torch
from ...text_process.tokenizer import Tokenizer
class Levenshtein(AttackMetric):
NAME = "Levenshtein Edit Distance"
def __init__(self, tokenizer : Tokenizer) -> None:
"""
Args:
tokenizer: A tokenizer that will... | 1,727 | 32.230769 | 156 | py |
OpenAttack | OpenAttack-master/OpenAttack/metric/algorithms/gptlm.py | import math
import transformers
from ...tags import *
from .base import AttackMetric
class GPT2LM(AttackMetric):
NAME = "Fluency (ppl)"
TAGS = { TAG_English }
def __init__(self):
"""
Language Models are Unsupervised Multitask Learners.
`[pdf] <https://d4mucfpksywv.cloudfront.net/b... | 1,644 | 31.254902 | 108 | py |
OpenAttack | OpenAttack-master/OpenAttack/metric/algorithms/usencoder.py | from .base import AttackMetric
import numpy as np
from ...tags import *
from ...data_manager import DataManager
## TODO use a pytorch model instead
class UniversalSentenceEncoder(AttackMetric):
NAME = "Semantic Similarity"
TAGS = { TAG_English }
def __init__(self):
"""
Universal Sentenc... | 1,410 | 28.395833 | 90 | py |
OpenAttack | OpenAttack-master/OpenAttack/attackers/bert_attack/__init__.py | import copy
from typing import List, Optional, Union
import numpy as np
from transformers import BertConfig, BertTokenizerFast, BertForMaskedLM
import torch
from ..classification import ClassificationAttacker, Classifier, ClassifierGoal
from ...tags import TAG_English, Tag
from ...exceptions import WordNotInDictionar... | 12,769 | 40.193548 | 144 | py |
OpenAttack | OpenAttack-master/OpenAttack/attackers/bae/__init__.py | from typing import List, Optional
from ...data_manager import DataManager
from ..classification import ClassificationAttacker, Classifier, ClassifierGoal
from ...metric import UniversalSentenceEncoder
from ...utils import check_language
from ...tags import Tag, TAG_English
from ...attack_assist.filter_words import get_... | 16,398 | 44.052198 | 166 | py |
OpenAttack | OpenAttack-master/OpenAttack/attackers/geometry/__init__.py | import numpy as np
import torch
import torch.nn as nn
import copy
from typing import List, Optional
from ...text_process.tokenizer import Tokenizer, get_default_tokenizer
from ...attack_assist.substitute.word import WordSubstitute, get_default_substitute
from ...utils import get_language, check_language, language_by_na... | 53,860 | 40.178135 | 156 | py |
OpenAttack | OpenAttack-master/OpenAttack/attackers/gan/__init__.py | import numpy as np
from copy import deepcopy
from ..classification import ClassificationAttacker, Classifier, ClassifierGoal
from ...data_manager import DataManager
from ...tags import TAG_English, Tag
import torch
def get_min(indices_adv1, d):
d1 = deepcopy(d)
idx_adv1 = indices_adv1[np.argmin(d1[indices_adv... | 7,259 | 37.823529 | 143 | py |
OpenAttack | OpenAttack-master/OpenAttack/attackers/scpn/models.py | import torch
import torch.nn as nn
from torch.nn.utils.rnn import pad_packed_sequence as unpack
from torch.nn.utils.rnn import pack_padded_sequence as pack
import numpy as np
class ParseNet(nn.Module):
def __init__(self, d_nt, d_hid, len_voc):
super(ParseNet, self).__init__()
self.d_nt = d_nt
... | 23,359 | 43.495238 | 175 | py |
OpenAttack | OpenAttack-master/OpenAttack/attackers/scpn/__init__.py |
from typing import List, Optional
from ...text_process.tokenizer import Tokenizer, get_default_tokenizer
from ...text_process.constituency_parser import ConstituencyParser, get_default_constituency_parser
from ...utils import check_language
from ...tags import TAG_English, Tag
from ...data_manager import DataManager
... | 8,934 | 39.986239 | 185 | py |
OpenAttack | OpenAttack-master/OpenAttack/victim/classifiers/transformers.py | import numpy as np
from .base import Classifier
from ...utils import language_by_name,get_language, HookCloser
from ...text_process.tokenizer import TransformersTokenizer
from ...attack_assist.word_embedding import WordEmbedding
import transformers
import torch
from ...tags import TAG_English
class TransformersClassif... | 6,612 | 37.447674 | 165 | py |
OpenAttack | OpenAttack-master/OpenAttack/attack_assist/substitute/word/embed_based.py | from typing import Dict, Optional
from .base import WordSubstitute
from ....exceptions import WordNotInDictionaryException
import torch
from ....tags import *
DEFAULT_CONFIG = {"cosine": False}
class EmbedBasedSubstitute(WordSubstitute):
def __init__(self, word2id : Dict[str, int], embedding : torch.Tensor,... | 2,227 | 31.764706 | 129 | py |
OpenAttack | OpenAttack-master/OpenAttack/attack_assist/substitute/word/english_word2vec.py | from .embed_based import EmbedBasedSubstitute
from ....data_manager import DataManager
from ....tags import TAG_English
import torch
class Word2VecSubstitute(EmbedBasedSubstitute):
TAGS = { TAG_English }
def __init__(self, cosine = False, k = 50, threshold = 0.5, device = None):
"""
English w... | 1,109 | 30.714286 | 105 | py |
OpenAttack | OpenAttack-master/OpenAttack/attack_assist/substitute/word/english_glove.py | import torch
from .embed_based import EmbedBasedSubstitute
from ....data_manager import DataManager
from ....tags import TAG_English
class GloveSubstitute(EmbedBasedSubstitute):
TAGS = { TAG_English }
def __init__(self, cosine = False, k = 50, threshold = 0.5, device = None):
"""
English wo... | 1,184 | 31.027027 | 105 | py |
OpenAttack | OpenAttack-master/OpenAttack/attack_assist/substitute/word/english_counterfit.py | from .embed_based import EmbedBasedSubstitute
from ....data_manager import DataManager
from ....tags import TAG_English
import torch
class CounterFittedSubstitute(EmbedBasedSubstitute):
TAGS = { TAG_English }
def __init__(self, cosine : bool = False, k : int = 50, threshold : float = 0.5, device = None):
... | 1,228 | 33.138889 | 105 | py |
OpenAttack | OpenAttack-master/OpenAttack/attack_assist/substitute/word/chinese_word2vec.py | from typing import Union
from .embed_based import EmbedBasedSubstitute
from ....data_manager import DataManager
from ....tags import TAG_Chinese
import torch
class ChineseWord2VecSubstitute(EmbedBasedSubstitute):
TAGS = { TAG_Chinese }
def __init__(self, cosine : bool = False, threshold : float = 0.5, k : in... | 1,226 | 33.083333 | 133 | py |
OpenAttack | OpenAttack-master/OpenAttack/data/victim_albert_ag.py | """
:type: OpenAttack.utils.AlbertClassifier
:Size: 788.697MB
:Package Requirements:
* transformers
* pytorch
Pretrained ALBERT model on AG-4 dataset. See :py:data:`Dataset.AG` for detail.
"""
from OpenAttack.utils import make_zip_downloader
NAME = "Victim.ALBERT.AG"
URL = "/TAADToolbox/victim/albert_ag.zip... | 749 | 31.608696 | 123 | py |
OpenAttack | OpenAttack-master/OpenAttack/data/victim_roberta_imdb.py | """
:type: OpenAttack.utils.RobertaClassifier
:Size: 1.18GB
:Package Requirements:
* transformers
* pytorch
Pretrained ROBERTA model on IMDB dataset. See :py:data:`Dataset.IMDB` for detail.
"""
from OpenAttack.utils import make_zip_downloader
NAME = "Victim.ROBERTA.IMDB"
URL = "/TAADToolbox/victim/roberta_i... | 762 | 30.791667 | 123 | py |
OpenAttack | OpenAttack-master/OpenAttack/data/victim_roberta_ag.py | """
:type: OpenAttack.utils.RobertaClassifier
:Size: 1.22GB
:Package Requirements:
* transformers
* pytorch
Pretrained ROBERTA model on AG-4 dataset. See :py:data:`Dataset.AG` for detail.
"""
from OpenAttack.utils import make_zip_downloader
NAME = "Victim.ROBERTA.AG"
URL = "/TAADToolbox/victim/roberta_ag.zi... | 752 | 30.375 | 123 | py |
OpenAttack | OpenAttack-master/OpenAttack/data/victim_roberta_sst.py | """
:type: OpenAttack.utils.RobertaClassifier
:Size: 1.18GB
:Package Requirements:
* transformers
* pytorch
Pretrained ROBERTA model on SST-2 dataset. See :py:data:`Dataset.SST` for detail.
"""
from OpenAttack.utils import make_zip_downloader
NAME = "Victim.ROBERTA.SST"
URL = "/TAADToolbox/victim/roberta_ss... | 760 | 30.708333 | 123 | py |
OpenAttack | OpenAttack-master/OpenAttack/data/victim_albert_imdb.py | """
:type: OpenAttack.utils.AlbertClassifier
:Size: 788.662MB
:Package Requirements:
* transformers
* pytorch
Pretrained ALBERT model on IMDB dataset. See :py:data:`Dataset.IMDB` for detail.
"""
from OpenAttack.utils import make_zip_downloader
NAME = "Victim.ALBERT.IMDB"
URL = "/TAADToolbox/victim/albert_im... | 760 | 30.708333 | 123 | py |
OpenAttack | OpenAttack-master/OpenAttack/data/translation_models.py | """
:type: dict
:Size: 1.22GB
:Package Requirements:
* **pytorch**
Pretrained translation models. See :py:data:`TranslationModels` for detail.
`[code] <https://github.com/OpenNMT/OpenNMT-py>`__
`[page] <https://opennmt.net/>`__
"""
from OpenAttack.utils import make_zip_downloader
import os
NAME = "AttackAssist.... | 742 | 26.518519 | 117 | py |
OpenAttack | OpenAttack-master/OpenAttack/data/victim_albert_sst.py | """
:type: OpenAttack.utils.AlbertClassifier
:Size: 788.66MB
:Package Requirements:
* transformers
* pytorch
Pretrained ALBERT model on SST-2 dataset. See :py:data:`Dataset.SST` for detail.
"""
from OpenAttack.utils import make_zip_downloader
NAME = "Victim.ALBERT.SST"
URL = "/TAADToolbox/victim/albert_sst.... | 757 | 30.583333 | 123 | py |
OpenAttack | OpenAttack-master/OpenAttack/data/gan.py | """
:type: tuple
:Size: 55.041MB
:Package Requirements:
* **pytorch**
Pretrained GAN model on SNLI dataset used in :py:class:`.GANAttacker`. See :py:class:`.GANAttacker` for detail.
"""
import os
from OpenAttack.utils import make_zip_downloader
import torch
import torch.nn as nn
import torch.nn.functional as F
fr... | 25,710 | 38.253435 | 111 | py |
OpenAttack | OpenAttack-master/OpenAttack/data/victim_xlnet_imdb.py | """
:type: OpenAttack.utils.XlnetClassifier
:Size: 1.25GB
:Package Requirements:
* transformers
* pytorch
Pretrained XLNET model on IMDB dataset. See :py:data:`Dataset.IMDB` for detail.
"""
from OpenAttack.utils import make_zip_downloader
NAME = "Victim.XLNET.IMDB"
URL = "/TAADToolbox/victim/xlnet_imdb.zip"... | 746 | 30.125 | 123 | py |
OpenAttack | OpenAttack-master/OpenAttack/data/victim_xlnet_sst.py | """
:type: OpenAttack.utils.XlnetClassifier
:Size: 1.25GB
:Package Requirements:
* transformers
* pytorch
Pretrained XLNET model on SST-2 dataset. See :py:data:`Dataset.SST` for detail.
"""
from OpenAttack.utils import make_zip_downloader
NAME = "Victim.XLNET.SST"
URL = "/TAADToolbox/victim/xlnet_sst.zip"
D... | 745 | 28.84 | 123 | py |
OpenAttack | OpenAttack-master/OpenAttack/data/victim_bert_amazon_zh.py | """
:type: OpenAttack.utils.BertClassifier
:Size: 992.75 MB
:Package Requirements:
* transformers
* pytorch
Pretrained BERT model on Amazon Reviews (Chinese) dataset.
"""
from OpenAttack.utils import make_zip_downloader
import os
NAME = "Victim.BERT.AMAZON_ZH"
URL = "/TAADToolbox/victim/bert_amazon_reviews_... | 771 | 28.692308 | 123 | py |
OpenAttack | OpenAttack-master/OpenAttack/data/victim_xlnet_ag.py | """
:type: OpenAttack.utils.XlnetClassifier
:Size: 1.25GB
:Package Requirements:
* transformers
* pytorch
Pretrained XLNET model on AG-4 dataset. See :py:data:`Dataset.AG` for detail.
"""
from OpenAttack.utils import make_zip_downloader
NAME = "Victim.XLNET.AG"
URL = "/TAADToolbox/victim/xlnet_ag.zip"
DOWNL... | 736 | 29.708333 | 123 | py |
OpenAttack | OpenAttack-master/OpenAttack/data/sgan.py | """
:type: tuple
:Size: 54.854MB
:Package Requirements:
* **pytorch**
Pretrained GAN model on SST-2 dataset used in :py:class:`.GANAttacker`. See :py:class:`.GANAttacker` for detail.
"""
from OpenAttack.utils import make_zip_downloader
NAME = "AttackAssist.SGAN"
URL = "/TAADToolbox/SGNAE.zip"
DOWNLOAD = make_zip... | 25,824 | 38.128788 | 112 | py |
OpenAttack | OpenAttack-master/OpenAttack/data/victim_bert.py | """
:type: OpenAttack.utils.BertClassifier
:Size: 386.584MB
:Package Requirements:
* transformers
* pytorch
Pretrained BERT model on SST-2 dataset. See :py:data:`Dataset.SST` for detail.
"""
from OpenAttack.utils import make_zip_downloader
NAME = "Victim.BERT.SST"
URL = "/TAADToolbox/victim/bert_sst.zip"
DO... | 749 | 29 | 123 | py |
espnet | espnet-master/setup.py | #!/usr/bin/env python3
"""ESPnet setup script."""
import os
from setuptools import find_packages, setup
requirements = {
"install": [
"setuptools>=38.5.1",
"packaging",
"configargparse>=1.2.1",
"typeguard==2.13.3",
"humanfriendly",
"scipy>=1.4.1",
"fileloc... | 5,217 | 30.817073 | 94 | py |
espnet | espnet-master/tools/check_install.py | #!/usr/bin/env python3
"""Script to check whether the installation is done correctly."""
# Copyright 2018 Nagoya University (Tomoki Hayashi)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import importlib
import re
import shutil
import subprocess
import sys
from pathlib import Path
from packaging.versi... | 6,394 | 31.29798 | 83 | py |
espnet | espnet-master/test/test_e2e_compatibility.py | #!/usr/bin/env python3
# coding: utf-8
# Copyright 2019 Tomoki Hayashi
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
from __future__ import print_function
import importlib
import os
import re
import shutil
import subprocess
import tempfile
from os.path import join
import chainer
import numpy as np
imp... | 3,521 | 30.72973 | 111 | py |
espnet | espnet-master/test/test_e2e_asr_conformer.py | import argparse
import pytest
import torch
from espnet.nets.pytorch_backend.e2e_asr_conformer import E2E
from espnet.nets.pytorch_backend.transformer import plot
def make_arg(**kwargs):
defaults = dict(
adim=2,
aheads=1,
dropout_rate=0.0,
transformer_attn_dropout_rate=None,
... | 4,895 | 25.901099 | 83 | py |
espnet | espnet-master/test/test_custom_transducer.py | # coding: utf-8
import argparse
import json
import tempfile
import pytest
import torch
from packaging.version import parse as V
import espnet.lm.pytorch_backend.extlm as extlm_pytorch
import espnet.nets.pytorch_backend.lm.default as lm_pytorch
from espnet.asr.pytorch_backend.asr_init import load_trained_model
from e... | 21,623 | 30.33913 | 87 | py |
espnet | espnet-master/test/test_batch_beam_search.py | import os
from argparse import Namespace
from test.test_beam_search import prepare, transformer_args
import numpy
import pytest
import torch
from espnet.nets.batch_beam_search import BatchBeamSearch, BeamSearch
from espnet.nets.beam_search import Hypothesis
from espnet.nets.lm_interface import dynamic_import_lm
from ... | 5,863 | 30.026455 | 88 | py |
espnet | espnet-master/test/test_e2e_mt.py | # coding: utf-8
# Copyright 2019 Hirofumi Inaguma
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
from __future__ import division
import argparse
import importlib
import os
import tempfile
from test.utils_test import make_dummy_json_mt
import chainer
import numpy as np
import pytest
import torch
from e... | 12,854 | 31.298995 | 88 | py |
espnet | espnet-master/test/test_multi_spkrs.py | # coding: utf-8
# Copyright 2018 Hiroshi Seki
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import importlib
import re
import numpy
import pytest
import torch
def make_arg(**kwargs):
defaults = dict(
aconv_chans=2,
aconv_filts=20,
adim=20,
aheads=4,... | 7,289 | 28.51417 | 86 | py |
espnet | espnet-master/test/test_positional_encoding.py | import pytest
import torch
from espnet.nets.pytorch_backend.transformer.embedding import (
LearnableFourierPosEnc,
PositionalEncoding,
ScaledPositionalEncoding,
)
@pytest.mark.parametrize(
"dtype, device",
[(dt, dv) for dt in ("float32", "float64") for dv in ("cpu", "cuda")],
)
def test_pe_extend... | 5,074 | 30.32716 | 87 | py |
espnet | espnet-master/test/test_asr_init.py | # coding: utf-8
import argparse
import json
import os
import tempfile
import numpy as np
import pytest
import torch
import espnet.nets.pytorch_backend.lm.default as lm_pytorch
from espnet.asr.asr_utils import torch_save
from espnet.asr.pytorch_backend.asr_init import freeze_modules, load_trained_modules
from espnet.... | 7,583 | 25.989324 | 84 | py |
espnet | espnet-master/test/test_e2e_mt_transformer.py | # coding: utf-8
# Copyright 2019 Hirofumi Inaguma
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import pytest
import torch
from espnet.nets.pytorch_backend.e2e_mt_transformer import E2E
from espnet.nets.pytorch_backend.transformer import plot
def make_arg(**kwargs):
defaults = di... | 3,754 | 26.014388 | 83 | py |
espnet | espnet-master/test/test_e2e_asr_transformer.py | import argparse
import chainer
import numpy
import pytest
import torch
import espnet.nets.chainer_backend.e2e_asr_transformer as ch
import espnet.nets.pytorch_backend.e2e_asr_transformer as th
from espnet.nets.pytorch_backend.nets_utils import rename_state_dict
from espnet.nets.pytorch_backend.transformer import plot... | 8,385 | 29.717949 | 87 | py |
espnet | espnet-master/test/test_beam_search_timesync.py | from argparse import Namespace
import pytest
import torch
from espnet.nets.asr_interface import dynamic_import_asr
from espnet.nets.beam_search_timesync import BeamSearchTimeSync
from espnet.nets.lm_interface import dynamic_import_lm
from espnet.nets.scorers.length_bonus import LengthBonus
rnn_args = Namespace(
... | 5,619 | 26.149758 | 88 | py |
espnet | espnet-master/test/test_e2e_tts_transformer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Tomoki Hayashi
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
from argparse import Namespace
import numpy as np
import pytest
import torch
from espnet.nets.pytorch_backend.e2e_tts_transformer import Transformer, subsequent_mask
from espnet... | 15,609 | 32.354701 | 88 | py |
espnet | espnet-master/test/test_asr_interface.py | import pytest
from espnet.nets.asr_interface import dynamic_import_asr
@pytest.mark.parametrize(
"name, backend",
[(nn, backend) for nn in ("transformer", "rnn") for backend in ("pytorch",)],
)
def test_asr_build(name, backend):
model = dynamic_import_asr(name, backend).build(
10, 10, mtlalpha=0.... | 415 | 26.733333 | 81 | py |
espnet | espnet-master/test/test_e2e_asr.py | # coding: utf-8
# Copyright 2017 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
from __future__ import division
import argparse
import importlib
import os
import tempfile
from test.utils_test import make_dummy_json
import chainer
import numpy as np
import pytest
import torch
import espn... | 26,215 | 34.331536 | 88 | py |
espnet | espnet-master/test/test_asr_quantize.py | # Copyright 2021 Gaopeng Xu
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import pytest
import torch
from espnet.nets.asr_interface import dynamic_import_asr
@pytest.mark.parametrize(
"name, backend",
[(nn, backend) for nn in ("transformer", "rnn") for backend in ("pytorch",)],
)
def test_asr_... | 642 | 28.227273 | 81 | py |
espnet | espnet-master/test/test_optimizer.py | # coding: utf-8
# Copyright 2017 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import chainer
import numpy
import pytest
import torch
from espnet.optimizer.factory import dynamic_import_optimizer
from espnet.optimizer.pytorch import OPTIMIZER_FACTORY_DICT
class ChModel(chainer.Chain):
... | 3,023 | 29.857143 | 83 | py |
espnet | espnet-master/test/test_loss.py | # Copyright 2017 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import chainer.functions as F
import numpy
import pytest
import torch
from espnet.nets.pytorch_backend.e2e_asr import pad_list
from espnet.nets.pytorch_backend.nets_utils import th_accuracy
@pytest.mark.parametrize("ctc_type"... | 5,405 | 35.527027 | 86 | py |
espnet | espnet-master/test/test_beam_search.py | from argparse import Namespace
import numpy
import pytest
import torch
from espnet.nets.asr_interface import dynamic_import_asr
from espnet.nets.beam_search import BeamSearch
from espnet.nets.lm_interface import dynamic_import_lm
from espnet.nets.scorers.length_bonus import LengthBonus
rnn_args = Namespace(
elay... | 6,366 | 27.55157 | 88 | py |
espnet | espnet-master/test/test_lm.py | from test.test_beam_search import prepare, rnn_args
import chainer
import numpy
import pytest
import torch
import espnet.lm.chainer_backend.lm as lm_chainer
import espnet.nets.pytorch_backend.lm.default as lm_pytorch
from espnet.nets.beam_search import beam_search
from espnet.nets.lm_interface import dynamic_import_l... | 6,647 | 33.268041 | 88 | py |
espnet | espnet-master/test/test_e2e_tts_fastspeech.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Tomoki Hayashi
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import json
import os
import shutil
import tempfile
from argparse import Namespace
import numpy as np
import pytest
import torch
from espnet.nets.pytorch_backend.e2e_tts_fastspe... | 21,140 | 32.398104 | 87 | py |
espnet | espnet-master/test/test_distributed_launch.py | # coding: utf-8
#
# SPDX-FileCopyrightText:
# Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
import argparse
import itertools
import os
import sys
from multiprocessing import Queue
import pytest
from espnet.distributed.pytorch_backend.launch import... | 4,110 | 26.225166 | 76 | py |
espnet | espnet-master/test/test_e2e_st_transformer.py | # coding: utf-8
# Copyright 2019 Hirofumi Inaguma
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import pytest
import torch
from espnet.nets.pytorch_backend.e2e_st_transformer import E2E
from espnet.nets.pytorch_backend.transformer import plot
def make_arg(**kwargs):
defaults = dic... | 5,352 | 28.738889 | 85 | py |
espnet | espnet-master/test/test_torch.py | # Copyright 2017 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import torch
from espnet.nets.pytorch_backend.nets_utils import pad_list
def test_pad_list():
xs = [[1, 2, 3], [1, 2], [1, 2, 3, 4]]
xs = list(map(lambda x: torch.LongTensor(x), xs))
xpad = pad_list(xs, -1)
e... | 852 | 26.516129 | 74 | py |
espnet | espnet-master/test/test_initialization.py | # Copyright 2017 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import os
import random
import numpy
import torch
args = argparse.Namespace(
elayers=4,
subsample="1_2_2_1_1",
etype="vggblstmp",
eunits=320,
eprojs=320,
dtype="lstm",
dlayers=2,
... | 3,380 | 28.4 | 72 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.