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 |
|---|---|---|---|---|---|---|
pase | pase-master/ASR/neural_networks.py | ##########################################################
# pytorch-kaldi v.0.1
# Mirco Ravanelli, Titouan Parcollet
# Mila, University of Montreal
# October 2018
##########################################################
import torch
import torch.nn.functional as F
import torch... | 61,209 | 34.463499 | 304 | py |
pase | pase-master/ASR/utils.py | ##########################################################
# pytorch-kaldi v.0.1
# Mirco Ravanelli, Titouan Parcollet
# Mila, University of Montreal
# October 2018
##########################################################
import configparser
import sys
import os.path
import rando... | 94,244 | 39.241247 | 248 | py |
pase | pase-master/ASR/run_minichime5_fast.py | # Mirco Ravanelli
# Mila, June 2019
# This script runs a simple speech recognition experiment on the top of PASE features.
# The results are reported in terms of Frame Error Rate over phonemes (context-independent).
# This system is not designed for an extensive evaluation of PASE features, but mainly for quickly mo... | 10,349 | 28.073034 | 456 | py |
pase | pase-master/ASR/run_TIMIT_full_decoding.py | #
# To run a TIMIT experiment, go to the ASR folder and execute the following command:
#
# python run_TIMIT_full_decoding.py ../cfg/frontend/PASE+.cfg ../FE_e199.ckpt $SLURM_TMPDIR/TIMIT/ TIMIT_asr_exp cfg/MLP_PASE.cfg cfg/decoder.cfg
#
# Importing libraries
import os
import sys
from neural_networks import MLP, cont... | 18,591 | 31.732394 | 146 | py |
pase | pase-master/ASR/data_io.py | ##########################################################
# pytorch-kaldi v.0.1
# Mirco Ravanelli, Titouan Parcollet
# Mila, University of Montreal
# October 2018
##########################################################
import numpy as np
import sys
from utils import compute_cw... | 51,195 | 40.998359 | 244 | py |
pase | pase-master/ASR/waveminionet/losses.py | import torch
import torch.nn as nn
class RegressionLoss(object):
def __call__(self, pred, gtruth):
loss = self.criterion(pred, gtruth)
return loss
class AdversarialLoss(object):
def __init__(self, z_gen=torch.randn,
loss='L2'):
self.z_gen = z_gen
self.loss =... | 1,535 | 27.444444 | 66 | py |
pase | pase-master/ASR/waveminionet/utils.py | import json
import torch
import torch.nn as nn
def waveminionet_parser(cfg_fname):
with open(cfg_fname, 'r') as cfg_f:
cfg_all = json.load(cfg_f)
# change loss section to select those
# from nn package
for i, cfg in enumerate(cfg_all):
cfg_all[i]['loss'] = getattr(nn,
... | 406 | 26.133333 | 62 | py |
pase | pase-master/ASR/waveminionet/dataset.py | import torch
from torch.utils.data import Dataset
import soundfile as sf
import json
import librosa
import os
import random
import numpy as np
from collections import defaultdict
class DictCollater(object):
def __init__(self, batching_keys=['chunk',
'chunk_ctxt',
... | 6,865 | 33.852792 | 84 | py |
pase | pase-master/ASR/waveminionet/transforms.py | import torch
import numpy as np
import random
import pysptk
import librosa
import pickle
from ahoproc_tools.interpolate import interpolation
def norm_and_scale(wav):
assert isinstance(wav, torch.Tensor), type(wav)
wav = wav / torch.max(torch.abs(wav))
return wav * torch.rand(1)
def format_package(x):
... | 7,884 | 32.130252 | 79 | py |
pase | pase-master/ASR/waveminionet/models/core.py | from .modules import *
from .frontend import *
from .minions import *
from ..losses import *
from tensorboardX import SummaryWriter
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
import numpy as np
import random
import json
import timeit
import os
class Waveminionet(Model):
def __ini... | 26,313 | 46.073345 | 88 | py |
pase | pase-master/ASR/waveminionet/models/modules.py | import torch
import torch.nn as nn
import math
import torch.nn.functional as F
from torch.nn.utils.spectral_norm import spectral_norm
import numpy as np
import json
import os
def build_norm_layer(norm_type, param=None, num_feats=None):
if norm_type == 'bnorm':
return nn.BatchNorm1d(num_feats)
elif nor... | 28,254 | 34.230673 | 131 | py |
pase | pase-master/ASR/waveminionet/models/minions.py | import torch
import torch.nn as nn
from .frontend import WaveFe
from .modules import *
import torch.nn.functional as F
import json
import random
def minion_maker(cfg):
mtype = cfg.pop('type', 'mlp')
if mtype == 'mlp':
minion = MLPMinion(**cfg)
elif mtype == 'decoder':
minion = DecoderMinio... | 8,084 | 30.705882 | 74 | py |
pase | pase-master/ASR/waveminionet/models/decoders.py | import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from .frontend import *
from .minions import *
import random
class SpectrumLM(nn.Module):
""" RNN lang model for spectrum frame preds """
def __init__(self, rnn_size, rnn_layers, out_dim,
dro... | 2,413 | 33 | 69 | py |
pase | pase-master/ASR/waveminionet/models/frontend.py | import torch
import torch.nn.functional as F
import torch.nn as nn
import json
if __name__ == '__main__':
from modules import *
else:
from .modules import *
def wf_builder(cfg_path):
with open(cfg_path, 'r') as cfg_f:
cfg = json.load(cfg_f)
return WaveFe(**cfg)
class WaveFe(Model):
"... | 3,677 | 31.548673 | 72 | py |
pase | pase-master/ASR/waveminionet/models/encoders.py | import torch
import torch.nn as nn
from .core import LayerNorm
class AhoCNNEncoder(nn.Module):
def __init__(self, input_dim, kwidth=3, dropout=0.5, layer_norm=False):
super().__init__()
pad = (kwidth - 1) // 2
if layer_norm:
norm_layer = LayerNorm
else:
no... | 2,834 | 29.815217 | 75 | py |
RelativeNAS | RelativeNAS-master/test.py | import os
import sys
import glob
import numpy as np
import torch
import utils
import logging
import argparse
import torch.nn as nn
import genotypes
import torch.utils
import torchvision.datasets as dset
import torch.backends.cudnn as cudnn
from model import NetworkCIFAR as Network
parser = argparse.ArgumentParser("ci... | 4,131 | 35.245614 | 104 | py |
RelativeNAS | RelativeNAS-master/train_imagenet.py | import os
import sys
import time
import glob
import numpy as np
import torch
import utils
import logging
import argparse
import torch.nn as nn
import torch.utils
import torchvision.datasets as dset
import torch.backends.cudnn as cudnn
from dataset.imagenet_scripts import imagenet_data
from torch.autograd import Variab... | 8,166 | 45.141243 | 127 | py |
RelativeNAS | RelativeNAS-master/utils.py | import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
class AvgrageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.avg = 0
self.sum = 0
self.cnt = 0
def update(self, v... | 3,970 | 26.964789 | 109 | py |
RelativeNAS | RelativeNAS-master/model.py | from operations import *
from utils import drop_path
class Cell(nn.Module):
def __init__(self, genotype, C_prev_prev, C_prev, C, reduction, reduction_prev):
super(Cell, self).__init__()
# print(C_prev_prev, C_prev, C)
if reduction_prev:
self.preprocess0 = FactorizedReduce(C_p... | 7,459 | 34.188679 | 96 | py |
RelativeNAS | RelativeNAS-master/model_search.py | from genotypes import PRIMITIVES
from operations import *
from utils import drop_path
class Cell(nn.Module):
def __init__(self, genotype, C_prev_prev, C_prev, C, reduction, reduction_prev):
super(Cell, self).__init__()
if reduction_prev:
self.preprocess0 = FactorizedReduce(C_prev_pre... | 4,475 | 33.96875 | 89 | py |
RelativeNAS | RelativeNAS-master/train_search.py | import os
import sys
import time
import glob
import numpy as np
import torch
import utils
import logging
import argparse
import torch.nn as nn
import torch.utils
import torchvision.datasets as dset
import torch.backends.cudnn as cudnn
from slow_fast_learning import init_pop, cal_center, gen_pairs, decode, update_state... | 9,758 | 36.106464 | 105 | py |
RelativeNAS | RelativeNAS-master/test_imagenet.py | import argparse
import logging
import os
import pprint
import sys
import time
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
from configs.imagenet_val_cfg import cfg
from dataset.imagenet_scripts import imagenet_data
from tools import utils
from tools.multadds_count import comp_multadds
impor... | 3,263 | 41.38961 | 142 | py |
RelativeNAS | RelativeNAS-master/train.py | import os
import sys
import time
import glob
import numpy as np
import torch
import utils
import logging
import argparse
import torch.nn as nn
import genotypes
import torch.utils
import torchvision.datasets as dset
import torch.backends.cudnn as cudnn
from model import NetworkCIFAR as Network
parser = argparse.Argume... | 7,258 | 37.611702 | 106 | py |
RelativeNAS | RelativeNAS-master/operations.py | import torch
import torch.nn as nn
OPS = {
'none': lambda C, stride, affine: Zero(stride),
'avg_pool_3x3': lambda C, stride, affine: nn.AvgPool2d(3, stride=stride, padding=1, count_include_pad=False),
'max_pool_3x3': lambda C, stride, affine: nn.MaxPool2d(3, stride=stride, padding=1),
'skip_connect': l... | 3,993 | 35.981481 | 116 | py |
RelativeNAS | RelativeNAS-master/tools/lr_scheduler.py | import torch
from torch.optim.lr_scheduler import CosineAnnealingLR
from torch.optim.optimizer import Optimizer
import math
class CosineRestartAnnealingLR(object):
# decay as step
# T_max refers to the max update step
def __init__(self, optimizer, T_max, lr_period, lr_step, eta_min=0, last_step=-1,
... | 5,320 | 36.20979 | 131 | py |
RelativeNAS | RelativeNAS-master/tools/utils.py | import logging
import os
import shutil
import sys
import logging
import time
import numpy as np
import torch
import torch.nn as nn
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.avg = 0
self.sum = 0
self.cnt = 0
def update(self, val, n... | 3,721 | 26.57037 | 110 | py |
RelativeNAS | RelativeNAS-master/tools/multadds_count.py | import torch
# Original implementation:
# https://github.com/warmspringwinds/pytorch-segmentation-detection/blob/master/pytorch_segmentation_detection/utils/flops_benchmark.py
# ---- Public functions
def comp_multadds(model, input_size=(3,224,224), half=False):
input_size = (1,) + tuple(input_size)
model = m... | 8,761 | 30.978102 | 136 | py |
RelativeNAS | RelativeNAS-master/dataset/imagenet_scripts/lmdb_dataset.py | import os
import cv2
import msgpack
import numpy as np
import torch.utils.data as data
from PIL import Image
import lmdb
class Datum(object):
def __init__(self, shape=None, image=None, label=None):
self.shape = shape
self.image = image
self.label = label
def SerializeToString(self):... | 4,426 | 34.134921 | 143 | py |
RelativeNAS | RelativeNAS-master/dataset/imagenet_scripts/prefetch_data.py | import torch
import numpy as np
import time
class data_prefetcher():
def __init__(self, loader, mean=None, std=None, is_cutout=False, cutout_length=16):
self.loader = iter(loader)
self.stream = torch.cuda.Stream()
if mean is None:
self.mean = torch.tensor([0.485 * 255, 0.456 * ... | 3,670 | 39.340659 | 99 | py |
RelativeNAS | RelativeNAS-master/dataset/imagenet_scripts/imagenet_data.py | import os
import torch
import torchvision
import torchvision.transforms as transforms
from . import lmdb_dataset
from . import torchvision_extension as transforms_extension
from .prefetch_data import fast_collate
class ImageNet12(object):
def __init__(self, trainFolder, testFolder, num_workers=8, pin_memory=Tr... | 5,375 | 46.157895 | 181 | py |
RelativeNAS | RelativeNAS-master/dataset/imagenet_scripts/torchvision_extension.py | import random
import torchvision.transforms as transforms
from torchvision.transforms import functional as F
#In this file some more transformations (apart from the ones defined in torchvision.transform)
#are added. Particularly helpful to train imagenet, and in the style of the transforms
#used by fb.resnet https://g... | 1,592 | 31.510204 | 139 | py |
RelativeNAS | RelativeNAS-master/run_apis/validation.py | import argparse
import logging
import os
import pprint
import sys
import time
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
from configs.imagenet_val_cfg import cfg
from dataset import imagenet_data
from models import model_derived
from tools import utils
from tools.multadds_count import com... | 2,754 | 35.733333 | 99 | py |
RelativeNAS | RelativeNAS-master/run_apis/retrain.py | import argparse
import ast
import logging
import os
import pprint
import sys
import time
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
from tensorboardX import SummaryWriter
from configs.imagenet_train_cfg import cfg as config
from dataset import imagenet_data
from models ... | 5,285 | 38.744361 | 157 | py |
RelativeNAS | RelativeNAS-master/run_apis/trainer.py | import logging
import time
import torch.nn as nn
from dataset.prefetch_data import data_prefetcher
from tools import utils
class Trainer(object):
def __init__(self, train_data, val_data, criterion=None, config=None, report_freq=None):
self.train_data = train_data
self.val_data = val_data
... | 4,233 | 38.570093 | 185 | py |
NLR | NLR-master/src/main.py | # coding=utf-8
import argparse
import logging
import sys
import numpy as np
import os
import torch
import datetime
import pickle
import copy
from utils import utils
from utils.global_p import *
# # import data_loaders
from data_loaders.DataLoader import DataLoader
from data_loaders.ProLogicDL import ProLogicDL
# # ... | 16,937 | 46.181058 | 200 | py |
NLR | NLR-master/src/data_processors/DataProcessor.py | # coding=utf-8
import copy
from utils import utils
import numpy as np
import logging
import pandas as pd
from tqdm import tqdm
import torch
from collections import defaultdict, Counter
from utils.global_p import *
class DataProcessor(object):
# data dict中存储模型所需特征信息的key,需要转换为tensor
# The key to store the featu... | 23,923 | 43.801498 | 237 | py |
NLR | NLR-master/src/data_processors/ProLogicRecDP.py | # coding=utf-8
from utils import utils
import numpy as np
import torch
from data_processors.DataProcessor import DataProcessor
from data_processors.HistoryDP import HistoryDP
from utils.global_p import *
class ProLogicRecDP(HistoryDP):
@staticmethod
def parse_dp_args(parser):
"""
数据处理生成batch的命... | 2,873 | 41.264706 | 237 | py |
NLR | NLR-master/src/data_processors/RNNLogicDP.py | # coding=utf-8
import copy
from utils import utils
import numpy as np
import logging
import pandas as pd
from tqdm import tqdm
import torch
from collections import defaultdict
from data_processors.DataProcessor import DataProcessor
from utils.global_p import *
import re
class RNNLogicDP(DataProcessor):
# data dic... | 2,275 | 34.015385 | 142 | py |
NLR | NLR-master/src/data_processors/ProLogicDP.py | # coding=utf-8
import copy
from utils import utils
import numpy as np
import logging
import pandas as pd
from tqdm import tqdm
import torch
from collections import defaultdict
from data_processors.DataProcessor import DataProcessor
from utils.global_p import *
import re
class ProLogicDP(DataProcessor):
# data dic... | 3,562 | 39.954023 | 142 | py |
NLR | NLR-master/src/data_processors/HistoryDP.py | # coding=utf-8
import copy
from utils import utils
import numpy as np
import logging
import pandas as pd
from tqdm import tqdm
import torch
from collections import defaultdict
from data_processors.DataProcessor import DataProcessor
from utils.global_p import *
class HistoryDP(DataProcessor):
# data dict中存储模型所需特征信... | 7,063 | 45.169935 | 237 | py |
NLR | NLR-master/src/models/CNNLogic.py | # coding=utf-8
import torch
import torch.nn.functional as F
from models.DeepModel import DeepModel
from utils.global_p import *
class CNNLogic(DeepModel):
include_id = False
include_user_features = False
include_item_features = False
include_context_features = False
data_loader = 'ProLogicDL'
... | 5,211 | 43.547009 | 141 | py |
NLR | NLR-master/src/models/NARM.py | # coding=utf-8
import torch
import torch.nn.functional as F
from models.GRU4Rec import GRU4Rec
from utils import utils
from utils.global_p import *
class NARM(GRU4Rec):
data_processor = 'HistoryDP' # Default data_processor
@staticmethod
def parse_model_args(parser, model_name='NARM'):
parser.ad... | 5,333 | 47.93578 | 118 | py |
NLR | NLR-master/src/models/NLR.py | # coding=utf-8
import torch
import torch.nn.functional as F
import logging
from sklearn.metrics import *
import numpy as np
from models.BaseModel import BaseModel
from utils import utils
from utils.global_p import *
class NLR(BaseModel):
include_id = False
include_user_features = False
include_item_featu... | 13,665 | 43.660131 | 141 | py |
NLR | NLR-master/src/models/RNNLogic.py | # coding=utf-8
import torch
import torch.nn.functional as F
from models.DeepModel import DeepModel
from utils.global_p import *
class RNNLogic(DeepModel):
include_id = False
include_user_features = False
include_item_features = False
include_context_features = False
data_loader = 'ProLogicDL'
... | 5,239 | 41.95082 | 141 | py |
NLR | NLR-master/src/models/NLRRec.py | # coding=utf-8
import torch
import torch.nn.functional as F
import logging
from sklearn.metrics import *
import numpy as np
from models.NLR import NLR
from utils import utils
from utils.global_p import *
class NLRRec(NLR):
include_id = True
include_user_features = False
include_item_features = False
... | 13,795 | 46.737024 | 147 | py |
NLR | NLR-master/src/models/STAMP.py | # coding=utf-8
import torch
import torch.nn.functional as F
from models.GRU4Rec import GRU4Rec
from utils import utils
from utils.global_p import *
class STAMP(GRU4Rec):
data_processor = 'HistoryDP' # Default data_processor
@staticmethod
def parse_model_args(parser, model_name='STAMP'):
parser.... | 4,483 | 46.2 | 118 | py |
NLR | NLR-master/src/models/SVDPP.py | # coding=utf-8
import torch
import torch.nn.functional as F
from models.RecModel import RecModel
from utils import utils
from utils.global_p import *
class SVDPP(RecModel):
data_processor = 'HistoryDP' # Default data_processor
def _init_weights(self):
self.uid_embeddings = torch.nn.Embedding(self.u... | 2,578 | 41.983333 | 118 | py |
NLR | NLR-master/src/models/GRU4Rec.py | # coding=utf-8
import torch
import torch.nn.functional as F
from models.RecModel import RecModel
from utils import utils
from utils.global_p import *
class GRU4Rec(RecModel):
data_processor = 'HistoryDP' # Default data_processor
@staticmethod
def parse_model_args(parser, model_name='GRU4Rec'):
... | 4,987 | 46.056604 | 118 | py |
NLR | NLR-master/src/models/BaseModel.py | # coding=utf-8
import torch
import logging
from sklearn.metrics import *
import numpy as np
import torch.nn.functional as F
import os
import pandas as pd
from tqdm import tqdm
from collections import defaultdict
from utils.rank_metrics import *
from utils.global_p import *
from utils import utils
class BaseModel(tor... | 16,033 | 40.324742 | 158 | py |
NLR | NLR-master/src/models/DeepModel.py | # coding=utf-8
import torch
import torch.nn.functional as F
import logging
from sklearn.metrics import *
import numpy as np
from models.BaseModel import BaseModel
from utils import utils
from utils.global_p import *
class DeepModel(BaseModel):
@staticmethod
def parse_model_args(parser, model_name='DeepModel'... | 2,219 | 41.692308 | 91 | py |
NLR | NLR-master/src/models/BiasedMF.py | # coding=utf-8
import torch
import torch.nn.functional as F
from models.RecModel import RecModel
from utils import utils
from utils.global_p import *
class BiasedMF(RecModel):
def _init_weights(self):
self.uid_embeddings = torch.nn.Embedding(self.user_num, self.ui_vector_size)
self.iid_embeddings... | 1,505 | 35.731707 | 91 | py |
NLR | NLR-master/src/models/RecModel.py | # coding=utf-8
import torch
import torch.nn.functional as F
from models.BaseModel import BaseModel
from utils import utils
from utils.global_p import *
class RecModel(BaseModel):
include_id = False
include_user_features = False
include_item_features = False
include_context_features = False
@stat... | 1,883 | 35.941176 | 84 | py |
NLR | NLR-master/src/runners/BaseRunner.py | # coding=utf-8
import torch
import logging
from time import time
from utils import utils
from utils.global_p import *
from tqdm import tqdm
import gc
import numpy as np
import copy
import os
class BaseRunner(object):
@staticmethod
def parse_runner_args(parser):
"""
跑模型的命令行参数
:param pa... | 23,165 | 44.334638 | 162 | py |
NLR | NLR-master/src/utils/utils.py | # coding=utf-8
import logging
import numpy as np
import torch
from utils.global_p import *
import os
import inspect
LOWER_METRIC_LIST = ["rmse", 'mae']
def parse_global_args(parser):
"""
全局命令行参数
:param parser:
:return:
Global command-line parameters
:param parser:
:return:
"""
... | 6,327 | 24.011858 | 146 | py |
NLR | NLR-master/src/utils/components.py | # coding=utf-8
import torch
import torch.nn.functional as F
from utils import utils
def qk_attention(query, key, value, valid=None, beta=1):
"""
:param query: ? * l * a
:param key: ? * l * a
:param value: ? * l * v
:param valid: ? * l
:param beta: smooth softmax
:return: ? * v
"""
... | 4,853 | 38.145161 | 112 | py |
SimTSC | SimTSC-main/train_resnet.py | import os
import argparse
import numpy as np
import torch
from src.utils import read_dataset_from_npy, Logger
from src.resnet.model import ResNet, ResNetTrainer
data_dir = './tmp'
log_dir = './logs'
multivariate_datasets = ['CharacterTrajectories', 'ECG', 'KickvsPunch', 'NetFlow']
def train(X_train, y_train, X_tes... | 2,432 | 31.878378 | 155 | py |
SimTSC | SimTSC-main/train_simtsc.py | import os
import argparse
import numpy as np
import torch
from src.utils import read_dataset_from_npy, Logger
from src.simtsc.model import SimTSC, SimTSCTrainer
data_dir = './tmp'
log_dir = './logs'
multivariate_datasets = ['CharacterTrajectories', 'ECG', 'KickvsPunch', 'NetFlow']
def train(X, y, train_idx, test_i... | 2,885 | 33.357143 | 155 | py |
SimTSC | SimTSC-main/src/simtsc/model.py | import os
import uuid
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
import torch.utils.data
class SimTSCTrainer:
def __init__(self, device, logger):
... | 9,595 | 38.817427 | 180 | py |
SimTSC | SimTSC-main/src/resnet/model.py | import os
import uuid
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
class ResNetTrainer:
def __init__(self, device, logger):
self.device = device
self.logger = logger
self.tmp_dir = 'tmp'
if not os.path.exists... | 4,459 | 32.037037 | 142 | py |
efficientnet | efficientnet-master/scripts/load_efficientnet.py | #!/usr/bin/env bash
# =============================================================================
# Copyright 2019 Pavel Yakubovskiy, Sasha Illarionov. 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 ob... | 5,259 | 31.073171 | 105 | py |
efficientnet | efficientnet-master/tests/test_model.py | import os
import sys
import pytest
import numpy as np
from skimage.io import imread
sys.path.insert(0, '.')
if os.environ.get('TF_KERAS'):
import efficientnet.tfkeras as efn
from tensorflow.keras.models import load_model
else:
import efficientnet.keras as efn
from keras.models import load_model
PANDA... | 1,911 | 24.837838 | 61 | py |
efficientnet | efficientnet-master/efficientnet/weights.py | IMAGENET_WEIGHTS_PATH = (
'https://github.com/Callidior/keras-applications/'
'releases/download/efficientnet/')
IMAGENET_WEIGHTS_HASHES = {
'efficientnet-b0': ('163292582f1c6eaca8e7dc7b51b01c61'
'5b0dbc0039699b4dcd0b975cc21533dc',
'c1421ad80a9fc67c2cc4000f666... | 2,947 | 56.803922 | 96 | py |
efficientnet | efficientnet-master/efficientnet/keras.py | from . import inject_keras_modules, init_keras_custom_objects
from . import model
from .preprocessing import center_crop_and_resize
EfficientNetB0 = inject_keras_modules(model.EfficientNetB0)
EfficientNetB1 = inject_keras_modules(model.EfficientNetB1)
EfficientNetB2 = inject_keras_modules(model.EfficientNetB2)
Effici... | 768 | 39.473684 | 63 | py |
efficientnet | efficientnet-master/efficientnet/model.py | # Copyright 2019 The TensorFlow Authors, Pavel Yakubovskiy, Björn Barz. 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... | 24,218 | 36.901408 | 109 | py |
efficientnet | efficientnet-master/efficientnet/__init__.py | # Copyright 2019 The TensorFlow Authors, Pavel Yakubovskiy. 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 ... | 2,711 | 30.172414 | 80 | py |
efficientnet | efficientnet-master/efficientnet/tfkeras.py | from . import inject_tfkeras_modules, init_tfkeras_custom_objects
from . import model
from .preprocessing import center_crop_and_resize
EfficientNetB0 = inject_tfkeras_modules(model.EfficientNetB0)
EfficientNetB1 = inject_tfkeras_modules(model.EfficientNetB1)
EfficientNetB2 = inject_tfkeras_modules(model.EfficientNet... | 794 | 40.842105 | 65 | py |
OFA | OFA-main/evaluate.py | #!/usr/bin/env python3 -u
# Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
import logging
import os
import sys
import numpy as np
import torch
from fairseq import distributed_utils, options, tasks, ... | 7,436 | 35.635468 | 217 | py |
OFA | OFA-main/train.py | #!/usr/bin/env python3 -u
# Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
"""
Train a new model on one or across multiple GPUs.
"""
import argparse
import logging
import math
import os
import sys... | 19,304 | 34.8829 | 109 | py |
OFA | OFA-main/trainer.py | # Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
"""
Train a network across multiple GPUs.
"""
import contextlib
import logging
import sys
import time
from argparse import Namespace
from itertools... | 62,409 | 39.737598 | 171 | py |
OFA | OFA-main/criterions/scst_loss.py | # Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
import math
import string
from dataclasses import dataclass, field
from collections import OrderedDict
from typing import Optional
import torch
fro... | 10,744 | 37.102837 | 118 | py |
OFA | OFA-main/criterions/label_smoothed_encouraging_loss.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 math
from dataclasses import dataclass, field
from typing import Optional
import torch
import torch.nn.functional as F
import numpy as... | 16,420 | 40.467172 | 134 | py |
OFA | OFA-main/criterions/label_smoothed_cross_entropy.py | # Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
import math
from dataclasses import dataclass, field
from typing import Optional
import torch
import torch.nn.functional as F
import numpy as np
fr... | 14,199 | 40.27907 | 134 | py |
OFA | OFA-main/criterions/speech_pretrain_loss.py | # Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
import math
from dataclasses import dataclass, field
from typing import Optional
import torch
import torch.nn.functional as F
import numpy as np
from... | 20,129 | 41.025052 | 149 | py |
OFA | OFA-main/criterions/clip_scst_loss.py | # Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
import math
from dataclasses import dataclass, field
from typing import Optional
from PIL import Image
from torchvision import transforms
import to... | 10,563 | 37 | 118 | py |
OFA | OFA-main/models/sequence_generator.py | # Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
import math
from typing import Dict, List, Optional
import sys
import torch
import torch.nn as nn
from fairseq import search, utils
from fairseq.mo... | 43,774 | 40.258247 | 127 | py |
OFA | OFA-main/models/search.py | # Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
import math
from typing import List, Optional
import torch
import torch.nn as nn
from fairseq.token_generation_constraints import (
ConstraintS... | 31,331 | 37.444172 | 100 | py |
OFA | OFA-main/models/clip/clip.py | import hashlib
import os
import urllib
import warnings
from typing import Any, Union, List
from pkg_resources import packaging
import torch
from PIL import Image
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
from tqdm import tqdm
from .model import build_model
from .simple_tokeni... | 8,555 | 36.2 | 149 | py |
OFA | OFA-main/models/clip/model.py | from collections import OrderedDict
from typing import Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1):
super().__init__()
# all conv layers have strid... | 17,326 | 38.559361 | 120 | py |
OFA | OFA-main/models/ofa/ofa_speech.py | import logging
logger = logging.getLogger(__name__)
from dataclasses import dataclass, field
import torch.distributed as dist
from fairseq.data.data_utils import compute_mask_indices
from fairseq.models.wav2vec.wav2vec2 import (
Wav2Vec2Config,
TransformerEncoder as SpeechTransformerEncoder,
make_conv_pos
... | 46,244 | 40.549865 | 120 | py |
OFA | OFA-main/models/ofa/resnet.py | import torch
import torch.nn as nn
def drop_path(x, drop_prob: float = 0., training: bool = False):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
the original name is m... | 9,081 | 39.364444 | 113 | py |
OFA | OFA-main/models/ofa/unify_multihead_attention.py | # Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
import math
from typing import Dict, Optional, Tuple
import torch
import torch.nn.functional as F
from fairseq import utils
from fairseq.incrementa... | 21,275 | 39.680688 | 110 | py |
OFA | OFA-main/models/ofa/frozen_bn.py | # Modified from detectron2: https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py#L13
import torch
from torch import nn
from torch.nn import functional as F
class FrozenBatchNorm2d(nn.Module):
"""
BatchNorm2d where the batch statistics and the affine parameters are fixed.
... | 3,481 | 41.987654 | 120 | py |
OFA | OFA-main/models/ofa/ofa.py | # Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
"""
OFA
"""
from typing import Optional
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import util... | 19,120 | 42.755149 | 98 | py |
OFA | OFA-main/models/ofa/vit.py | from collections import OrderedDict
import torch
import torch.nn.functional as F
from torch import nn
from fairseq.modules import LayerNorm
class QuickGELU(nn.Module):
def forward(self, x: torch.Tensor):
return x * torch.sigmoid(1.702 * x)
class ResidualAttentionBlock(nn.Module):
def __init__(self, ... | 3,640 | 30.938596 | 86 | py |
OFA | OFA-main/models/ofa/unify_transformer.py | # Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
import math
import random
from typing import Any, Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from... | 87,035 | 43.360856 | 122 | py |
OFA | OFA-main/models/ofa/unify_transformer_layer.py | # Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
from typing import Dict, List, Optional
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.modules import LayerNorm
from fai... | 25,301 | 40.141463 | 135 | py |
OFA | OFA-main/models/taming/modules/util.py | import torch
import torch.nn as nn
def count_params(model):
total_params = sum(p.numel() for p in model.parameters())
return total_params
class ActNorm(nn.Module):
def __init__(self, num_features, logdet=False, affine=True,
allow_reverse_init=False):
assert affine
super(... | 3,847 | 28.374046 | 85 | py |
OFA | OFA-main/models/taming/modules/vqvae/quantize.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch import einsum
from einops import rearrange
class VectorQuantizer(nn.Module):
"""
see https://github.com/MishaLaskin/vqvae/blob/d761a999e2267766400dc646d82d3ac3657771d4/models/quantizer.py
_____________________... | 18,182 | 39.769058 | 110 | py |
OFA | OFA-main/models/taming/modules/discriminator/model.py | import functools
import torch.nn as nn
from models.taming.modules.util import ActNorm
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find('BatchNorm') != -1:
nn.init.normal_(m.weight.data, 1.... | 2,557 | 36.617647 | 116 | py |
OFA | OFA-main/models/taming/modules/misc/coord.py | import torch
class CoordStage(object):
def __init__(self, n_embed, down_factor):
self.n_embed = n_embed
self.down_factor = down_factor
def eval(self):
return self
def encode(self, c):
"""fake vqmodel interface"""
assert 0.0 <= c.min() and c.max() <= 1.0
b,c... | 904 | 27.28125 | 79 | py |
OFA | OFA-main/models/taming/modules/diffusionmodules/model.py | # pytorch_diffusion + derived encoder decoder
import math
import torch
import torch.nn as nn
import numpy as np
def get_timestep_embedding(timesteps, embedding_dim):
"""
This matches the implementation in Denoising Diffusion Probabilistic Models:
From Fairseq.
Build sinusoidal embeddings.
This mat... | 30,221 | 37.895753 | 121 | py |
OFA | OFA-main/models/taming/modules/losses/lpips.py | """Stripped version of https://github.com/richzhang/PerceptualSimilarity/tree/master/models"""
import torch
import torch.nn as nn
from torchvision import models
from collections import namedtuple
from models.taming.util import get_ckpt_path
class LPIPS(nn.Module):
# Learned perceptual metric
def __init__(se... | 4,839 | 38.032258 | 104 | py |
OFA | OFA-main/models/taming/modules/losses/segmentation.py | import torch.nn as nn
import torch.nn.functional as F
class BCELoss(nn.Module):
def forward(self, prediction, target):
loss = F.binary_cross_entropy_with_logits(prediction,target)
return loss, {}
class BCELossWithQuant(nn.Module):
def __init__(self, codebook_weight=1.):
super().__ini... | 816 | 34.521739 | 82 | py |
OFA | OFA-main/models/taming/modules/losses/vqperceptual.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from models.taming.modules.losses.lpips import LPIPS
from models.taming.modules.discriminator.model import NLayerDiscriminator, weights_init
class DummyLoss(nn.Module):
def __init__(self):
super().__init__()
def adopt_weight(weight, glo... | 6,193 | 44.211679 | 113 | py |
OFA | OFA-main/models/taming/models/vqgan.py | import torch
import torch.nn.functional as F
import pytorch_lightning as pl
from models.taming.util import instantiate_from_config
from models.taming.modules.diffusionmodules.model import Encoder, Decoder
from models.taming.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer
from models.taming.modules.v... | 10,657 | 39.524715 | 120 | py |
OFA | OFA-main/run_scripts/image_gen/generate_code.py | import sys
sys.path.append('../../')
import argparse
import base64
from io import BytesIO
from data.file_dataset import FileDataset
from PIL import Image, ImageFile
from torchvision import transforms
from omegaconf import OmegaConf
from models.taming.models.vqgan import GumbelVQ
import os
import torch
from torch.util... | 4,439 | 31.647059 | 110 | py |
OFA | OFA-main/run_scripts/image_gen/inception_score.py | import os
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
import torchvision.transforms as transforms
from torchvision.models.inception import inception_v3
from scipy.stats import entropy
fr... | 3,318 | 32.525253 | 90 | py |
OFA | OFA-main/run_scripts/image_gen/fid_score.py | #!/usr/bin/env python3
"""Calculates the Frechet Inception Distance (FID) to evalulate GANs
The FID metric calculates the distance between two distributions of images.
Typically, we have summary statistics (mean & covariance matrix) of one
of these distributions, while the 2nd distribution is given by a GAN.
When run... | 10,717 | 36.215278 | 119 | py |
OFA | OFA-main/run_scripts/image_gen/image_gen_example.py | import sys
sys.path.append('../../')
import torch
import numpy as np
from fairseq import utils, tasks
from fairseq import checkpoint_utils
from utils.eval_utils import eval_step
from tasks.mm_tasks import ImageGenTask
from models.ofa import OFAModel
from PIL import Image
from torchvision import transforms
import time
... | 3,798 | 29.886179 | 101 | py |
OFA | OFA-main/run_scripts/image_gen/eval_utils/inceptionV3.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
class InceptionV3(nn.Module):
"""Pretrained InceptionV3 network returning feature maps"""
# Index of default block of inception to return,
# corresponds to output of final average pooling
DEFAULT_BLOCK_IN... | 4,939 | 33.305556 | 83 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.