code stringlengths 17 6.64M |
|---|
def create_transform():
return FeatureExtractor()
|
def decoar_layers_custom(ckpt: str, refresh=False, *args, **kwargs):
if ckpt.startswith('http'):
ckpt = _urls_to_filepaths(ckpt, refresh=refresh)
return _UpstreamExpert(ckpt, *args, **kwargs)
|
def decoar_layers_local(*args, **kwargs):
return decoar_layers_custom(*args, **kwargs)
|
def decoar_layers_url(*args, **kwargs):
return decoar_layers_custom(*args, **kwargs)
|
def decoar_layers(*args, refresh=False, **kwargs):
'\n The apc standard model on 360hr\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/checkpoint_decoar.pt'
return decoar_layers_url(*args, refre... |
class UpstreamExpert(UpstreamBase):
'\n The Distiller wrapper\n '
def __init__(self, ckpt, model_config=None, **kwargs):
super().__init__(**kwargs)
if (model_config is not None):
print('[UpstreamExpert] - Using upstream expert config file from:', model_config)
wi... |
def distiller_local(ckpt, *args, **kwargs):
'\n The model from local ckpt\n ckpt (str): PATH\n '
assert os.path.isfile(ckpt)
return _UpstreamExpert(ckpt, *args, **kwargs)
|
def distiller_url(ckpt, refresh=False, *args, **kwargs):
'\n The model from url\n ckpt (str): URL\n refresh (bool): whether to download ckpt/config again if existed\n '
return distiller_local(_urls_to_filepaths(ckpt, refresh=refresh), *args, **kwargs)
|
def distilhubert(refresh=False, *args, **kwargs):
'\n DistilHuBERT\n '
return distilhubert_base(*args, refresh=refresh, **kwargs)
|
def distilhubert_base(refresh=False, *args, **kwargs):
'\n DistilHuBERT Base\n Default model in https://arxiv.org/abs/2110.01900\n '
kwargs['ckpt'] = 'https://huggingface.co/leo19941227/distilhubert/resolve/main/distilhubert_ls960_4-8-12.ckpt'
return distiller_url(*args, refresh=refresh, **kwargs... |
def init_bert_params(module):
'\n Initialize the weights specific to the BERT Model.\n This overrides the default initializations depending on the specified arguments.\n 1. If normal_init_linear_weights is set then weights of linear\n layer will be initialized using the normal distribution ... |
class SplitLinear(nn.Module):
'Split Linear Layer'
def __init__(self, in_dim, in_split, out_dim):
super().__init__()
self.in_dim = in_dim
self.in_split = in_split
self.out_dim = out_dim
if (in_split > 1):
weight = torch.zeros((self.in_split, self.in_dim, se... |
class TransformerSentenceEncoderLayer(nn.Module):
'\n Implements a Transformer Encoder Layer used in BERT/XLM style pre-trained\n models.\n '
def __init__(self, embedding_dim: float=768, ffn_embedding_dim: float=3072, num_attention_heads: float=8, dropout: float=0.1, attention_dropout: float=0.1, ac... |
class TransformerEncoder(nn.Module):
def __init__(self, args):
super().__init__()
self.dropout = args.dropout
self.embedding_dim = args.encoder_embed_dim
self.pos_conv = nn.Conv1d(self.embedding_dim, self.embedding_dim, kernel_size=args.conv_pos, padding=(args.conv_pos // 2), grou... |
class UpstreamExpert(torch.nn.Module):
def __init__(self, ckpt, config=None, **kwargs):
super().__init__()
device = ('cuda' if torch.cuda.is_available() else 'cpu')
assert (HubertTask is not None), 'ESPnet is not installed, run `external_tools/install_espnet.sh` to install'
(huber... |
def espnet_hubert_custom(ckpt, *args, config=None, **kwargs):
return _UpstreamExpert(ckpt, *args, **kwargs)
|
def espnet_hubert_local(*args, **kwargs):
return espnet_hubert_custom(*args, **kwargs)
|
def cvhubert(*args, refresh=False, **kwargs):
url = 'https://huggingface.co/espnet/espnet_cvhubert/resolve/main/exp/hubert_iter2_train_ssl_torchaudiohubert_base_960h_pretrain_it2_raw/latest.pth'
config_url = 'https://huggingface.co/espnet/espnet_cvhubert/raw/main/exp/hubert_iter2_train_ssl_torchaudiohubert_ba... |
def wavlablm_ek_40k(*args, refresh=False, **kwargs):
url = 'https://huggingface.co/espnet/WavLabLM-EK-40k/resolve/main/exp_li/hubert_iter2_train_ssl_torchaudiohubert_large_960h_pretrain_it2_cont_raw_layer_9/5epoch.pth'
config_url = 'https://huggingface.co/espnet/WavLabLM-EK-40k/raw/main/exp_li/hubert_iter2_tr... |
def wavlablm_ms_40k(*args, refresh=False, **kwargs):
url = 'https://huggingface.co/espnet/WavLabLM-MS-40k/resolve/main/exp_babel/hubert_iter2_train_ssl_torchaudiohubert_large_960h_pretrain_it2_wavlm_babel_light_raw_layer_9/5epoch.pth'
config_url = 'https://huggingface.co/espnet/WavLabLM-MS-40k/raw/main/exp_ba... |
def wavlablm_mk_40k(*args, refresh=False, **kwargs):
url = 'https://huggingface.co/espnet/WavLabLM-MK-40k/resolve/main/exp_li/hubert_iter2_train_ssl_torchaudiohubert_large_960h_pretrain_it2_wavlm_raw_layer_9/valid.acc_m.ave_10best.pth'
config_url = 'https://huggingface.co/espnet/WavLabLM-MK-40k/raw/main/exp_l... |
def espnet_hubert_base_iter1(*args, refresh=False, **kwargs):
url = 'https://huggingface.co/espnet/simpleoier_librispeech_hubert_iter1_train_ssl_torchaudiohubert_base_960h_pretrain_it1_raw/resolve/main/exp/hubert_iter1_train_ssl_torchaudiohubert_base_960h_pretrain_it1_raw/valid.loss.ave.pth'
config_url = 'htt... |
def espnet_hubert_base_iter0(*args, refresh=False, **kwargs):
url = 'https://huggingface.co/espnet/simpleoier_librispeech_hubert_iter0_train_ssl_torchaudiohubert_base_960h_pretrain_it0_raw/resolve/main/exp/hubert_iter0_train_ssl_torchaudiohubert_base_960h_pretrain_it0_raw/valid.loss.ave.pth'
config_url = 'htt... |
def espnet_hubert_large_gs_ll60k(*args, refresh=False, **kwargs):
url = 'https://huggingface.co/espnet/hubert_large_gs_16_librilight60k/resolve/main/mnt/datastore/exp/hubert_iter1_train_ssl_torchaudiohubert_large_960h_pretrain_it2_bins_raw/valid.loss.ave_10best.pth'
config_url = 'https://huggingface.co/espnet... |
class UpstreamExpert(nn.Module):
def __init__(self, ckpt: str=None, model_config: str=None, **kwargs):
'\n Args:\n ckpt:\n The checkpoint path for loading your pretrained weights.\n Can be assigned by the -k option in run_downstream.py\n\n model_... |
def customized_upstream(*args, **kwargs):
"\n To enable your customized pretrained model, you only need to implement\n upstream/example/expert.py and leave this file as is. This file is\n used to register the UpstreamExpert in upstream/example/expert.py\n The following is a brief introduction of the r... |
class UpstreamExpert(torch.nn.Module):
def __init__(self, ckpt, **kwds):
super().__init__()
try:
self.extracter = Wav2Vec2FeatureExtractor.from_pretrained(ckpt)
except:
if ('base' in ckpt):
alter_extractor = 'facebook/hubert-base-ls960'
... |
def hf_hubert_custom(ckpt, *args, **kwargs):
return _UpstreamExpert(ckpt, *args, **kwargs)
|
class UpstreamExpert(torch.nn.Module):
def __init__(self, ckpt, **kwds):
super().__init__()
self.extracter = Wav2Vec2FeatureExtractor.from_pretrained(ckpt)
self.model = Wav2Vec2Model.from_pretrained(ckpt)
def get_downsample_rates(self, key: str=None) -> int:
return 320
d... |
def hf_wav2vec2_custom(ckpt, *args, **kwargs):
return _UpstreamExpert(ckpt, *args, **kwargs)
|
def load_and_convert_fairseq_ckpt(fairseq_source: str, output_path: str=None):
from fairseq.data.dictionary import Dictionary
(state, cfg) = load_fairseq_ckpt(fairseq_source)
dicts: List[Dictionary] = state['task_state']['dictionaries']
symbols = [dictionary.symbols for dictionary in dicts]
output... |
def load_converted_model(ckpt: str):
ckpt_state = torch.load(ckpt, map_location='cpu')
for required_key in ['task_cfg', 'model_cfg', 'model_weight', 'dictionaries_symbols']:
if (required_key not in ckpt_state):
raise ValueError(f'{ckpt} is not a valid checkpoint since the required key: {re... |
def hubert_custom(ckpt: str, legacy: bool=False, fairseq: bool=False, refresh: bool=False, **kwargs):
assert (not (legacy and fairseq)), "The option 'legacy' will directly load a fairseq checkpoint, while the option 'fairseq' will first convert the fairseq checkpoint to be fairseq indenpendent and then load the c... |
def hubert_local(*args, **kwargs):
return hubert_custom(*args, **kwargs)
|
def hubert_url(*args, **kwargs):
return hubert_custom(*args, **kwargs)
|
def hubert(refresh=False, *args, **kwargs):
'\n The default model - Base\n refresh (bool): whether to download ckpt/config again if existed\n '
return hubert_base(*args, refresh=refresh, **kwargs)
|
def hubert_base(refresh=False, legacy=False, **kwargs):
'\n The Base model\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/hubert/hubert_base_ls960.pt'
if (not legacy):
kwargs['ckpt'] = 'https://huggingface.co/s3p... |
def hubert_large_ll60k(refresh=False, legacy=False, **kwargs):
'\n The Large model\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://dl.fbaipublicfiles.com/hubert/hubert_large_ll60k.pt'
if (not legacy):
kwargs['ckpt'] = 'https://huggingfa... |
def hubert_base_robust_mgr(refresh=False, legacy=False, **kwargs):
'\n The Base model, continually trained with Libri 960 hr with Musan noise, Gaussian noise and Reverberation.\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://huggingface.co/kphuang6... |
def mhubert_base_vp_en_es_fr_it3(refresh=False, **kwds):
kwds['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/mhubert_base_vp_en_es_fr_it3.pt'
return hubert_custom(refresh=refresh, **kwds)
|
def contentvec(refresh=False, **kwds):
kwds['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/contentvec_km100.pt'
return hubert_custom(refresh=refresh, **kwds)
|
def contentvec_km100(refresh=False, **kwds):
kwds['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/contentvec_km100.pt'
return hubert_custom(refresh=refresh, **kwds)
|
def contentvec_km500(refresh=False, **kwds):
kwds['ckpt'] = 'https://huggingface.co/s3prl/converted_ckpts/resolve/main/contentvec_km500.pt'
return hubert_custom(refresh=refresh, **kwds)
|
class Hook():
def __init__(self, module_path, transform, unique_identifier=None):
self.module_path = module_path
self.transform = transform
self.unique_identifier = (unique_identifier or module_path)
self.handler = None
assert isinstance(self.module_path, str)
asse... |
class initHook(type):
def __call__(cls, *args, **kwargs):
instance = super().__call__(*args, **kwargs)
for hook in instance.hooks:
if (hook.handler is None):
instance._register_hook_handler(hook)
return instance
|
class UpstreamBase(nn.Module, metaclass=initHook):
def __init__(self, hooks: List[Tuple]=None, hook_postprocess: Callable[([List[Tuple[(str, Tensor)]]], List[Tuple[(str, Tensor)]])]=None, **kwargs):
'\n Args:\n hooks: each Tuple is an argument list for the Hook initializer\n '
... |
class Featurizer(nn.Module):
def __init__(self, upstream: UpstreamBase, feature_selection: str='hidden_states', upstream_device: str='cuda', layer_selection: int=None, normalize: bool=False, **kwargs):
super().__init__()
self.name = 'Featurizer'
upstream.eval()
paired_wavs = [torc... |
class UpstreamExpert(torch.nn.Module):
def __init__(self, ckpt, **kwds):
super().__init__()
checkpoint = torch.load(ckpt)
assert (checkpoint['cfg']['model']['_name'] in ['hubert_pruner', 'student_hubert'])
self.cfg = LightHuBERTConfig(checkpoint['cfg']['model'])
if (checkp... |
def lighthubert_local(ckpt, *args, **kwargs):
'\n The model from local ckpt\n ckpt (str): PATH\n '
assert os.path.isfile(ckpt)
return _UpstreamExpert(ckpt, *args, **kwargs)
|
def lighthubert_url(ckpt, refresh=False, *args, **kwargs):
'\n The model from google drive id\n ckpt (str): URL\n refresh (bool): whether to download ckpt/config again if existed\n '
return lighthubert_local(_urls_to_filepaths(ckpt, refresh=refresh), *args, **kwargs)
|
def lighthubert(refresh=False, *args, **kargs):
'\n The default model - Small\n refresh (bool): whether to download ckpt/config again if existed\n '
return lighthubert_small(*args, refresh=refresh, **kargs)
|
def lighthubert_small(refresh=False, *args, **kwargs):
'\n The small model\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://huggingface.co/mechanicalsea/lighthubert/resolve/main/lighthubert_small.pt'
return lighthubert_url(*args, refresh=refresh... |
def lighthubert_base(refresh=False, *args, **kwargs):
'\n The Base model\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://huggingface.co/mechanicalsea/lighthubert/resolve/main/lighthubert_base.pt'
return lighthubert_url(*args, refresh=refresh, *... |
def lighthubert_stage1(refresh=False, *args, **kwargs):
'\n The Stage1 model\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://huggingface.co/mechanicalsea/lighthubert/resolve/main/lighthubert_stage1.pt'
return lighthubert_url(*args, refresh=refr... |
def is_xla_tensor(tensor):
return (torch.is_tensor(tensor) and (tensor.device.type == 'xla'))
|
def index_put(tensor, indices, value):
if is_xla_tensor(tensor):
for _ in range(indices.dim(), tensor.dim()):
indices = indices.unsqueeze((- 1))
if (indices.size((- 1)) < tensor.size((- 1))):
indices = indices.expand_as(tensor)
tensor = (torch.mul(tensor, (~ indices... |
def pad_to_multiple(x, multiple, dim=(- 1), value=0):
if (x is None):
return (None, 0)
tsz = x.size(dim)
m = (tsz / multiple)
remainder = ((math.ceil(m) * multiple) - tsz)
if m.is_integer():
return (x, 0)
pad_offset = (((0,) * ((- 1) - dim)) * 2)
return (F.pad(x, (*pad_offs... |
def gelu_accurate(x):
if (not hasattr(gelu_accurate, '_a')):
gelu_accurate._a = math.sqrt((2 / math.pi))
return ((0.5 * x) * (1 + torch.tanh((gelu_accurate._a * (x + (0.044715 * torch.pow(x, 3)))))))
|
def gelu(x: torch.Tensor) -> torch.Tensor:
return torch.nn.functional.gelu(x.float()).type_as(x)
|
def relu_squared(x: torch.Tensor):
return F.relu(x).pow(2)
|
def deprecation_warning(message, stacklevel=3):
warnings.warn(message, stacklevel=stacklevel)
|
def get_activation_fn(activation: str) -> Callable:
'Returns the activation function corresponding to `activation`'
def gelu_accurate(x):
if (not hasattr(gelu_accurate, '_a')):
gelu_accurate._a = math.sqrt((2 / math.pi))
return ((0.5 * x) * (1 + torch.tanh((gelu_accurate._a * (x +... |
class SLayerNorm(nn.LayerNorm):
'LayerNorm: variable 1-D size\n __base__: torch.nn.LayerNorm\n '
def __init__(self, normalized_shape: int, eps: float=1e-05, elementwise_affine: bool=True) -> None:
super(SLayerNorm, self).__init__(normalized_shape, eps, elementwise_affine)
self.staticize... |
class ConvFeatureExtractionModel(nn.Module):
def __init__(self, conv_layers: List[Tuple[(int, int, int)]], dropout: float=0.0, mode: str='default', conv_bias: bool=False):
super().__init__()
assert (mode in {'default', 'layer_norm'})
def block(n_in, n_out, k, stride, is_layer_norm=False,... |
class Spectrogram(nn.Module):
def __init__(self, cfg, **kwargs):
super(Spectrogram, self).__init__()
self.eps = 1e-08
self.cfg = cfg
self.n_fft = cfg['spectrogram']['n_fft']
self.hop_length = cfg['spectrogram']['hop_length']
self.win_length = cfg['spectrogram']['wi... |
class UpstreamExpert(nn.Module):
'\n Extract spectrogram features from wavforms with torchaudio\n '
def __init__(self, model_config=None, **kwargs):
super(UpstreamExpert, self).__init__()
with open(model_config, 'r') as file:
self.config = yaml.load(file, Loader=yaml.FullLoa... |
def stft_mag(model_config, *args, **kwargs):
assert os.path.isfile(model_config)
return _UpstreamExpert(model_config, *args, **kwargs)
|
def mae_ast_local(ckpt, *args, **kwargs):
'\n The model from local ckpt\n ckpt (str): PATH\n '
assert os.path.isfile(ckpt)
return _UpstreamExpert(ckpt, *args, **kwargs)
|
def mae_ast_url(ckpt, refresh=False, *args, **kwargs):
'\n The model from URL\n ckpt (str): URL\n '
return mae_ast_local(_urls_to_filepaths(ckpt, refresh=refresh), *args, **kwargs)
|
def mae_ast_frame(refresh=False, *args, **kwargs):
'\n The MAE-AST Frame model, 12-layered, random masking\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://www.cs.utexas.edu/~harwath/model_checkpoints/mae_ast/random_frame_75_12LayerEncoder.pt'
r... |
def mae_ast_patch(refresh=False, *args, **kwargs):
'\n The MAE-AST Patch model, 12-layered, chunked masking\n refresh (bool): whether to download ckpt/config again if existed\n '
kwargs['ckpt'] = 'https://www.cs.utexas.edu/~harwath/model_checkpoints/mae_ast/chunk_patch_75_12LayerEncoder.pt'
r... |
@dataclass
class MAE_AST_Pretraining_Config():
data: str = field(default=MISSING, metadata={'help': 'path to data directory'})
sample_rate: int = field(default=16000, metadata={'help': 'target sample rate. audio files will be up/down sampled to this rate'})
normalize: bool = field(default=False, metadata=... |
class MAE_AST_Pretraining_Task():
cfg: MAE_AST_Pretraining_Config
def __init__(self, cfg: MAE_AST_Pretraining_Config) -> None:
super().__init__(cfg)
logger.info(f'current directory is {os.getcwd()}')
logger.info(f'MAEPretrainingTask Config {cfg}')
self.cfg = cfg
@property... |
class UpstreamExpert(UpstreamBase):
'\n The Mockingjay wrapper\n '
def __init__(self, ckpt, options_config=None, **kwargs):
super().__init__(**kwargs)
if (options_config is not None):
print('[UpstreamExpert] - Using upstream expert config file from:', options_config)
... |
def mockingjay_local(ckpt, options_config=None, *args, **kwargs):
'\n The model from local ckpt\n ckpt (str): PATH\n feature_selection (int): -1 (default, the last layer) or an int in range(0, max_layer_num)\n '
assert os.path.isfile(ckpt)
if (options_config is not None):
asser... |
def mockingjay_url(ckpt, refresh=False, *args, **kwargs):
'\n The model from URL\n ckpt (str): URL\n '
return mockingjay_local(_urls_to_filepaths(ckpt, refresh=refresh), *args, **kwargs)
|
def mockingjay(refresh=False, *args, **kwargs):
'\n The default model\n refresh (bool): whether to download ckpt/config again if existed\n '
return mockingjay_origin(*args, refresh=refresh, **kwargs)
|
def mockingjay_origin(refresh=False, *args, **kwargs):
'\n The mockingjay large model on 360hr, with Lel as input and Linear as target\n refresh (bool): whether to download ckpt/config again if existed\n '
return mockingjay_logMelLinearLarge_T_AdamW_b32_500k_360hr_drop1(*args, refresh=refresh, **... |
def mockingjay_100hr(refresh=False, *args, **kwargs):
'\n The mockingjay base model on 100hr\n refresh (bool): whether to download ckpt/config again if existed\n '
return mockingjay_logMelBase_T_AdamW_b32_200k_100hr(*args, refresh=refresh, **kwargs)
|
def mockingjay_960hr(refresh=False, *args, **kwargs):
'\n The mockingjay base model on 960hr\n refresh (bool): whether to download ckpt/config again if existed\n '
return mockingjay_logMelBase_T_AdamW_b32_1m_960hr_drop1(*args, refresh=refresh, **kwargs)
|
def mockingjay_logMelBase_T_AdamW_b32_200k_100hr(refresh=False, *args, **kwargs):
'\n Feature: 80-dim log Mel\n Alteration: time\n Optimizer: AdamW\n Batch size: 32\n Total steps: 200k\n Unlabled Speech: 100hr\n '
kwargs['ckpt'] = 'https://www.dropbox.com/s/luorglf8mdg67l2/states-200000.c... |
def mockingjay_logMelLinearLarge_T_AdamW_b32_500k_360hr_drop1(refresh=False, *args, **kwargs):
'\n Feature: 80-dim log Mel (input) / 201-dim Linear (target)\n Alteration: time\n Optimizer: AdamW\n Batch size: 32\n Total steps: 500k\n Unlabled Speech: 360hr\n '
kwargs['ckpt'] = 'https://hu... |
def mockingjay_logMelBase_T_AdamW_b32_1m_960hr(refresh=False, *args, **kwargs):
'\n Feature: 80-dim log Mel\n Alteration: time\n Optimizer: AdamW\n Batch size: 32\n Total steps: 1M\n Unlabled Speech: 960hr\n '
kwargs['ckpt'] = 'https://www.dropbox.com/s/jzx0xggk663jev6/states-1000000.ckpt... |
def mockingjay_logMelBase_T_AdamW_b32_1m_960hr_drop1(refresh=False, *args, **kwargs):
'\n Feature: 80-dim log Mel\n Alteration: time\n Optimizer: AdamW\n Batch size: 32\n Total steps: 1M\n Unlabled Speech: 960hr\n Differences: Dropout of 0.1 (instead of 0.3)\n '
kwargs['ckpt'] = 'https... |
def mockingjay_logMelBase_T_AdamW_b32_1m_960hr_seq3k(refresh=False, *args, **kwargs):
'\n Feature: 80-dim log Mel\n Alteration: time\n Optimizer: AdamW\n Batch size: 32\n Total steps: 1M\n Unlabled Speech: 960hr\n Differences: sequence length of 3k (instead of 1.5k)\n '
kwargs['ckpt'] ... |
class TransformerConfig(object):
'Configuration class to store the configuration of a `TransformerModel`.'
def __init__(self, config):
self.hidden_size = int(config['hidden_size'])
self.num_hidden_layers = int(config['num_hidden_layers'])
self.num_attention_heads = int(config['num_att... |
def prune_linear_layer(layer, index, dim=0):
'Prune a linear layer (a model parameters) to keep only entries in index.\n Return the pruned layer as a new layer with requires_grad=True.\n Used to remove heads.\n '
index = index.to(layer.weight.device)
W = layer.weight.index_select(dim, index).clon... |
def gelu(x):
"Implementation of the gelu activation function.\n For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):\n 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))\n Also see https://arxiv.org/abs/1606.08415\n "
r... |
def swish(x):
return (x * torch.sigmoid(x))
|
class TransformerLayerNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-12):
'Construct a layernorm module in the TF style (epsilon inside the square root).'
super(TransformerLayerNorm, self).__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.bias = nn.Param... |
class TransformerInputRepresentations(nn.Module):
'Construct the input representation from spectrogram, and position encodings.'
def __init__(self, config, input_dim):
super(TransformerInputRepresentations, self).__init__()
self.hidden_size = config.hidden_size
self.spec_transform = n... |
class TransformerSelfAttention(nn.Module):
def __init__(self, config, output_attentions=False, keep_multihead_output=False):
super(TransformerSelfAttention, self).__init__()
if ((config.hidden_size % config.num_attention_heads) != 0):
raise ValueError(('The hidden size (%d) is not a m... |
class TransformerSelfOutput(nn.Module):
def __init__(self, config):
super(TransformerSelfOutput, self).__init__()
self.pre_layer_norm = config.pre_layer_norm
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
... |
class TransformerAttention(nn.Module):
def __init__(self, config, output_attentions=False, keep_multihead_output=False):
super(TransformerAttention, self).__init__()
self.output_attentions = output_attentions
self.pre_layer_norm = config.pre_layer_norm
self.self = TransformerSelfA... |
class TransformerIntermediate(nn.Module):
def __init__(self, config):
super(TransformerIntermediate, self).__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act... |
class TransformerOutput(nn.Module):
def __init__(self, config):
super(TransformerOutput, self).__init__()
self.pre_layer_norm = config.pre_layer_norm
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
... |
class TransformerLayer(nn.Module):
def __init__(self, config, output_attentions=False, keep_multihead_output=False):
super(TransformerLayer, self).__init__()
self.output_attentions = output_attentions
self.pre_layer_norm = config.pre_layer_norm
self.attention = TransformerAttentio... |
class TransformerEncoder(nn.Module):
def __init__(self, config, output_attentions=False, keep_multihead_output=False):
super(TransformerEncoder, self).__init__()
self.output_attentions = output_attentions
self.pre_layer_norm = config.pre_layer_norm
layer = TransformerLayer(config,... |
class TransformerSpecPredictionHead(nn.Module):
def __init__(self, config, output_dim, input_dim=None):
super(TransformerSpecPredictionHead, self).__init__()
self.output_dim = output_dim
if (input_dim is None):
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
... |
class TransformerInitModel(nn.Module):
'An abstract class to handle weights initialization.'
def __init__(self, config, output_attentions, *inputs, **kwargs):
super(TransformerInitModel, self).__init__()
self.config = config
self.output_attentions = output_attentions
def init_Tra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.