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
Oort
Oort-master/training/utils/transforms_wav.py
"""Transforms on raw wav samples.""" __author__ = 'Yuan Xu' import random import numpy as np import librosa import torch from torch.utils.data import Dataset random.seed(233) def should_apply_transform(prob=0.5): """Transforms are only randomly applied with the given probability.""" return random.random() ...
5,000
29.87037
129
py
Oort
Oort-master/training/utils/voice_model.py
import math from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F supported_rnns = { 'lstm': nn.LSTM, 'rnn': nn.RNN, 'gru': nn.GRU } supported_rnns_inv = dict((v, k) for k, v in supported_rnns.items()) class SequenceWise(nn.Module): def __init__(self,...
9,585
36.299611
120
py
E2FGVI
E2FGVI-master/test.py
# -*- coding: utf-8 -*- import cv2 from PIL import Image import numpy as np import importlib import os import argparse from tqdm import tqdm import matplotlib.pyplot as plt from matplotlib import animation import torch from core.utils import to_tensors parser = argparse.ArgumentParser(description="E2FGVI") parser.add...
7,775
33.56
89
py
E2FGVI
E2FGVI-master/evaluate.py
# -*- coding: utf-8 -*- import cv2 import numpy as np import importlib import os import argparse from PIL import Image import torch from torch.utils.data import DataLoader from core.dataset import TestDataset from core.metrics import calc_psnr_and_ssim, calculate_i3d_activations, calculate_vfid, init_i3d_model # glo...
6,741
37.090395
119
py
E2FGVI
E2FGVI-master/train.py
import os import json import argparse from shutil import copyfile import torch import torch.multiprocessing as mp from core.trainer import Trainer from core.dist import ( get_world_size, get_local_rank, get_global_rank, get_master_ip, ) parser = argparse.ArgumentParser(description='E2FGVI') parser.ad...
3,169
34.222222
79
py
E2FGVI
E2FGVI-master/core/lr_scheduler.py
""" LR scheduler from BasicSR https://github.com/xinntao/BasicSR """ import math from collections import Counter from torch.optim.lr_scheduler import _LRScheduler class MultiStepRestartLR(_LRScheduler): """ MultiStep with restarts learning rate scheme. Args: optimizer (torch.nn.optimizer): Torch o...
4,386
37.823009
79
py
E2FGVI
E2FGVI-master/core/loss.py
import torch import torch.nn as nn class AdversarialLoss(nn.Module): r""" Adversarial loss https://arxiv.org/abs/1711.10337 """ def __init__(self, type='nsgan', target_real_label=1.0, target_fake_label=0.0): r""" type = nsgan | lsg...
1,279
29.47619
75
py
E2FGVI
E2FGVI-master/core/utils.py
import os import io import cv2 import random import numpy as np from PIL import Image, ImageOps import zipfile import torch import matplotlib import matplotlib.patches as patches from matplotlib.path import Path from matplotlib import pyplot as plt from torchvision import transforms # matplotlib.use('agg') # #######...
12,064
35.450151
85
py
E2FGVI
E2FGVI-master/core/dataset.py
import os import json import random import cv2 from PIL import Image import numpy as np import torch import torchvision.transforms as transforms from core.utils import (TrainZipReader, TestZipReader, create_random_shape_with_random_motion, Stack, ToTorchFormatTensor, G...
4,958
35.463235
79
py
E2FGVI
E2FGVI-master/core/dist.py
import os import torch def get_world_size(): """Find OMPI world size without calling mpi functions :rtype: int """ if os.environ.get('PMI_SIZE') is not None: return int(os.environ.get('PMI_SIZE') or 1) elif os.environ.get('OMPI_COMM_WORLD_SIZE') is not None: return int(os.environ.g...
1,459
29.416667
69
py
E2FGVI
E2FGVI-master/core/metrics.py
import numpy as np from skimage import measure from scipy import linalg import torch import torch.nn as nn import torch.nn.functional as F from core.utils import to_tensors def calculate_epe(flow1, flow2): """Calculate End point errors.""" epe = torch.sum((flow1 - flow2)**2, dim=1).sqrt() epe = epe.vie...
20,663
35.189142
86
py
E2FGVI
E2FGVI-master/core/trainer.py
import os import glob import logging import importlib from tqdm import tqdm import torch import torch.nn as nn from torch.utils.data import DataLoader from torch.utils.data.distributed import DistributedSampler from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.tensorboard import SummaryWrit...
16,590
40.4775
79
py
E2FGVI
E2FGVI-master/model/e2fgvi_hq.py
''' Towards An End-to-End Framework for Video Inpainting ''' import torch import torch.nn as nn import torch.nn.functional as F from model.modules.flow_comp import SPyNet from model.modules.feat_prop import BidirectionalPropagation, SecondOrderDeformableAlignment from model.modules.tfocal_transformer_hq import Tempor...
14,282
39.692308
132
py
E2FGVI
E2FGVI-master/model/e2fgvi.py
''' Towards An End-to-End Framework for Video Inpainting ''' import torch import torch.nn as nn import torch.nn.functional as F from model.modules.flow_comp import SPyNet from model.modules.feat_prop import BidirectionalPropagation, SecondOrderDeformableAlignment from model.modules.tfocal_transformer import TemporalF...
14,229
39.541311
132
py
E2FGVI
E2FGVI-master/model/modules/tfocal_transformer_hq.py
""" This code is based on: [1] FuseFormer: Fusing Fine-Grained Information in Transformers for Video Inpainting, ICCV 2021 https://github.com/ruiliu-ai/FuseFormer [2] Tokens-to-Token ViT: Training Vision Transformers from Scratch on ImageNet, ICCV 2021 https://github.com/yitu-opensource/T2T-...
24,390
42.09364
131
py
E2FGVI
E2FGVI-master/model/modules/spectral_norm.py
""" Spectral Normalization from https://arxiv.org/abs/1802.05957 """ import torch from torch.nn.functional import normalize class SpectralNorm(object): # Invariant before and after each forward call: # u = normalize(W @ v) # NB: At initialization, this invariant is not enforced _version = 1 # ...
12,357
41.909722
118
py
E2FGVI
E2FGVI-master/model/modules/tfocal_transformer.py
""" This code is based on: [1] FuseFormer: Fusing Fine-Grained Information in Transformers for Video Inpainting, ICCV 2021 https://github.com/ruiliu-ai/FuseFormer [2] Tokens-to-Token ViT: Training Vision Transformers from Scratch on ImageNet, ICCV 2021 https://github.com/yitu-opensource/T2T-...
23,112
42.040968
168
py
E2FGVI
E2FGVI-master/model/modules/feat_prop.py
""" BasicVSR++: Improving Video Super-Resolution with Enhanced Propagation and Alignment, CVPR 2022 """ import torch import torch.nn as nn from mmcv.ops import ModulatedDeformConv2d, modulated_deform_conv2d from mmcv.cnn import constant_init from model.modules.flow_comp import flow_warp class SecondOrderDeforma...
6,004
39.033333
99
py
E2FGVI
E2FGVI-master/model/modules/flow_comp.py
import numpy as np import torch.nn as nn import torch.nn.functional as F import torch from mmcv.cnn import ConvModule from mmcv.runner import load_checkpoint class FlowCompletionLoss(nn.Module): """Flow completion loss""" def __init__(self): super().__init__() self.fix_spynet = SPyNet() ...
16,931
36.543237
157
py
returnn-experiments
returnn-experiments-master/2020-TTS-LJSpeech/decoder.py
import argparse from num2words import num2words import numpy import os import subprocess import sys import torch import yaml import wave sys.path.append("returnn") sys.path.append("ParallelWaveGAN") from parallel_wavegan import models as pwg_models from parallel_wavegan.layers import PQMF from returnn import rnn from...
4,301
37.070796
133
py
returnn-experiments
returnn-experiments-master/2020-rnn-transducer/configs/code/rna_tf_impl.py
#!/usr/bin/env python3 # vim: sw=2 """ Implementation of the RNA loss in pure TF, plus comparisons against reference implementations. This is very similar to RNN-T loss, but restricts the paths to be strictly monotonic. references: * recurrent neural aligner: https://pdfs.semanticscholar.org/7703/a2c5468ecbee5...
48,807
40.222973
139
py
hsoftmax
hsoftmax-master/wenet/dataset/wav_distortion.py
import sys import random import math import torchaudio import torch torchaudio.set_audio_backend("sox_io") def db2amp(db): return pow(10, db / 20) def amp2db(amp): return 20 * math.log10(amp) def make_poly_distortion(conf): """Generate a db-domain ploynomial distortion function f(x) = a * x^m ...
8,784
27.247588
81
py
hsoftmax
hsoftmax-master/wenet/dataset/dataset.py
# Copyright (c) 2020 Mobvoi Inc. (authors: Binbin Zhang, Chao Yang) # Copyright (c) 2021 Jinsong Pan # # 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/LIC...
19,933
36.329588
87
py
hsoftmax
hsoftmax-master/wenet/bin/export_jit.py
# Copyright (c) 2020 Mobvoi Inc. (authors: Binbin Zhang, Di Wu) # # 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 appli...
2,252
36.55
79
py
hsoftmax
hsoftmax-master/wenet/bin/average_model.py
# Copyright 2019 Mobvoi Inc. All Rights Reserved. # Author: di.wu@mobvoi.com (DI WU) import os import argparse import glob import yaml import numpy as np import torch if __name__ == '__main__': parser = argparse.ArgumentParser(description='average model') parser.add_argument('--dst_model', required=True, help...
2,924
36.025316
76
py
hsoftmax
hsoftmax-master/wenet/bin/alignment.py
# Copyright (c) 2021 Mobvoi Inc. (authors: Di Wu) # # 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 a...
8,176
36.682028
79
py
hsoftmax
hsoftmax-master/wenet/bin/recognize.py
# Copyright (c) 2020 Mobvoi Inc. (authors: Binbin Zhang, Xiaoyu Chen, Di Wu) # # 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 requ...
9,875
42.315789
105
py
hsoftmax
hsoftmax-master/wenet/bin/train.py
# Copyright (c) 2020 Mobvoi Inc. (authors: Binbin Zhang, Xiaoyu Chen) # # 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...
12,809
40.189711
100
py
hsoftmax
hsoftmax-master/wenet/utils/checkpoint.py
# Copyright 2019 Mobvoi Inc. All Rights Reserved. # Author: binbinzhang@mobvoi.com (Binbin Zhang) import logging import os import re import yaml import torch def load_checkpoint(model: torch.nn.Module, path: str) -> dict: if torch.cuda.is_available(): logging.info('Checkpoint: loading from checkpoint %s...
1,473
30.361702
77
py
hsoftmax
hsoftmax-master/wenet/utils/ctc_util.py
# Copyright 2021 Mobvoi Inc. All Rights Reserved. # Author: binbinzhang@mobvoi.com (Di Wu) import numpy as np import torch def insert_blank(label, blank_id=0): """Insert blank token between every two label token.""" label = np.expand_dims(label, 1) blanks = np.zeros((label.shape[0], 1), dtype=np.int64) + ...
2,668
35.561644
85
py
hsoftmax
hsoftmax-master/wenet/utils/executor.py
# Copyright 2019 Mobvoi Inc. All Rights Reserved. # Author: binbinzhang@mobvoi.com (Binbin Zhang) import logging from contextlib import nullcontext # if your python version < 3.7 use the below one # from contextlib import suppress as nullcontext import torch from torch.nn.utils import clip_grad_norm_ from tqdm import ...
8,091
44.206704
89
py
hsoftmax
hsoftmax-master/wenet/utils/hsoftmax_processpool.py
import numpy as np import torch import torch.multiprocessing as mp from torch.multiprocessing import Process # purpose of this class is to save function context to subprocess import time class Worker(Process): """Process executing tasks from shared memories""" def __init__(self, workerid, ...
4,436
34.214286
107
py
hsoftmax
hsoftmax-master/wenet/utils/scheduler.py
from typing import Union import torch from torch.optim.lr_scheduler import _LRScheduler from typeguard import check_argument_types class WarmupLR(_LRScheduler): """The WarmupLR scheduler This scheduler is almost same as NoamLR Scheduler except for following difference: NoamLR: lr = optimi...
3,726
27.234848
77
py
hsoftmax
hsoftmax-master/wenet/utils/common.py
"""Unility functions for Transformer.""" import multiprocessing import math from typing import Tuple, List import torch from torch.nn.utils.rnn import pad_sequence IGNORE_ID = -1 def pad_list(xs: List[torch.Tensor], pad_value: int): """Perform padding for the list of tensors. Args: xs (List): List...
6,689
30.261682
79
py
hsoftmax
hsoftmax-master/wenet/utils/mask.py
# -*- coding: utf-8 -*- # Copyright 2019 Shigeki Karita # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import torch def subsequent_mask( size: int, device: torch.device = torch.device("cpu"), ) -> torch.Tensor: """Create mask for subsequent steps (size, size). This mask is used...
8,920
34.400794
78
py
hsoftmax
hsoftmax-master/wenet/utils/optimizer.py
import torch.optim as optim OPTIMIZER_DICT = {'adam': optim.Adam, 'sgd': optim.SGD} def init_optimizer(parameters, configs): assert configs['optim'] in OPTIMIZER_DICT optim = OPTIMIZER_DICT[configs['optim']] return optim(parameters, **configs['optim_conf'])
271
33
55
py
hsoftmax
hsoftmax-master/wenet/transformer/embedding.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2019 Mobvoi Inc. All Rights Reserved. # Author: di.wu@mobvoi.com (DI WU) """Positonal Encoding Module.""" import math from typing import Tuple import torch class PositionalEncoding(torch.nn.Module): """Positional encoding. :param int d_model: embe...
4,668
33.330882
79
py
hsoftmax
hsoftmax-master/wenet/transformer/encoder_layer.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2019 Mobvoi Inc. All Rights Reserved. # Author: di.wu@mobvoi.com (DI WU) """Encoder self-attention layer definition.""" from typing import Optional, Tuple import torch from torch import nn class TransformerEncoderLayer(nn.Module): """Encoder layer modu...
10,193
36.895911
79
py
hsoftmax
hsoftmax-master/wenet/transformer/label_smoothing_loss.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2019 Shigeki Karita # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Label smoothing module.""" import torch from torch import nn class LabelSmoothingLoss(nn.Module): """Label-smoothing loss. In a standard CE loss, the label's data di...
3,046
32.855556
77
py
hsoftmax
hsoftmax-master/wenet/transformer/positionwise_feed_forward.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2019 Shigeki Karita # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Positionwise feed forward layer definition.""" import torch class PositionwiseFeedForward(torch.nn.Module): """Positionwise feed forward layer. FeedForward are appie...
1,399
30.818182
68
py
hsoftmax
hsoftmax-master/wenet/transformer/ctc.py
import torch import torch.nn.functional as F from typeguard import check_argument_types class CTC(torch.nn.Module): """CTC module""" def __init__( self, odim: int, encoder_output_size: int, dropout_rate: float = 0.0, reduce: bool = True, ): """ Construct CTC...
2,415
33.514286
77
py
hsoftmax
hsoftmax-master/wenet/transformer/subsampling.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2019 Mobvoi Inc. All Rights Reserved. # Author: di.wu@mobvoi.com (DI WU) """Subsampling layer definition.""" from typing import Tuple import torch class BaseSubsampling(torch.nn.Module): def __init__(self): super().__init__() self.right...
7,611
32.240175
74
py
hsoftmax
hsoftmax-master/wenet/transformer/encoder.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2019 Mobvoi Inc. All Rights Reserved. # Author: di.wu@mobvoi.com (DI WU) """Encoder definition.""" from typing import Tuple, List, Optional import torch from typeguard import check_argument_types from wenet.transformer.attention import MultiHeadedAttention f...
19,676
42.629712
82
py
hsoftmax
hsoftmax-master/wenet/transformer/convolution.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2021 Mobvoi Inc. All Rights Reserved. # Author: di.wu@mobvoi.com (DI WU) """ConvolutionModule definition.""" from typing import Optional, Tuple import torch from torch import nn from typeguard import check_argument_types class ConvolutionModule(nn.Module):...
4,512
32.42963
78
py
hsoftmax
hsoftmax-master/wenet/transformer/cmvn.py
#!/usr/bin/env python3 # Copyright (c) 2020 Mobvoi Inc (Binbin Zhang) # # 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 a...
1,510
30.479167
74
py
hsoftmax
hsoftmax-master/wenet/transformer/decoder.py
# Copyright 2021 Mobvoi Inc. All Rights Reserved. # Author: di.wu@mobvoi.com (DI WU) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Decoder definition.""" from typing import Tuple, List, Optional import torch from typeguard import check_argument_types from wenet.transformer.attention import MultiHeade...
13,287
40.917981
83
py
hsoftmax
hsoftmax-master/wenet/transformer/hsoftmax_layer.py
from multiprocessing import dummy from typing import List import torch from torch import nn import math from wenet.utils.huffman_tree import HuffmanTree from wenet.utils.hsoftmax_processpool import ProcessPool, Worker from queue import PriorityQueue import heapq import time import logging class HSoftmaxLayer(nn.Modu...
12,322
40.076667
153
py
hsoftmax
hsoftmax-master/wenet/transformer/subsampling.bak.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2019 Mobvoi Inc. All Rights Reserved. # Author: di.wu@mobvoi.com (DI WU) """Subsampling layer definition.""" from typing import Tuple import torch class BaseSubsampling(torch.nn.Module): def __init__(self): super().__init__() self.right...
7,611
32.240175
74
py
hsoftmax
hsoftmax-master/wenet/transformer/swish.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020 Johns Hopkins University (Shinji Watanabe) # Northwestern Polytechnical University (Pengcheng Guo) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Swish() activation function for Conformer.""" import torch class Swish(torc...
511
29.117647
70
py
hsoftmax
hsoftmax-master/wenet/transformer/attention.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2019 Shigeki Karita # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Multi-Head Attention layer definition.""" import math from typing import Optional, Tuple import torch from torch import nn class MultiHeadedAttention(nn.Module): """Mult...
9,149
40.03139
80
py
hsoftmax
hsoftmax-master/wenet/transformer/decoder_layer.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2019 Shigeki Karita # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Decoder self-attention layer definition.""" from typing import Optional, Tuple import torch from torch import nn class DecoderLayer(nn.Module): """Single decoder layer mo...
5,170
35.160839
79
py
hsoftmax
hsoftmax-master/wenet/transformer/asr_model.py
# Copyright (c) 2020 Mobvoi Inc. (authors: Binbin Zhang, Di Wu) # # 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 appli...
31,951
41.376658
80
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/fairness_test_Celeba_timm.py
import argparse import torch import os import torch.nn as nn print('Imported torch') from util.fairness_utils import evaluate, most_least_variant_classes from util.data_utils_balanced import load_dict_as_str from util.data_utils_balanced import ImageFolderWithProtectedAttributes import numpy as np import torchvision.tr...
7,492
42.563953
121
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/fairness_test_Celeba.py
import argparse import torch import os import torch.nn as nn print('Imported torch') from util.fairness_utils import evaluate, most_least_variant_classes from util.data_utils_balanced import load_dict_as_str from util.data_utils_balanced import ImageFolderWithProtectedAttributes from backbone.model_resnet import ResNet...
9,029
48.615385
121
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/config.py
import torch configurations = { 1: dict( SEED = 1337, # random seed for reproduce results DATA_ROOT = '/home/peter/Project/face.evoLVe.PyTorch/data', # the parent root where your train/val/test data are stored MODEL_ROOT = '/home/peter/Project/face.evoLVe.PyTorch/model', # the root to buf...
2,645
40.34375
194
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/fairness_train_timm.py
from pathlib import Path from comet_ml import Experiment import argparse from tqdm import tqdm from config import user_configs import os import torch import torch.nn as nn import torch.optim as optim from head.metrics import CosFace from loss.focal import FocalLoss from util.utils import separate_resnet_bn_paras, warm...
10,167
42.639485
229
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/train.py
import torch import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms import torchvision.datasets as datasets from config import configurations from backbone.model_resnet import ResNet_50, ResNet_101, ResNet_152 from backbone.model_irse import IR_50, IR_101, IR_152, IR_SE_50, IR_SE_...
14,081
52.340909
290
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/backbone/model_resnet.py
import torch.nn as nn from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, ReLU, Dropout, MaxPool2d, Sequential, Module # Support: ['ResNet_50', 'ResNet_101', 'ResNet_152'] def conv3x3(in_planes, out_planes, stride = 1): """3x3 convolution with padding""" return Conv2d(in_planes, out_planes, kern...
5,756
29.460317
107
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/backbone/MobileFaceNets.py
# based on: # https://github.com/TreB1eN/InsightFace_Pytorch/blob/master/model.py from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module import torch class Flatten(Module): def forward(self, input): return input.view(input.size(0), -1) class Conv_block(Module): def _...
4,399
44.833333
131
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/backbone/EfficientNets.py
# based on: # Github repo: https://github.com/lukemelas/EfficientNet-PyTorch import re import math import collections from functools import partial import torch from torch import nn from torch.nn import functional as F from torch.utils import model_zoo from torch.nn import Sequential, BatchNorm1d, BatchNorm2d, Dropout...
42,605
40.165217
130
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/backbone/model_irse.py
import torch import torch.nn as nn from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, ReLU, Sigmoid, Dropout, MaxPool2d, \ AdaptiveAvgPool2d, Sequential, Module from collections import namedtuple # Support: ['IR_50', 'IR_101', 'IR_152', 'IR_SE_50', 'IR_SE_101', 'IR_SE_152'] class Flatten(Modu...
7,418
30.172269
112
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/backbone/GhostNet.py
# based on: # https://github.com/huawei-noah/ghostnet/blob/master/ghostnet_pytorch/ghostnet.py # 2020.06.09-Changed for building GhostNet # Huawei Technologies Co., Ltd. <foss@huawei.com> """ Creates a GhostNet Model as defined in: GhostNet: More Features from Cheap Operations By Kai Han, Yunhe Wang, Qi Ti...
8,416
33.495902
115
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/backbone/AttentionNets.py
# based on: # https://github.com/tengshaofeng/ResidualAttentionNetwork-pytorch/tree/master/Residual-Attention-Network/model import torch import torch.nn as nn from torch.nn import init import functools from torch.autograd import Variable import numpy as np class Flatten(nn.Module): def forward(self, x): r...
10,698
44.52766
111
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/backup/data_pipe.py
from PIL import Image, ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True import numpy as np import cv2 import bcolz import pickle import mxnet as mx from tqdm import tqdm def load_bin(path, rootdir, transform, image_size = [112, 112]): if not rootdir.exists(): rootdir.mkdir() bins, issame_list = pickle...
1,671
34.574468
118
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/backup/prepare_data.py
from config import get_config from data.data_pipe import load_bin, load_mx_rec import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description = 'for extracting faces_emore data') parser.add_argument("-r", "--rec_path", help="mxnet record file path",default = 'faces_emore', type = str) ...
670
40.9375
110
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/backup/utils.py
import torch import torchvision.transforms as transforms import torch.nn.functional as F from .verification import evaluate from datetime import datetime import matplotlib.pyplot as plt plt.switch_backend('agg') import numpy as np from PIL import Image import bcolz import io import os # Support: ['get_time', 'l2_no...
7,584
30.869748
306
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/backup/config.py
import torch configurations = { 1: dict( SEED = 1337, # random seed for reproduce results DATA_ROOT = '/media/pc/6T/jasonjzhao/data/faces_emore', # the parent root where your train/val/test data are stored MODEL_ROOT = '/media/pc/6T/jasonjzhao/buffer/model_ir152', # the root to buffer you...
1,963
52.081081
194
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/backup/metrics.py
from __future__ import print_function from __future__ import division import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Parameter import math # Support: ['Softmax', 'ArcFace', 'CosFace', 'SphereFace', 'Am_softmax'] class Softmax(nn.Module): r"""Implement of Softmax (normal ...
9,015
37.365957
121
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/backup/train.py
import torch import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms import torchvision.datasets as datasets from config import configurations from backbone.model_resnet import ResNet_50, ResNet_101, ResNet_152 from backbone.model_irse import IR_50, IR_101, IR_152, IR_SE_50, IR_SE...
16,788
55.911864
318
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/head/metrics.py
from __future__ import print_function from __future__ import division import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Parameter import math # Support: ['Softmax', 'ArcFace', 'CosFace', 'SphereFace', 'Am_softmax'] # Support: ['AdaCos','AdaM_Softmax','ArcFace','ArcNegFace','Circl...
30,133
42.609262
138
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/util/data_utils_balanced.py
import torch import torchvision.transforms as transforms import torchvision.datasets as datasets from typing import Any, Callable, cast, Dict, List, Optional, Tuple import random import json import os from PIL import Image import numpy as np torch.manual_seed(222) torch.cuda.manual_seed_all(222) np.random.seed(222) #r...
16,509
42.677249
151
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/util/extract_feature_v1.py
# Helper function for extracting features from pre-trained models import torch import torchvision.transforms as transforms import torchvision.datasets as datasets import numpy as np import os def l2_norm(input, axis = 1): norm = torch.norm(input, 2, axis, True) output = torch.div(input, norm) return out...
3,253
34.369565
258
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/util/utils.py
import torch import torchvision.transforms as transforms import torch.nn.functional as F import torchvision.datasets as datasets from .verification import evaluate from sklearn.model_selection import train_test_split from torch.utils.data import Subset from datetime import datetime import matplotlib.pyplot as plt plt.s...
9,632
31.434343
165
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/util/extract_feature_v2.py
# Helper function for extracting features from pre-trained models import torch import cv2 import numpy as np import os import matplotlib.pyplot as plt def l2_norm(input, axis = 1): norm = torch.norm(input, 2, axis, True) output = torch.div(input, norm) return output def extract_feature(img_root, backbo...
2,206
29.652778
137
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/util/fairness_utils.py
import torch from tqdm import tqdm import numpy as np import random import os import pandas as pd device = torch.device("cuda" if torch.cuda.is_available() else "cpu") torch.manual_seed(222) torch.cuda.manual_seed_all(222) np.random.seed(222) random.seed(222) torch.backends.cudnn.deterministic = True torch.backends.cu...
9,000
37.965368
183
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/data_processing/randaugment.py
from PIL import Image import matplotlib.pyplot as plt import numpy as np from PIL import Image, ImageEnhance, ImageOps import numpy as np import random class Rand_Augment(): def __init__(self, Numbers=None, max_Magnitude=None): self.transforms = ['autocontrast', 'equalize', 'rotate', 'solarize', 'color', ...
5,693
45.292683
120
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/loss/focal.py
import torch import torch.nn as nn # Support: ['FocalLoss'] class FocalLoss(nn.Module): def __init__(self, elementwise = False, gamma = 2, eps = 1e-7): super(FocalLoss, self).__init__() self.gamma = gamma self.eps = eps self.elementwise = elementwise if self.elementwise: ...
689
23.642857
67
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/paddle/mult_gpu_training.py
import paddle import paddle.nn as nn import paddle.optimizer as optim from paddle.vision import transforms from config import configurations from dataload import NormalDataset,BalancingClassDataset from backbone.model_resnet import ResNet_50, ResNet_101, ResNet_152 from backbone.model_irse import IR_50, IR_101, IR_152,...
12,632
49.939516
171
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/paddle/dataload.py
import paddle import os, tqdm,cv2 import numpy as np from paddle.vision import transforms import paddle.vision as vision class BalancingClassDataset(paddle.io.Dataset): def __init__(self, data_root, input_size, mean, std): super(BalancingClassDataset, self).__init__() self.input_size = input_size ...
4,753
38.616667
110
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/paddle/head/metrics.py
from __future__ import print_function from __future__ import division import paddle import paddle.nn as nn import paddle.nn.functional as F import math # Support: ['Softmax', 'ArcFace', 'CosFace', 'SphereFace', 'Am_softmax'] class Softmax(nn.Layer): """Implement of Softmax (normal classification head): Ar...
9,710
38.47561
110
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/paddle/align/get_nets.py
import paddle import paddle.nn as nn import paddle.nn.functional as F from collections import OrderedDict import numpy as np class Flatten(nn.Layer): def __init__(self): super(Flatten, self).__init__() def forward(self, x): """ Arguments: x: a float tensor with shape [bat...
5,081
28.546512
65
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/paddle/align/detector.py
import numpy as np import paddle from get_nets import PNet, RNet, ONet from box_utils import nms, calibrate_box, get_image_boxes, convert_to_square from first_stage import run_first_stage def detect_faces(image, min_face_size = 20.0, thresholds=[0.6, 0.7, 0.8], nms_thresholds=[0.7, 0...
4,350
33.259843
95
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/applications/align/get_nets.py
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict import numpy as np class Flatten(nn.Module): def __init__(self): super(Flatten, self).__init__() def forward(self, x): """ Arguments: x: a float tensor with shape [batch...
4,864
27.786982
65
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/applications/align/first_stage.py
import torch from torch.autograd import Variable import math from PIL import Image import numpy as np from box_utils import nms, _preprocess def run_first_stage(image, net, scale, threshold): """Run P-Net, generate bounding boxes, and do NMS. Arguments: image: an instance of PIL.Image. net: a...
3,012
30.061856
76
py
FR-NAS
FR-NAS-main/face.evoLVe.PyTorch/applications/align/detector.py
import numpy as np import torch from torch.autograd import Variable from get_nets import PNet, RNet, ONet from box_utils import nms, calibrate_box, get_image_boxes, convert_to_square from first_stage import run_first_stage def detect_faces(image, min_face_size = 20.0, thresholds=[0.6, 0.7, 0.8], ...
4,186
32.496
95
py
catastrophic-overfitting
catastrophic-overfitting-main/eval.py
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter import torch from torchattacks import FGSM, PGD, MultiAttack from defenses.loader import base_loader from defenses.model import get_model def run(name, model, root, data_path, gpu, method, eps, alpha, steps, restart): torch.cuda.set_device(gpu...
2,537
36.323529
113
py
catastrophic-overfitting
catastrophic-overfitting-main/train.py
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter import numpy as np import random import torch import torch.optim as optim from defenses.loader import base_loader from defenses.model import get_model from defenses.trainer import COAdvTrainer from defenses.trainer import FastAdvTrainer def run(name...
3,697
36.734694
135
py
catastrophic-overfitting
catastrophic-overfitting-main/defenses/model.py
import torch.nn as nn from .models.preact_resnet import PreActBlock, PreActResNet from .models.wide_resnet import WideResNet from .models.normalize import Normalize, Identity def get_model(name, num_classes, fc_input_dim_scale=1): # CIFAR10 w/ Normalize Layer norm = Normalize(mean=[0.4914, 0.4822, 0.4465...
1,768
45.552632
131
py
catastrophic-overfitting
catastrophic-overfitting-main/defenses/loaders/base_loader.py
import torchvision.utils import torchvision.datasets as dsets import torchvision.transforms as transforms from .datasets import Datasets r""" Arguments: data_name (str): model to train. root (str): strength of the attack or maximum perturbation. val_info (int or float or list): ratio or index of the v...
2,563
36.15942
94
py
catastrophic-overfitting
catastrophic-overfitting-main/defenses/loaders/datasets.py
import random import torch from torch.utils.data import DataLoader, Subset from torch.utils.data.sampler import SubsetRandomSampler import torchvision.utils import torchvision.datasets as dsets import torchvision.transforms as transforms class Datasets() : def __init__(self, data_name, root='./data', ...
20,157
38.52549
114
py
catastrophic-overfitting
catastrophic-overfitting-main/defenses/models/preact_resnet.py
import math import torch import torch.nn as nn import torch.nn.functional as F # Modified from https://github.com/kuangliu/pytorch-cifar/tree/master/models class PreActBlock(nn.Module): '''Pre-activation version of the BasicBlock.''' expansion = 1 def __init__(self, in_planes, planes, stride=1): s...
3,781
38.810526
102
py
catastrophic-overfitting
catastrophic-overfitting-main/defenses/models/wide_resnet.py
import math import torch import torch.nn as nn import torch.nn.functional as F # Modified from https://github.com/bearpaw/pytorch-classification/blob/master/models/cifar/wrn.py class BasicBlock(nn.Module): def __init__(self, in_planes, out_planes, stride, dropRate=0.0): super(BasicBlock, self).__init__() ...
3,921
44.08046
116
py
catastrophic-overfitting
catastrophic-overfitting-main/defenses/models/normalize.py
# Modified from https://github.com/bearpaw/pytorch-classification/blob/master/models/cifar/wrn.py import math import torch import torch.nn as nn import torch.nn.functional as F class Normalize(nn.Module): def __init__(self, mean, std): super(Normalize, self).__init__() self.register_buffer('mean', ...
967
28.333333
97
py
catastrophic-overfitting
catastrophic-overfitting-main/defenses/trainers/adv_trainer.py
import os import torch # from torchhk import Trainer from .trainer import Trainer from torchattacks.attack import Attack from torchattacks import VANILA, FGSM, PGD, GN r""" Trainer for Adversarial Training. Attributes: self.model : model. self.device : device where model is. self.optimizer : optimizer. ...
2,877
29.946237
83
py
catastrophic-overfitting
catastrophic-overfitting-main/defenses/trainers/co_adv_trainer.py
import torch import torch.nn as nn from torchattacks.attack import Attack from .adv_trainer import AdvTrainer r""" 'Understanding Catastrophic Overfitting in Single-step Adversarial Training' [https://arxiv.org/abs/2010.01799] Attributes: self.model : model. self.device : device where model is. self.opt...
5,929
35.832298
118
py
catastrophic-overfitting
catastrophic-overfitting-main/defenses/trainers/fast_adv_trainer.py
import torch import torch.nn as nn from torchattacks import FFGSM from .adv_trainer import AdvTrainer r""" 'Fast is better than free: Revisiting adversarial training' [https://arxiv.org/abs/2001.03994] Attributes: self.model : model. self.device : device where model is. self.optimizer : optimizer. s...
1,627
26.133333
79
py
catastrophic-overfitting
catastrophic-overfitting-main/defenses/trainers/trainer.py
import os import torch from torch.optim import * from torch.optim.lr_scheduler import * from torchhk import RecordManager r""" Trainer. Attributes: self.model : model. self.device : device where model is. self.optimizer : optimizer. self.scheduler : scheduler (* Automatically Updated). self....
9,113
35.166667
119
py
urnng
urnng-master/data.py
#!/usr/bin/env python3 import numpy as np import torch import pickle class Dataset(object): def __init__(self, data_file): data = pickle.load(open(data_file, 'rb')) #get text data self.sents = self._convert(data['source']).long() self.other_data = data['other_data'] self.sent_lengths = self._convert(...
1,585
35.883721
90
py
urnng
urnng-master/eval_ppl.py
#!/usr/bin/env python3 import sys import os import argparse import json import random import shutil import copy import torch from torch import cuda import torch.nn as nn from torch.autograd import Variable from torch.nn.parameter import Parameter import torch.nn.functional as F import numpy as np import time import ...
3,753
35.446602
116
py
urnng
urnng-master/TreeCRF.py
#!/usr/bin/env python3 import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import itertools import utils import random class ConstituencyTreeCRF(nn.Module): def __init__(self): super(ConstituencyTreeCRF, self).__init__() self.huge = 1e9 def logadd(self, x, y): d = ...
6,934
32.995098
97
py