Instructions to use deepsafe/deepsafe-services with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use deepsafe/deepsafe-services with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("deepsafe/deepsafe-services", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
chore: remove non-weight files (batch 3)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/bart/model.py +0 -393
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/composite_encoder.py +0 -57
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/distributed_fairseq_model.py +0 -146
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/ema/__init__.py +0 -20
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/ema/ema.py +0 -208
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/fairseq_decoder.py +0 -104
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/fairseq_encoder.py +0 -91
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/fairseq_incremental_decoder.py +0 -117
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/fairseq_model.py +0 -573
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/fconv.py +0 -756
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/fconv_lm.py +0 -136
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/fconv_self_att.py +0 -673
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/hubert/__init__.py +0 -7
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/hubert/hubert.py +0 -571
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/hubert/hubert_asr.py +0 -363
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/huggingface/__init__.py +0 -19
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/huggingface/hf_gpt2.py +0 -167
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/lightconv.py +0 -1019
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/lightconv_lm.py +0 -306
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/lstm.py +0 -754
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/lstm_lm.py +0 -141
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/masked_lm.py +0 -403
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/model_utils.py +0 -92
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/multilingual_transformer.py +0 -229
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/__init__.py +0 -13
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/cmlm_transformer.py +0 -162
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/fairseq_nat_model.py +0 -172
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/insertion_transformer.py +0 -280
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/iterative_nonautoregressive_transformer.py +0 -228
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/levenshtein_transformer.py +0 -510
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/levenshtein_utils.py +0 -292
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/nat_crf_transformer.py +0 -121
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/nonautoregressive_ensembles.py +0 -254
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/nonautoregressive_transformer.py +0 -456
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/__init__.py +0 -11
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/alignment_utils.py +0 -118
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/enc_dec.py +0 -192
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/hub_interface.py +0 -235
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/model.py +0 -699
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/model_camembert.py +0 -50
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/model_gottbert.py +0 -49
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/model_xlmr.py +0 -46
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_speech/__init__.py +0 -8
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_speech/modules.py +0 -58
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_speech/s2s_conformer.py +0 -112
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_speech/s2s_transformer.py +0 -701
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_text/__init__.py +0 -12
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_text/berard.py +0 -606
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_text/convtransformer.py +0 -448
- audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_text/hub_interface.py +0 -125
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/bart/model.py
DELETED
|
@@ -1,393 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
"""
|
| 6 |
-
BART: Denoising Sequence-to-Sequence Pre-training for
|
| 7 |
-
Natural Language Generation, Translation, and Comprehension
|
| 8 |
-
"""
|
| 9 |
-
import logging
|
| 10 |
-
from typing import Optional
|
| 11 |
-
|
| 12 |
-
import torch
|
| 13 |
-
import torch.nn as nn
|
| 14 |
-
from fairseq import utils
|
| 15 |
-
from fairseq.models import register_model, register_model_architecture
|
| 16 |
-
from fairseq.models.transformer import TransformerModel
|
| 17 |
-
from fairseq.modules.transformer_sentence_encoder import init_bert_params
|
| 18 |
-
|
| 19 |
-
from .hub_interface import BARTHubInterface
|
| 20 |
-
|
| 21 |
-
logger = logging.getLogger(__name__)
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
@register_model("bart")
|
| 25 |
-
class BARTModel(TransformerModel):
|
| 26 |
-
__jit_unused_properties__ = ["supported_targets"]
|
| 27 |
-
|
| 28 |
-
@classmethod
|
| 29 |
-
def hub_models(cls):
|
| 30 |
-
return {
|
| 31 |
-
"bart.base": "http://dl.fbaipublicfiles.com/fairseq/models/bart.base.tar.gz",
|
| 32 |
-
"bart.large": "http://dl.fbaipublicfiles.com/fairseq/models/bart.large.tar.gz",
|
| 33 |
-
"bart.large.mnli": "http://dl.fbaipublicfiles.com/fairseq/models/bart.large.mnli.tar.gz",
|
| 34 |
-
"bart.large.cnn": "http://dl.fbaipublicfiles.com/fairseq/models/bart.large.cnn.tar.gz",
|
| 35 |
-
"bart.large.xsum": "http://dl.fbaipublicfiles.com/fairseq/models/bart.large.xsum.tar.gz",
|
| 36 |
-
}
|
| 37 |
-
|
| 38 |
-
def __init__(self, args, encoder, decoder):
|
| 39 |
-
super().__init__(args, encoder, decoder)
|
| 40 |
-
|
| 41 |
-
# We follow BERT's random weight initialization
|
| 42 |
-
self.apply(init_bert_params)
|
| 43 |
-
|
| 44 |
-
self.classification_heads = nn.ModuleDict()
|
| 45 |
-
if hasattr(self.encoder, "dictionary"):
|
| 46 |
-
self.eos: int = self.encoder.dictionary.eos()
|
| 47 |
-
|
| 48 |
-
@staticmethod
|
| 49 |
-
def add_args(parser):
|
| 50 |
-
super(BARTModel, BARTModel).add_args(parser)
|
| 51 |
-
parser.add_argument(
|
| 52 |
-
"--pooler-dropout",
|
| 53 |
-
type=float,
|
| 54 |
-
metavar="D",
|
| 55 |
-
help="dropout probability in the masked_lm pooler layers",
|
| 56 |
-
)
|
| 57 |
-
parser.add_argument(
|
| 58 |
-
"--pooler-activation-fn",
|
| 59 |
-
choices=utils.get_available_activation_fns(),
|
| 60 |
-
help="activation function to use for pooler layer",
|
| 61 |
-
)
|
| 62 |
-
parser.add_argument(
|
| 63 |
-
"--spectral-norm-classification-head",
|
| 64 |
-
action="store_true",
|
| 65 |
-
help="Apply spectral normalization on the classification head",
|
| 66 |
-
)
|
| 67 |
-
|
| 68 |
-
@property
|
| 69 |
-
def supported_targets(self):
|
| 70 |
-
return {"self"}
|
| 71 |
-
|
| 72 |
-
def forward(
|
| 73 |
-
self,
|
| 74 |
-
src_tokens,
|
| 75 |
-
src_lengths,
|
| 76 |
-
prev_output_tokens,
|
| 77 |
-
features_only: bool = False,
|
| 78 |
-
classification_head_name: Optional[str] = None,
|
| 79 |
-
token_embeddings: Optional[torch.Tensor] = None,
|
| 80 |
-
return_all_hiddens: bool = True,
|
| 81 |
-
alignment_layer: Optional[int] = None,
|
| 82 |
-
alignment_heads: Optional[int] = None,
|
| 83 |
-
):
|
| 84 |
-
if classification_head_name is not None:
|
| 85 |
-
features_only = True
|
| 86 |
-
|
| 87 |
-
encoder_out = self.encoder(
|
| 88 |
-
src_tokens,
|
| 89 |
-
src_lengths=src_lengths,
|
| 90 |
-
token_embeddings=token_embeddings,
|
| 91 |
-
return_all_hiddens=return_all_hiddens,
|
| 92 |
-
)
|
| 93 |
-
x, extra = self.decoder(
|
| 94 |
-
prev_output_tokens,
|
| 95 |
-
encoder_out=encoder_out,
|
| 96 |
-
features_only=features_only,
|
| 97 |
-
alignment_layer=alignment_layer,
|
| 98 |
-
alignment_heads=alignment_heads,
|
| 99 |
-
src_lengths=src_lengths,
|
| 100 |
-
return_all_hiddens=return_all_hiddens,
|
| 101 |
-
)
|
| 102 |
-
eos: int = self.eos
|
| 103 |
-
if classification_head_name is not None:
|
| 104 |
-
sentence_representation = x[src_tokens.eq(eos), :].view(
|
| 105 |
-
x.size(0), -1, x.size(-1)
|
| 106 |
-
)[:, -1, :]
|
| 107 |
-
for k, head in self.classification_heads.items():
|
| 108 |
-
# for torch script only supports iteration
|
| 109 |
-
if k == classification_head_name:
|
| 110 |
-
x = head(sentence_representation)
|
| 111 |
-
break
|
| 112 |
-
return x, extra
|
| 113 |
-
|
| 114 |
-
@classmethod
|
| 115 |
-
def from_pretrained(
|
| 116 |
-
cls,
|
| 117 |
-
model_name_or_path,
|
| 118 |
-
checkpoint_file="model.pt",
|
| 119 |
-
data_name_or_path=".",
|
| 120 |
-
bpe="gpt2",
|
| 121 |
-
sample_break_mode="eos",
|
| 122 |
-
**kwargs,
|
| 123 |
-
):
|
| 124 |
-
from fairseq import hub_utils
|
| 125 |
-
|
| 126 |
-
x = hub_utils.from_pretrained(
|
| 127 |
-
model_name_or_path,
|
| 128 |
-
checkpoint_file,
|
| 129 |
-
data_name_or_path,
|
| 130 |
-
archive_map=cls.hub_models(),
|
| 131 |
-
bpe=bpe,
|
| 132 |
-
load_checkpoint_heads=True,
|
| 133 |
-
sample_break_mode=sample_break_mode,
|
| 134 |
-
**kwargs,
|
| 135 |
-
)
|
| 136 |
-
return BARTHubInterface(x["args"], x["task"], x["models"][0])
|
| 137 |
-
|
| 138 |
-
def register_classification_head(
|
| 139 |
-
self, name, num_classes=None, inner_dim=None, **kwargs
|
| 140 |
-
):
|
| 141 |
-
"""Register a classification head."""
|
| 142 |
-
logger.info("Registering classification head: {0}".format(name))
|
| 143 |
-
if name in self.classification_heads:
|
| 144 |
-
prev_num_classes = self.classification_heads[name].out_proj.out_features
|
| 145 |
-
prev_inner_dim = self.classification_heads[name].dense.out_features
|
| 146 |
-
if num_classes != prev_num_classes or inner_dim != prev_inner_dim:
|
| 147 |
-
logger.warning(
|
| 148 |
-
're-registering head "{}" with num_classes {} (prev: {}) '
|
| 149 |
-
"and inner_dim {} (prev: {})".format(
|
| 150 |
-
name, num_classes, prev_num_classes, inner_dim, prev_inner_dim
|
| 151 |
-
)
|
| 152 |
-
)
|
| 153 |
-
self.classification_heads[name] = BARTClassificationHead(
|
| 154 |
-
input_dim=self.args.encoder_embed_dim,
|
| 155 |
-
inner_dim=inner_dim or self.args.encoder_embed_dim,
|
| 156 |
-
num_classes=num_classes,
|
| 157 |
-
activation_fn=self.args.pooler_activation_fn,
|
| 158 |
-
pooler_dropout=self.args.pooler_dropout,
|
| 159 |
-
do_spectral_norm=getattr(
|
| 160 |
-
self.args, "spectral_norm_classification_head", False
|
| 161 |
-
),
|
| 162 |
-
)
|
| 163 |
-
|
| 164 |
-
def upgrade_state_dict_named(self, state_dict, name):
|
| 165 |
-
super().upgrade_state_dict_named(state_dict, name)
|
| 166 |
-
|
| 167 |
-
prefix = name + "." if name != "" else ""
|
| 168 |
-
current_head_names = (
|
| 169 |
-
[]
|
| 170 |
-
if not hasattr(self, "classification_heads")
|
| 171 |
-
else self.classification_heads.keys()
|
| 172 |
-
)
|
| 173 |
-
|
| 174 |
-
# Handle new classification heads present in the state dict.
|
| 175 |
-
keys_to_delete = []
|
| 176 |
-
for k in state_dict.keys():
|
| 177 |
-
if not k.startswith(prefix + "classification_heads."):
|
| 178 |
-
continue
|
| 179 |
-
|
| 180 |
-
head_name = k[len(prefix + "classification_heads.") :].split(".")[0]
|
| 181 |
-
num_classes = state_dict[
|
| 182 |
-
prefix + "classification_heads." + head_name + ".out_proj.weight"
|
| 183 |
-
].size(0)
|
| 184 |
-
inner_dim = state_dict[
|
| 185 |
-
prefix + "classification_heads." + head_name + ".dense.weight"
|
| 186 |
-
].size(0)
|
| 187 |
-
|
| 188 |
-
if getattr(self.args, "load_checkpoint_heads", False):
|
| 189 |
-
if head_name not in current_head_names:
|
| 190 |
-
self.register_classification_head(head_name, num_classes, inner_dim)
|
| 191 |
-
else:
|
| 192 |
-
if head_name not in current_head_names:
|
| 193 |
-
logger.warning(
|
| 194 |
-
"deleting classification head ({}) from checkpoint "
|
| 195 |
-
"not present in current model: {}".format(head_name, k)
|
| 196 |
-
)
|
| 197 |
-
keys_to_delete.append(k)
|
| 198 |
-
elif (
|
| 199 |
-
num_classes
|
| 200 |
-
!= self.classification_heads[head_name].out_proj.out_features
|
| 201 |
-
or inner_dim
|
| 202 |
-
!= self.classification_heads[head_name].dense.out_features
|
| 203 |
-
):
|
| 204 |
-
logger.warning(
|
| 205 |
-
"deleting classification head ({}) from checkpoint "
|
| 206 |
-
"with different dimensions than current model: {}".format(
|
| 207 |
-
head_name, k
|
| 208 |
-
)
|
| 209 |
-
)
|
| 210 |
-
keys_to_delete.append(k)
|
| 211 |
-
for k in keys_to_delete:
|
| 212 |
-
del state_dict[k]
|
| 213 |
-
|
| 214 |
-
def truncate_emb(key):
|
| 215 |
-
if key in state_dict:
|
| 216 |
-
state_dict[key] = state_dict[key][:-1, :]
|
| 217 |
-
|
| 218 |
-
# When finetuning on translation task, remove last row of
|
| 219 |
-
# embedding matrix that corresponds to mask_idx token.
|
| 220 |
-
loaded_dict_size = state_dict["encoder.embed_tokens.weight"].size(0)
|
| 221 |
-
if (
|
| 222 |
-
loaded_dict_size == len(self.encoder.dictionary) + 1
|
| 223 |
-
and "<mask>" not in self.encoder.dictionary
|
| 224 |
-
):
|
| 225 |
-
truncate_emb("encoder.embed_tokens.weight")
|
| 226 |
-
truncate_emb("decoder.embed_tokens.weight")
|
| 227 |
-
truncate_emb("encoder.output_projection.weight")
|
| 228 |
-
truncate_emb("decoder.output_projection.weight")
|
| 229 |
-
|
| 230 |
-
# When continued pretraining on new set of languages for mbart,
|
| 231 |
-
# add extra lang embeddings at the end of embed_tokens.
|
| 232 |
-
# Note: newly added languages are assumed to have been added at the end.
|
| 233 |
-
if self.args.task == "multilingual_denoising" and loaded_dict_size < len(
|
| 234 |
-
self.encoder.dictionary
|
| 235 |
-
):
|
| 236 |
-
logger.info(
|
| 237 |
-
"Adding extra language embeddings not found in pretrained model for "
|
| 238 |
-
"continued pretraining of MBART on new set of languages."
|
| 239 |
-
)
|
| 240 |
-
loaded_mask_token_embedding = state_dict["encoder.embed_tokens.weight"][
|
| 241 |
-
-1, :
|
| 242 |
-
]
|
| 243 |
-
|
| 244 |
-
num_langids_to_add = len(self.encoder.dictionary) - loaded_dict_size
|
| 245 |
-
embed_dim = state_dict["encoder.embed_tokens.weight"].size(1)
|
| 246 |
-
|
| 247 |
-
new_lang_embed_to_add = torch.zeros(num_langids_to_add, embed_dim)
|
| 248 |
-
nn.init.normal_(new_lang_embed_to_add, mean=0, std=embed_dim**-0.5)
|
| 249 |
-
new_lang_embed_to_add = new_lang_embed_to_add.to(
|
| 250 |
-
dtype=state_dict["encoder.embed_tokens.weight"].dtype,
|
| 251 |
-
)
|
| 252 |
-
|
| 253 |
-
state_dict["encoder.embed_tokens.weight"] = torch.cat(
|
| 254 |
-
[
|
| 255 |
-
state_dict["encoder.embed_tokens.weight"][
|
| 256 |
-
: loaded_dict_size - 1, :
|
| 257 |
-
],
|
| 258 |
-
new_lang_embed_to_add,
|
| 259 |
-
loaded_mask_token_embedding.unsqueeze(0),
|
| 260 |
-
]
|
| 261 |
-
)
|
| 262 |
-
state_dict["decoder.embed_tokens.weight"] = torch.cat(
|
| 263 |
-
[
|
| 264 |
-
state_dict["decoder.embed_tokens.weight"][
|
| 265 |
-
: loaded_dict_size - 1, :
|
| 266 |
-
],
|
| 267 |
-
new_lang_embed_to_add,
|
| 268 |
-
loaded_mask_token_embedding.unsqueeze(0),
|
| 269 |
-
]
|
| 270 |
-
)
|
| 271 |
-
|
| 272 |
-
# Copy any newly-added classification heads into the state dict
|
| 273 |
-
# with their current weights.
|
| 274 |
-
if hasattr(self, "classification_heads"):
|
| 275 |
-
cur_state = self.classification_heads.state_dict()
|
| 276 |
-
for k, v in cur_state.items():
|
| 277 |
-
if prefix + "classification_heads." + k not in state_dict:
|
| 278 |
-
logger.info("Overwriting " + prefix + "classification_heads." + k)
|
| 279 |
-
state_dict[prefix + "classification_heads." + k] = v
|
| 280 |
-
|
| 281 |
-
def set_beam_size(self, beam):
|
| 282 |
-
"""Set beam size for efficient beamable enc-dec attention."""
|
| 283 |
-
beamable = False
|
| 284 |
-
for layer in self.decoder.layers:
|
| 285 |
-
if layer.encoder_attn is not None:
|
| 286 |
-
if hasattr(layer.encoder_attn, "set_beam_size"):
|
| 287 |
-
layer.encoder_attn.set_beam_size(beam)
|
| 288 |
-
beamable = True
|
| 289 |
-
if beamable:
|
| 290 |
-
self.encoder.reorder_encoder_out = self.encoder._reorder_encoder_out
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
class BARTClassificationHead(nn.Module):
|
| 294 |
-
"""Head for sentence-level classification tasks."""
|
| 295 |
-
|
| 296 |
-
def __init__(
|
| 297 |
-
self,
|
| 298 |
-
input_dim,
|
| 299 |
-
inner_dim,
|
| 300 |
-
num_classes,
|
| 301 |
-
activation_fn,
|
| 302 |
-
pooler_dropout,
|
| 303 |
-
do_spectral_norm=False,
|
| 304 |
-
):
|
| 305 |
-
super().__init__()
|
| 306 |
-
self.dense = nn.Linear(input_dim, inner_dim)
|
| 307 |
-
self.activation_fn = utils.get_activation_fn(activation_fn)
|
| 308 |
-
self.dropout = nn.Dropout(p=pooler_dropout)
|
| 309 |
-
self.out_proj = nn.Linear(inner_dim, num_classes)
|
| 310 |
-
|
| 311 |
-
if do_spectral_norm:
|
| 312 |
-
self.out_proj = torch.nn.utils.spectral_norm(self.out_proj)
|
| 313 |
-
|
| 314 |
-
def forward(self, features, **kwargs):
|
| 315 |
-
x = features
|
| 316 |
-
x = self.dropout(x)
|
| 317 |
-
x = self.dense(x)
|
| 318 |
-
x = self.activation_fn(x)
|
| 319 |
-
x = self.dropout(x)
|
| 320 |
-
x = self.out_proj(x)
|
| 321 |
-
return x
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
@register_model_architecture("bart", "bart_large")
|
| 325 |
-
def bart_large_architecture(args):
|
| 326 |
-
args.encoder_embed_path = getattr(args, "encoder_embed_path", None)
|
| 327 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 1024)
|
| 328 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4 * 1024)
|
| 329 |
-
args.encoder_layers = getattr(args, "encoder_layers", 12)
|
| 330 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 16)
|
| 331 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
|
| 332 |
-
args.encoder_learned_pos = getattr(args, "encoder_learned_pos", True)
|
| 333 |
-
args.decoder_embed_path = getattr(args, "decoder_embed_path", None)
|
| 334 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", args.encoder_embed_dim)
|
| 335 |
-
args.decoder_ffn_embed_dim = getattr(
|
| 336 |
-
args, "decoder_ffn_embed_dim", args.encoder_ffn_embed_dim
|
| 337 |
-
)
|
| 338 |
-
args.decoder_layers = getattr(args, "decoder_layers", 12)
|
| 339 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 16)
|
| 340 |
-
args.decoder_normalize_before = getattr(args, "decoder_normalize_before", False)
|
| 341 |
-
args.decoder_learned_pos = getattr(args, "decoder_learned_pos", True)
|
| 342 |
-
args.attention_dropout = getattr(args, "attention_dropout", 0.0)
|
| 343 |
-
args.relu_dropout = getattr(args, "relu_dropout", 0.0)
|
| 344 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 345 |
-
args.max_target_positions = getattr(args, "max_target_positions", 1024)
|
| 346 |
-
args.max_source_positions = getattr(args, "max_source_positions", 1024)
|
| 347 |
-
args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
|
| 348 |
-
args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
|
| 349 |
-
args.share_decoder_input_output_embed = getattr(
|
| 350 |
-
args, "share_decoder_input_output_embed", True
|
| 351 |
-
)
|
| 352 |
-
args.share_all_embeddings = getattr(args, "share_all_embeddings", True)
|
| 353 |
-
|
| 354 |
-
args.decoder_output_dim = getattr(
|
| 355 |
-
args, "decoder_output_dim", args.decoder_embed_dim
|
| 356 |
-
)
|
| 357 |
-
args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim)
|
| 358 |
-
|
| 359 |
-
args.no_scale_embedding = getattr(args, "no_scale_embedding", True)
|
| 360 |
-
args.layernorm_embedding = getattr(args, "layernorm_embedding", True)
|
| 361 |
-
|
| 362 |
-
args.activation_fn = getattr(args, "activation_fn", "gelu")
|
| 363 |
-
args.pooler_activation_fn = getattr(args, "pooler_activation_fn", "tanh")
|
| 364 |
-
args.pooler_dropout = getattr(args, "pooler_dropout", 0.0)
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
@register_model_architecture("bart", "bart_base")
|
| 368 |
-
def bart_base_architecture(args):
|
| 369 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 768)
|
| 370 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4 * 768)
|
| 371 |
-
args.encoder_layers = getattr(args, "encoder_layers", 6)
|
| 372 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 12)
|
| 373 |
-
args.decoder_layers = getattr(args, "decoder_layers", 6)
|
| 374 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 12)
|
| 375 |
-
bart_large_architecture(args)
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
@register_model_architecture("bart", "mbart_large")
|
| 379 |
-
def mbart_large_architecture(args):
|
| 380 |
-
args.no_scale_embedding = getattr(args, "no_scale_embedding", False)
|
| 381 |
-
bart_large_architecture(args)
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
@register_model_architecture("bart", "mbart_base")
|
| 385 |
-
def mbart_base_architecture(args):
|
| 386 |
-
args.no_scale_embedding = getattr(args, "no_scale_embedding", False)
|
| 387 |
-
bart_base_architecture(args)
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
@register_model_architecture("bart", "mbart_base_wmt20")
|
| 391 |
-
def mbart_base_wmt20_architecture(args):
|
| 392 |
-
args.layernorm_embedding = getattr(args, "layernorm_embedding", False)
|
| 393 |
-
mbart_base_architecture(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/composite_encoder.py
DELETED
|
@@ -1,57 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
from .fairseq_encoder import FairseqEncoder
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
class CompositeEncoder(FairseqEncoder):
|
| 10 |
-
"""
|
| 11 |
-
A wrapper around a dictionary of :class:`FairseqEncoder` objects.
|
| 12 |
-
|
| 13 |
-
We run forward on each encoder and return a dictionary of outputs. The first
|
| 14 |
-
encoder's dictionary is used for initialization.
|
| 15 |
-
|
| 16 |
-
Args:
|
| 17 |
-
encoders (dict): a dictionary of :class:`FairseqEncoder` objects.
|
| 18 |
-
"""
|
| 19 |
-
|
| 20 |
-
def __init__(self, encoders):
|
| 21 |
-
super().__init__(next(iter(encoders.values())).dictionary)
|
| 22 |
-
self.encoders = encoders
|
| 23 |
-
for key in self.encoders:
|
| 24 |
-
self.add_module(key, self.encoders[key])
|
| 25 |
-
|
| 26 |
-
def forward(self, src_tokens, src_lengths):
|
| 27 |
-
"""
|
| 28 |
-
Args:
|
| 29 |
-
src_tokens (LongTensor): tokens in the source language of shape
|
| 30 |
-
`(batch, src_len)`
|
| 31 |
-
src_lengths (LongTensor): lengths of each source sentence of shape
|
| 32 |
-
`(batch)`
|
| 33 |
-
|
| 34 |
-
Returns:
|
| 35 |
-
dict:
|
| 36 |
-
the outputs from each Encoder
|
| 37 |
-
"""
|
| 38 |
-
encoder_out = {}
|
| 39 |
-
for key in self.encoders:
|
| 40 |
-
encoder_out[key] = self.encoders[key](src_tokens, src_lengths)
|
| 41 |
-
return encoder_out
|
| 42 |
-
|
| 43 |
-
def reorder_encoder_out(self, encoder_out, new_order):
|
| 44 |
-
"""Reorder encoder output according to new_order."""
|
| 45 |
-
for key in self.encoders:
|
| 46 |
-
encoder_out[key] = self.encoders[key].reorder_encoder_out(
|
| 47 |
-
encoder_out[key], new_order
|
| 48 |
-
)
|
| 49 |
-
return encoder_out
|
| 50 |
-
|
| 51 |
-
def max_positions(self):
|
| 52 |
-
return min(self.encoders[key].max_positions() for key in self.encoders)
|
| 53 |
-
|
| 54 |
-
def upgrade_state_dict(self, state_dict):
|
| 55 |
-
for key in self.encoders:
|
| 56 |
-
self.encoders[key].upgrade_state_dict(state_dict)
|
| 57 |
-
return state_dict
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/distributed_fairseq_model.py
DELETED
|
@@ -1,146 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import logging
|
| 7 |
-
import os
|
| 8 |
-
import signal
|
| 9 |
-
import threading
|
| 10 |
-
|
| 11 |
-
import torch
|
| 12 |
-
import torch.nn as nn
|
| 13 |
-
from fairseq.distributed import (
|
| 14 |
-
DistributedTimeoutWrapper,
|
| 15 |
-
LegacyDistributedDataParallel,
|
| 16 |
-
ModuleProxyWrapper,
|
| 17 |
-
TPUDistributedDataParallel,
|
| 18 |
-
)
|
| 19 |
-
from torch.nn.parallel import DistributedDataParallel
|
| 20 |
-
|
| 21 |
-
logger = logging.getLogger(__name__)
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
_SLOWMO_DDP_DISABLED = False
|
| 25 |
-
try:
|
| 26 |
-
from fairscale.experimental.nn.data_parallel import (
|
| 27 |
-
SlowMoBaseAlgorithm,
|
| 28 |
-
SlowMoDistributedDataParallel,
|
| 29 |
-
)
|
| 30 |
-
except ImportError:
|
| 31 |
-
_SLOWMO_DDP_DISABLED = True
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def DistributedFairseqModel(args, model, process_group, device):
|
| 35 |
-
"""
|
| 36 |
-
Wrap a *model* to support distributed data parallel training.
|
| 37 |
-
|
| 38 |
-
This is similar to the built-in DistributedDataParallel, but allows
|
| 39 |
-
additional configuration of the DistributedDataParallel class to
|
| 40 |
-
use, and also provides easier access to the wrapped model by
|
| 41 |
-
forwarding requests for missing attributes to the wrapped model.
|
| 42 |
-
|
| 43 |
-
Args:
|
| 44 |
-
args (argparse.Namespace): fairseq args
|
| 45 |
-
model (BaseFairseqModel): model to wrap
|
| 46 |
-
process_group: the c10d process group to be used for distributed data
|
| 47 |
-
parallel all-reduction.
|
| 48 |
-
device: device to move model to
|
| 49 |
-
"""
|
| 50 |
-
assert isinstance(model, nn.Module)
|
| 51 |
-
if args.tpu:
|
| 52 |
-
wrapped_model = TPUDistributedDataParallel(
|
| 53 |
-
module=model.to(device),
|
| 54 |
-
process_group=process_group,
|
| 55 |
-
)
|
| 56 |
-
# forward missing getattr and state_dict/load_state_dict to orig model
|
| 57 |
-
wrapped_model = ModuleProxyWrapper(wrapped_model)
|
| 58 |
-
elif args.ddp_backend in {"c10d", "pytorch_ddp"}:
|
| 59 |
-
wrapped_model = DistributedDataParallel(
|
| 60 |
-
module=model.to(device),
|
| 61 |
-
device_ids=[args.device_id],
|
| 62 |
-
output_device=args.device_id,
|
| 63 |
-
broadcast_buffers=args.broadcast_buffers,
|
| 64 |
-
bucket_cap_mb=args.bucket_cap_mb,
|
| 65 |
-
process_group=process_group,
|
| 66 |
-
find_unused_parameters=args.find_unused_parameters,
|
| 67 |
-
gradient_as_bucket_view=args.gradient_as_bucket_view,
|
| 68 |
-
)
|
| 69 |
-
if args.ddp_comm_hook == "fp16":
|
| 70 |
-
logger.info("enable fp16 communication hook in DDP")
|
| 71 |
-
try:
|
| 72 |
-
from torch.distributed.algorithms.ddp_comm_hooks import (
|
| 73 |
-
DDPCommHookType,
|
| 74 |
-
register_ddp_comm_hook,
|
| 75 |
-
)
|
| 76 |
-
except:
|
| 77 |
-
logger.error(
|
| 78 |
-
"Could not import from torch.distributed.algorithms.ddp_comm_hooks; you may need to update your pytorch version"
|
| 79 |
-
)
|
| 80 |
-
raise
|
| 81 |
-
|
| 82 |
-
register_ddp_comm_hook(DDPCommHookType.FP16_COMPRESS, wrapped_model)
|
| 83 |
-
# forward missing getattr and state_dict/load_state_dict to orig model
|
| 84 |
-
wrapped_model = ModuleProxyWrapper(wrapped_model)
|
| 85 |
-
elif args.ddp_backend in {"no_c10d", "legacy_ddp"}:
|
| 86 |
-
wrapped_model = LegacyDistributedDataParallel(
|
| 87 |
-
module=model.to(device),
|
| 88 |
-
buffer_size=2**28,
|
| 89 |
-
process_group=process_group,
|
| 90 |
-
)
|
| 91 |
-
# forward missing getattr and state_dict/load_state_dict to orig model
|
| 92 |
-
wrapped_model = ModuleProxyWrapper(wrapped_model)
|
| 93 |
-
elif args.ddp_backend == "slowmo":
|
| 94 |
-
if _SLOWMO_DDP_DISABLED:
|
| 95 |
-
raise ImportError(
|
| 96 |
-
"Cannot find SlowMoDistributedDataParallel. "
|
| 97 |
-
"Please install fairscale with: pip install fairscale"
|
| 98 |
-
)
|
| 99 |
-
|
| 100 |
-
# The values of slowmo_momentum below were obtained by tuning on the
|
| 101 |
-
# En-De 16 dataset by training the transformer_wmt_en_de_large model
|
| 102 |
-
if args.slowmo_momentum is None:
|
| 103 |
-
if args.distributed_world_size <= 16:
|
| 104 |
-
args.slowmo_momentum = 0.0
|
| 105 |
-
elif args.distributed_world_size <= 32:
|
| 106 |
-
args.slowmo_momentum = 0.2
|
| 107 |
-
elif args.distributed_world_size <= 64:
|
| 108 |
-
args.slowmo_momentum = 0.5
|
| 109 |
-
else:
|
| 110 |
-
args.slowmo_momentum = 0.6
|
| 111 |
-
slowmo_base_algorithm = SlowMoBaseAlgorithm[args.slowmo_base_algorithm.upper()]
|
| 112 |
-
|
| 113 |
-
wrapped_model = SlowMoDistributedDataParallel(
|
| 114 |
-
module=model.to(device),
|
| 115 |
-
broadcast_buffers=args.broadcast_buffers,
|
| 116 |
-
nprocs_per_node=args.nprocs_per_node,
|
| 117 |
-
slowmo_momentum=args.slowmo_momentum,
|
| 118 |
-
slowmo_base_algorithm=slowmo_base_algorithm,
|
| 119 |
-
localsgd_frequency=args.localsgd_frequency,
|
| 120 |
-
)
|
| 121 |
-
# forward missing getattr and state_dict/load_state_dict to orig model
|
| 122 |
-
wrapped_model = ModuleProxyWrapper(wrapped_model)
|
| 123 |
-
elif args.ddp_backend == "fully_sharded":
|
| 124 |
-
try:
|
| 125 |
-
from fairscale.nn.data_parallel import FullyShardedDataParallel as FSDP
|
| 126 |
-
except ImportError:
|
| 127 |
-
raise ImportError(
|
| 128 |
-
"Cannot find FullyShardedDataParallel. "
|
| 129 |
-
"Please install fairscale with: pip install fairscale"
|
| 130 |
-
)
|
| 131 |
-
assert isinstance(model, FSDP), "expected model to already be wrapped in FSDP"
|
| 132 |
-
wrapped_model = model
|
| 133 |
-
if args.memory_efficient_fp16:
|
| 134 |
-
wrapped_model = wrapped_model.half()
|
| 135 |
-
if not args.cpu_offload:
|
| 136 |
-
wrapped_model = wrapped_model.to(device=device)
|
| 137 |
-
else:
|
| 138 |
-
raise ValueError("Unknown --ddp-backend: " + args.ddp_backend)
|
| 139 |
-
|
| 140 |
-
# kill hung distributed jobs after a timeout
|
| 141 |
-
if getattr(args, "heartbeat_timeout", -1) > 0:
|
| 142 |
-
wrapped_model = DistributedTimeoutWrapper(
|
| 143 |
-
wrapped_model, timeout=getattr(args, "heartbeat_timeout", -1)
|
| 144 |
-
)
|
| 145 |
-
|
| 146 |
-
return wrapped_model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/ema/__init__.py
DELETED
|
@@ -1,20 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import importlib
|
| 7 |
-
import os
|
| 8 |
-
|
| 9 |
-
from .ema import EMA
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
def build_ema(model, cfg, device):
|
| 13 |
-
return EMA(model, cfg, device)
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
# automatically import any Python files in the models/ema/ directory
|
| 17 |
-
for file in sorted(os.listdir(os.path.dirname(__file__))):
|
| 18 |
-
if file.endswith(".py") and not file.startswith("_"):
|
| 19 |
-
file_name = file[: file.find(".py")]
|
| 20 |
-
importlib.import_module("fairseq.models.ema." + file_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/ema/ema.py
DELETED
|
@@ -1,208 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
|
| 3 |
-
"""
|
| 4 |
-
This module has the EMA class used to store a copy of the exponentially decayed
|
| 5 |
-
model params.
|
| 6 |
-
|
| 7 |
-
Typical usage of EMA class involves initializing an object using an existing
|
| 8 |
-
model (random or from a seed model) and setting the config like ema_decay,
|
| 9 |
-
ema_start_update which determine how the EMA model is updated. After every
|
| 10 |
-
update of the model i.e. at the end of the train_step, the EMA should be updated
|
| 11 |
-
by passing the new model to the EMA.step function. The EMA model state dict
|
| 12 |
-
can be stored in the extra state under the key of "ema" and dumped
|
| 13 |
-
into a checkpoint and loaded. The EMA object can be passed to tasks
|
| 14 |
-
by setting task.uses_ema property.
|
| 15 |
-
EMA is a smoothed/ensemble model which might have better performance
|
| 16 |
-
when used for inference or further fine-tuning. EMA class has a
|
| 17 |
-
reverse function to load the EMA params into a model and use it
|
| 18 |
-
like a regular model.
|
| 19 |
-
|
| 20 |
-
This implementation is used for trainer-level ema tracking. For EMA tracking
|
| 21 |
-
inside the model, please use fairseq/modules/ema_module.py instead.
|
| 22 |
-
"""
|
| 23 |
-
|
| 24 |
-
import copy
|
| 25 |
-
import logging
|
| 26 |
-
|
| 27 |
-
import torch
|
| 28 |
-
from fairseq import checkpoint_utils
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
class EMA(object):
|
| 32 |
-
"""Exponential Moving Average of Fairseq Models
|
| 33 |
-
EMA keeps a copy of the exponentially decayed model params.
|
| 34 |
-
The set of params should include both gradient-descent and
|
| 35 |
-
non-gradient descent params, such as batch mean/var and buffers.
|
| 36 |
-
This is a modified implementation of
|
| 37 |
-
the open source code in https://github.com/zhawe01/fairseq-gec.git,
|
| 38 |
-
and internal source code in
|
| 39 |
-
fbcode/mobile-vision/projects/classification_pytorch/lib/utils/model_ema.py.
|
| 40 |
-
|
| 41 |
-
Similar to TF EMA.
|
| 42 |
-
https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage.
|
| 43 |
-
EMA provides a averaged and smoothed set of model weights, and has been shown to
|
| 44 |
-
improve vision models. EMA class does all necessary functions to update, reload,
|
| 45 |
-
or init EMA methods.
|
| 46 |
-
|
| 47 |
-
EMA object is initialized from an arbitrary model. By default, it is stored in
|
| 48 |
-
the same device (unless device specified at initialization) and with the
|
| 49 |
-
same precision as the model (unless ema_fp32 is True). ema_fp32 is recommended.
|
| 50 |
-
This stores the EMA parameters in fp32 only for the EMA update step, and
|
| 51 |
-
is used at the default precision otherwise.
|
| 52 |
-
EMA is usually enabled using EMAConfig with store_ema=True. Some important
|
| 53 |
-
parameters to configure EMA are
|
| 54 |
-
1) ema_decay - The decay of EMA
|
| 55 |
-
2) ema_update_freq - EMA is updated every this many model updates.
|
| 56 |
-
3) ema_start_update - Start EMA update after this many model updates [default 0]
|
| 57 |
-
|
| 58 |
-
Key methods:
|
| 59 |
-
1) step - One update of EMA using new model
|
| 60 |
-
2) restore - Update EMA from a state dict
|
| 61 |
-
3) reverse - Load EMA into a model
|
| 62 |
-
4) get_decay, _set_decay - Used to get or set the decay. Note _set_decay is
|
| 63 |
-
called from step.
|
| 64 |
-
5) build_fp32_params - Used to initialize or update the fp32 copy of EMA params.
|
| 65 |
-
Note this is enabled only when ema_fp32=True
|
| 66 |
-
"""
|
| 67 |
-
|
| 68 |
-
def __init__(self, model, config, device=None, skip_keys=None):
|
| 69 |
-
"""
|
| 70 |
-
@param model model to initialize the EMA with
|
| 71 |
-
@param config EMAConfig object with configuration like
|
| 72 |
-
ema_decay, ema_update_freq, ema_fp32
|
| 73 |
-
@param device If provided, copy EMA to this device (e.g. gpu).
|
| 74 |
-
Otherwise EMA is in the same device as the model.
|
| 75 |
-
"""
|
| 76 |
-
|
| 77 |
-
self.decay = config.ema_decay
|
| 78 |
-
self.model = copy.deepcopy(model)
|
| 79 |
-
self.model.requires_grad_(False)
|
| 80 |
-
self.config = config
|
| 81 |
-
self.skip_keys = skip_keys or set()
|
| 82 |
-
self.fp32_params = {}
|
| 83 |
-
|
| 84 |
-
if self.config.ema_seed_model is not None:
|
| 85 |
-
state = checkpoint_utils.load_ema_from_checkpoint(
|
| 86 |
-
self.config.ema_seed_model
|
| 87 |
-
)
|
| 88 |
-
self.model.load_state_dict(state["model"], strict=True)
|
| 89 |
-
|
| 90 |
-
if device is not None:
|
| 91 |
-
logging.info(f"Copying EMA model to device {device}")
|
| 92 |
-
self.model = self.model.to(device=device)
|
| 93 |
-
|
| 94 |
-
if self.config.ema_fp32:
|
| 95 |
-
self.build_fp32_params()
|
| 96 |
-
|
| 97 |
-
self.update_freq_counter = 0
|
| 98 |
-
|
| 99 |
-
def get_model(self):
|
| 100 |
-
return self.model
|
| 101 |
-
|
| 102 |
-
def build_fp32_params(self, state_dict=None):
|
| 103 |
-
"""
|
| 104 |
-
Store a copy of the EMA params in fp32.
|
| 105 |
-
If state dict is passed, the EMA params is copied from
|
| 106 |
-
the provided state dict. Otherwise, it is copied from the
|
| 107 |
-
current EMA model parameters.
|
| 108 |
-
"""
|
| 109 |
-
if not self.config.ema_fp32:
|
| 110 |
-
raise RuntimeError(
|
| 111 |
-
"build_fp32_params should not be called if ema_fp32=False. "
|
| 112 |
-
"Use ema_fp32=True if this is really intended."
|
| 113 |
-
)
|
| 114 |
-
|
| 115 |
-
if state_dict is None:
|
| 116 |
-
state_dict = self.model.state_dict()
|
| 117 |
-
|
| 118 |
-
def _to_float(t):
|
| 119 |
-
return t.float() if torch.is_floating_point(t) else t
|
| 120 |
-
|
| 121 |
-
for param_key in state_dict:
|
| 122 |
-
if param_key in self.fp32_params:
|
| 123 |
-
self.fp32_params[param_key].copy_(state_dict[param_key])
|
| 124 |
-
else:
|
| 125 |
-
self.fp32_params[param_key] = _to_float(state_dict[param_key])
|
| 126 |
-
|
| 127 |
-
def restore(self, state_dict, build_fp32_params=False):
|
| 128 |
-
"""Load data from a model spec into EMA model"""
|
| 129 |
-
self.model.load_state_dict(state_dict, strict=False)
|
| 130 |
-
if build_fp32_params:
|
| 131 |
-
self.build_fp32_params(state_dict)
|
| 132 |
-
|
| 133 |
-
def _set_decay(self, decay):
|
| 134 |
-
self.decay = decay
|
| 135 |
-
|
| 136 |
-
def get_decay(self):
|
| 137 |
-
return self.decay
|
| 138 |
-
|
| 139 |
-
def _step_internal(self, new_model, updates=None):
|
| 140 |
-
"""One update of the EMA model based on new model weights"""
|
| 141 |
-
decay = self.decay
|
| 142 |
-
|
| 143 |
-
ema_state_dict = {}
|
| 144 |
-
ema_params = (
|
| 145 |
-
self.fp32_params if self.config.ema_fp32 else self.model.state_dict()
|
| 146 |
-
)
|
| 147 |
-
for key, param in new_model.state_dict().items():
|
| 148 |
-
if isinstance(param, dict):
|
| 149 |
-
continue
|
| 150 |
-
try:
|
| 151 |
-
ema_param = ema_params[key]
|
| 152 |
-
except KeyError:
|
| 153 |
-
ema_param = (
|
| 154 |
-
param.float().clone() if param.ndim == 1 else copy.deepcopy(param)
|
| 155 |
-
)
|
| 156 |
-
|
| 157 |
-
if param.shape != ema_param.shape:
|
| 158 |
-
raise ValueError(
|
| 159 |
-
"incompatible tensor shapes between model param and ema param"
|
| 160 |
-
+ "{} vs. {}".format(param.shape, ema_param.shape)
|
| 161 |
-
)
|
| 162 |
-
|
| 163 |
-
if "version" in key:
|
| 164 |
-
# Do not decay a model.version pytorch param
|
| 165 |
-
continue
|
| 166 |
-
|
| 167 |
-
if key in self.skip_keys:
|
| 168 |
-
ema_param = param.to(dtype=ema_param.dtype).clone()
|
| 169 |
-
else:
|
| 170 |
-
ema_param.mul_(decay)
|
| 171 |
-
ema_param.add_(param.to(dtype=ema_param.dtype), alpha=1 - decay)
|
| 172 |
-
ema_state_dict[key] = ema_param
|
| 173 |
-
self.restore(ema_state_dict, build_fp32_params=False)
|
| 174 |
-
|
| 175 |
-
def step(self, new_model, updates=None):
|
| 176 |
-
"""
|
| 177 |
-
One update of EMA which is done every self.config.ema_update_freq
|
| 178 |
-
updates of the model.
|
| 179 |
-
|
| 180 |
-
@param updates The current number of model updates done.
|
| 181 |
-
Decay is set of 0 if model updates < ema_start_update, which means
|
| 182 |
-
the model will be simply copied over to the EMA.
|
| 183 |
-
When model updates >= ema_start_updates, then EMA is updated with
|
| 184 |
-
a decay of self.config.ema_decay.
|
| 185 |
-
"""
|
| 186 |
-
if updates is not None:
|
| 187 |
-
self._set_decay(
|
| 188 |
-
0 if updates < self.config.ema_start_update else self.config.ema_decay
|
| 189 |
-
)
|
| 190 |
-
if self.config.ema_update_freq > 1:
|
| 191 |
-
self.update_freq_counter += 1
|
| 192 |
-
if self.update_freq_counter >= self.config.ema_update_freq:
|
| 193 |
-
self._step_internal(new_model, updates)
|
| 194 |
-
self.update_freq_counter = 0
|
| 195 |
-
else:
|
| 196 |
-
self._step_internal(new_model, updates)
|
| 197 |
-
|
| 198 |
-
def reverse(self, model):
|
| 199 |
-
"""
|
| 200 |
-
Load the model parameters from EMA model.
|
| 201 |
-
Useful for inference or fine-tuning from the EMA model.
|
| 202 |
-
"""
|
| 203 |
-
d = self.model.state_dict()
|
| 204 |
-
if "_ema" in d:
|
| 205 |
-
del d["_ema"]
|
| 206 |
-
|
| 207 |
-
model.load_state_dict(d, strict=False)
|
| 208 |
-
return model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/fairseq_decoder.py
DELETED
|
@@ -1,104 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
from typing import Dict, List, Optional, Tuple
|
| 7 |
-
|
| 8 |
-
import torch.nn as nn
|
| 9 |
-
from fairseq import utils
|
| 10 |
-
from torch import Tensor
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
class FairseqDecoder(nn.Module):
|
| 14 |
-
"""Base class for decoders."""
|
| 15 |
-
|
| 16 |
-
def __init__(self, dictionary):
|
| 17 |
-
super().__init__()
|
| 18 |
-
self.dictionary = dictionary
|
| 19 |
-
self.onnx_trace = False
|
| 20 |
-
self.adaptive_softmax = None
|
| 21 |
-
|
| 22 |
-
def forward(self, prev_output_tokens, encoder_out=None, **kwargs):
|
| 23 |
-
"""
|
| 24 |
-
Args:
|
| 25 |
-
prev_output_tokens (LongTensor): shifted output tokens of shape
|
| 26 |
-
`(batch, tgt_len)`, for teacher forcing
|
| 27 |
-
encoder_out (dict, optional): output from the encoder, used for
|
| 28 |
-
encoder-side attention
|
| 29 |
-
|
| 30 |
-
Returns:
|
| 31 |
-
tuple:
|
| 32 |
-
- the decoder's output of shape `(batch, tgt_len, vocab)`
|
| 33 |
-
- a dictionary with any model-specific outputs
|
| 34 |
-
"""
|
| 35 |
-
x, extra = self.extract_features(
|
| 36 |
-
prev_output_tokens, encoder_out=encoder_out, **kwargs
|
| 37 |
-
)
|
| 38 |
-
x = self.output_layer(x)
|
| 39 |
-
return x, extra
|
| 40 |
-
|
| 41 |
-
def extract_features(self, prev_output_tokens, encoder_out=None, **kwargs):
|
| 42 |
-
"""
|
| 43 |
-
Returns:
|
| 44 |
-
tuple:
|
| 45 |
-
- the decoder's features of shape `(batch, tgt_len, embed_dim)`
|
| 46 |
-
- a dictionary with any model-specific outputs
|
| 47 |
-
"""
|
| 48 |
-
raise NotImplementedError
|
| 49 |
-
|
| 50 |
-
def output_layer(self, features, **kwargs):
|
| 51 |
-
"""
|
| 52 |
-
Project features to the default output size, e.g., vocabulary size.
|
| 53 |
-
|
| 54 |
-
Args:
|
| 55 |
-
features (Tensor): features returned by *extract_features*.
|
| 56 |
-
"""
|
| 57 |
-
raise NotImplementedError
|
| 58 |
-
|
| 59 |
-
def get_normalized_probs(
|
| 60 |
-
self,
|
| 61 |
-
net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]],
|
| 62 |
-
log_probs: bool,
|
| 63 |
-
sample: Optional[Dict[str, Tensor]] = None,
|
| 64 |
-
):
|
| 65 |
-
"""Get normalized probabilities (or log probs) from a net's output."""
|
| 66 |
-
return self.get_normalized_probs_scriptable(net_output, log_probs, sample)
|
| 67 |
-
|
| 68 |
-
# TorchScript doesn't support super() method so that the scriptable Subclass
|
| 69 |
-
# can't access the base class model in Torchscript.
|
| 70 |
-
# Current workaround is to add a helper function with different name and
|
| 71 |
-
# call the helper function from scriptable Subclass.
|
| 72 |
-
def get_normalized_probs_scriptable(
|
| 73 |
-
self,
|
| 74 |
-
net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]],
|
| 75 |
-
log_probs: bool,
|
| 76 |
-
sample: Optional[Dict[str, Tensor]] = None,
|
| 77 |
-
):
|
| 78 |
-
"""Get normalized probabilities (or log probs) from a net's output."""
|
| 79 |
-
|
| 80 |
-
if hasattr(self, "adaptive_softmax") and self.adaptive_softmax is not None:
|
| 81 |
-
if sample is not None:
|
| 82 |
-
assert "target" in sample
|
| 83 |
-
target = sample["target"]
|
| 84 |
-
else:
|
| 85 |
-
target = None
|
| 86 |
-
out = self.adaptive_softmax.get_log_prob(net_output[0], target=target)
|
| 87 |
-
return out.exp_() if not log_probs else out
|
| 88 |
-
|
| 89 |
-
logits = net_output[0]
|
| 90 |
-
if log_probs:
|
| 91 |
-
return utils.log_softmax(logits, dim=-1, onnx_trace=self.onnx_trace)
|
| 92 |
-
else:
|
| 93 |
-
return utils.softmax(logits, dim=-1, onnx_trace=self.onnx_trace)
|
| 94 |
-
|
| 95 |
-
def max_positions(self):
|
| 96 |
-
"""Maximum input length supported by the decoder."""
|
| 97 |
-
return 1e6 # an arbitrary large number
|
| 98 |
-
|
| 99 |
-
def upgrade_state_dict_named(self, state_dict, name):
|
| 100 |
-
"""Upgrade old state dicts to work with newer code."""
|
| 101 |
-
return state_dict
|
| 102 |
-
|
| 103 |
-
def prepare_for_onnx_export_(self):
|
| 104 |
-
self.onnx_trace = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/fairseq_encoder.py
DELETED
|
@@ -1,91 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
from typing import Dict, List, NamedTuple, Optional
|
| 7 |
-
|
| 8 |
-
import torch
|
| 9 |
-
import torch.nn as nn
|
| 10 |
-
from torch import Tensor
|
| 11 |
-
|
| 12 |
-
EncoderOut = NamedTuple(
|
| 13 |
-
"EncoderOut",
|
| 14 |
-
[
|
| 15 |
-
("encoder_out", Tensor), # T x B x C
|
| 16 |
-
("encoder_padding_mask", Optional[Tensor]), # B x T
|
| 17 |
-
("encoder_embedding", Optional[Tensor]), # B x T x C
|
| 18 |
-
("encoder_states", Optional[List[Tensor]]), # List[T x B x C]
|
| 19 |
-
("src_tokens", Optional[Tensor]), # B x T
|
| 20 |
-
("src_lengths", Optional[Tensor]), # B x 1
|
| 21 |
-
],
|
| 22 |
-
)
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
class FairseqEncoder(nn.Module):
|
| 26 |
-
"""Base class for encoders."""
|
| 27 |
-
|
| 28 |
-
def __init__(self, dictionary):
|
| 29 |
-
super().__init__()
|
| 30 |
-
self.dictionary = dictionary
|
| 31 |
-
|
| 32 |
-
def forward(self, src_tokens, src_lengths=None, **kwargs):
|
| 33 |
-
"""
|
| 34 |
-
Args:
|
| 35 |
-
src_tokens (LongTensor): tokens in the source language of shape
|
| 36 |
-
`(batch, src_len)`
|
| 37 |
-
src_lengths (LongTensor): lengths of each source sentence of shape
|
| 38 |
-
`(batch)`
|
| 39 |
-
"""
|
| 40 |
-
raise NotImplementedError
|
| 41 |
-
|
| 42 |
-
def forward_torchscript(self, net_input: Dict[str, Tensor]):
|
| 43 |
-
"""A TorchScript-compatible version of forward.
|
| 44 |
-
|
| 45 |
-
Encoders which use additional arguments may want to override
|
| 46 |
-
this method for TorchScript compatibility.
|
| 47 |
-
"""
|
| 48 |
-
if torch.jit.is_scripting():
|
| 49 |
-
return self.forward(
|
| 50 |
-
src_tokens=net_input["src_tokens"],
|
| 51 |
-
src_lengths=net_input["src_lengths"],
|
| 52 |
-
)
|
| 53 |
-
else:
|
| 54 |
-
return self.forward_non_torchscript(net_input)
|
| 55 |
-
|
| 56 |
-
@torch.jit.unused
|
| 57 |
-
def forward_non_torchscript(self, net_input: Dict[str, Tensor]):
|
| 58 |
-
encoder_input = {
|
| 59 |
-
k: v for k, v in net_input.items() if k != "prev_output_tokens"
|
| 60 |
-
}
|
| 61 |
-
return self.forward(**encoder_input)
|
| 62 |
-
|
| 63 |
-
def reorder_encoder_out(self, encoder_out, new_order):
|
| 64 |
-
"""
|
| 65 |
-
Reorder encoder output according to `new_order`.
|
| 66 |
-
|
| 67 |
-
Args:
|
| 68 |
-
encoder_out: output from the ``forward()`` method
|
| 69 |
-
new_order (LongTensor): desired order
|
| 70 |
-
|
| 71 |
-
Returns:
|
| 72 |
-
`encoder_out` rearranged according to `new_order`
|
| 73 |
-
"""
|
| 74 |
-
raise NotImplementedError
|
| 75 |
-
|
| 76 |
-
def max_positions(self):
|
| 77 |
-
"""Maximum input length supported by the encoder."""
|
| 78 |
-
return 1e6 # an arbitrary large number
|
| 79 |
-
|
| 80 |
-
def upgrade_state_dict_named(self, state_dict, name):
|
| 81 |
-
"""Upgrade old state dicts to work with newer code."""
|
| 82 |
-
return state_dict
|
| 83 |
-
|
| 84 |
-
def set_num_updates(self, num_updates):
|
| 85 |
-
"""State from trainer to pass along to model at every update."""
|
| 86 |
-
|
| 87 |
-
def _apply(m):
|
| 88 |
-
if hasattr(m, "set_num_updates") and m != self:
|
| 89 |
-
m.set_num_updates(num_updates)
|
| 90 |
-
|
| 91 |
-
self.apply(_apply)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/fairseq_incremental_decoder.py
DELETED
|
@@ -1,117 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import logging
|
| 7 |
-
from typing import Dict, Optional
|
| 8 |
-
|
| 9 |
-
from fairseq.incremental_decoding_utils import with_incremental_state
|
| 10 |
-
from fairseq.models import FairseqDecoder
|
| 11 |
-
from torch import Tensor
|
| 12 |
-
|
| 13 |
-
logger = logging.getLogger(__name__)
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
@with_incremental_state
|
| 17 |
-
class FairseqIncrementalDecoder(FairseqDecoder):
|
| 18 |
-
"""Base class for incremental decoders.
|
| 19 |
-
|
| 20 |
-
Incremental decoding is a special mode at inference time where the Model
|
| 21 |
-
only receives a single timestep of input corresponding to the previous
|
| 22 |
-
output token (for teacher forcing) and must produce the next output
|
| 23 |
-
*incrementally*. Thus the model must cache any long-term state that is
|
| 24 |
-
needed about the sequence, e.g., hidden states, convolutional states, etc.
|
| 25 |
-
|
| 26 |
-
Compared to the standard :class:`FairseqDecoder` interface, the incremental
|
| 27 |
-
decoder interface allows :func:`forward` functions to take an extra keyword
|
| 28 |
-
argument (*incremental_state*) that can be used to cache state across
|
| 29 |
-
time-steps.
|
| 30 |
-
|
| 31 |
-
The :class:`FairseqIncrementalDecoder` interface also defines the
|
| 32 |
-
:func:`reorder_incremental_state` method, which is used during beam search
|
| 33 |
-
to select and reorder the incremental state based on the selection of beams.
|
| 34 |
-
|
| 35 |
-
To learn more about how incremental decoding works, refer to `this blog
|
| 36 |
-
<http://www.telesens.co/2019/04/21/understanding-incremental-decoding-in-fairseq/>`_.
|
| 37 |
-
"""
|
| 38 |
-
|
| 39 |
-
def __init__(self, dictionary):
|
| 40 |
-
super().__init__(dictionary)
|
| 41 |
-
|
| 42 |
-
def forward(
|
| 43 |
-
self, prev_output_tokens, encoder_out=None, incremental_state=None, **kwargs
|
| 44 |
-
):
|
| 45 |
-
"""
|
| 46 |
-
Args:
|
| 47 |
-
prev_output_tokens (LongTensor): shifted output tokens of shape
|
| 48 |
-
`(batch, tgt_len)`, for teacher forcing
|
| 49 |
-
encoder_out (dict, optional): output from the encoder, used for
|
| 50 |
-
encoder-side attention
|
| 51 |
-
incremental_state (dict, optional): dictionary used for storing
|
| 52 |
-
state during :ref:`Incremental decoding`
|
| 53 |
-
|
| 54 |
-
Returns:
|
| 55 |
-
tuple:
|
| 56 |
-
- the decoder's output of shape `(batch, tgt_len, vocab)`
|
| 57 |
-
- a dictionary with any model-specific outputs
|
| 58 |
-
"""
|
| 59 |
-
raise NotImplementedError
|
| 60 |
-
|
| 61 |
-
def extract_features(
|
| 62 |
-
self, prev_output_tokens, encoder_out=None, incremental_state=None, **kwargs
|
| 63 |
-
):
|
| 64 |
-
"""
|
| 65 |
-
Returns:
|
| 66 |
-
tuple:
|
| 67 |
-
- the decoder's features of shape `(batch, tgt_len, embed_dim)`
|
| 68 |
-
- a dictionary with any model-specific outputs
|
| 69 |
-
"""
|
| 70 |
-
raise NotImplementedError
|
| 71 |
-
|
| 72 |
-
def reorder_incremental_state(
|
| 73 |
-
self,
|
| 74 |
-
incremental_state: Dict[str, Dict[str, Optional[Tensor]]],
|
| 75 |
-
new_order: Tensor,
|
| 76 |
-
):
|
| 77 |
-
"""Reorder incremental state.
|
| 78 |
-
|
| 79 |
-
This will be called when the order of the input has changed from the
|
| 80 |
-
previous time step. A typical use case is beam search, where the input
|
| 81 |
-
order changes between time steps based on the selection of beams.
|
| 82 |
-
"""
|
| 83 |
-
pass
|
| 84 |
-
|
| 85 |
-
def reorder_incremental_state_scripting(
|
| 86 |
-
self,
|
| 87 |
-
incremental_state: Dict[str, Dict[str, Optional[Tensor]]],
|
| 88 |
-
new_order: Tensor,
|
| 89 |
-
):
|
| 90 |
-
"""Main entry point for reordering the incremental state.
|
| 91 |
-
|
| 92 |
-
Due to limitations in TorchScript, we call this function in
|
| 93 |
-
:class:`fairseq.sequence_generator.SequenceGenerator` instead of
|
| 94 |
-
calling :func:`reorder_incremental_state` directly.
|
| 95 |
-
"""
|
| 96 |
-
for module in self.modules():
|
| 97 |
-
if hasattr(module, "reorder_incremental_state"):
|
| 98 |
-
result = module.reorder_incremental_state(incremental_state, new_order)
|
| 99 |
-
if result is not None:
|
| 100 |
-
incremental_state = result
|
| 101 |
-
|
| 102 |
-
def set_beam_size(self, beam_size):
|
| 103 |
-
"""Sets the beam size in the decoder and all children."""
|
| 104 |
-
if getattr(self, "_beam_size", -1) != beam_size:
|
| 105 |
-
seen = set()
|
| 106 |
-
|
| 107 |
-
def apply_set_beam_size(module):
|
| 108 |
-
if (
|
| 109 |
-
module != self
|
| 110 |
-
and hasattr(module, "set_beam_size")
|
| 111 |
-
and module not in seen
|
| 112 |
-
):
|
| 113 |
-
seen.add(module)
|
| 114 |
-
module.set_beam_size(beam_size)
|
| 115 |
-
|
| 116 |
-
self.apply(apply_set_beam_size)
|
| 117 |
-
self._beam_size = beam_size
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/fairseq_model.py
DELETED
|
@@ -1,573 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
"""
|
| 6 |
-
Base classes for various fairseq models.
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
import logging
|
| 10 |
-
from argparse import Namespace
|
| 11 |
-
from typing import Dict, List, Optional, Tuple
|
| 12 |
-
|
| 13 |
-
import torch
|
| 14 |
-
import torch.nn as nn
|
| 15 |
-
import torch.nn.functional as F
|
| 16 |
-
from fairseq import utils
|
| 17 |
-
from fairseq.data import Dictionary
|
| 18 |
-
from fairseq.dataclass.utils import (
|
| 19 |
-
convert_namespace_to_omegaconf,
|
| 20 |
-
gen_parser_from_dataclass,
|
| 21 |
-
)
|
| 22 |
-
from fairseq.models import FairseqDecoder, FairseqEncoder
|
| 23 |
-
from omegaconf import DictConfig
|
| 24 |
-
from torch import Tensor
|
| 25 |
-
|
| 26 |
-
logger = logging.getLogger(__name__)
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def check_type(module, expected_type):
|
| 30 |
-
if hasattr(module, "unwrapped_module"):
|
| 31 |
-
assert isinstance(
|
| 32 |
-
module.unwrapped_module, expected_type
|
| 33 |
-
), f"{type(module.unwrapped_module)} != {expected_type}"
|
| 34 |
-
else:
|
| 35 |
-
assert isinstance(module, expected_type), f"{type(module)} != {expected_type}"
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
class BaseFairseqModel(nn.Module):
|
| 39 |
-
"""Base class for fairseq models."""
|
| 40 |
-
|
| 41 |
-
def __init__(self):
|
| 42 |
-
super().__init__()
|
| 43 |
-
self._is_generation_fast = False
|
| 44 |
-
|
| 45 |
-
@classmethod
|
| 46 |
-
def add_args(cls, parser):
|
| 47 |
-
"""Add model-specific arguments to the parser."""
|
| 48 |
-
dc = getattr(cls, "__dataclass", None)
|
| 49 |
-
if dc is not None:
|
| 50 |
-
# do not set defaults so that settings defaults from various architectures still works
|
| 51 |
-
gen_parser_from_dataclass(parser, dc(), delete_default=True)
|
| 52 |
-
|
| 53 |
-
@classmethod
|
| 54 |
-
def build_model(cls, args, task):
|
| 55 |
-
"""Build a new model instance."""
|
| 56 |
-
raise NotImplementedError("Model must implement the build_model method")
|
| 57 |
-
|
| 58 |
-
def get_targets(self, sample, net_output):
|
| 59 |
-
"""Get targets from either the sample or the net's output."""
|
| 60 |
-
return sample["target"]
|
| 61 |
-
|
| 62 |
-
def get_normalized_probs(
|
| 63 |
-
self,
|
| 64 |
-
net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]],
|
| 65 |
-
log_probs: bool,
|
| 66 |
-
sample: Optional[Dict[str, Tensor]] = None,
|
| 67 |
-
):
|
| 68 |
-
"""Get normalized probabilities (or log probs) from a net's output."""
|
| 69 |
-
return self.get_normalized_probs_scriptable(net_output, log_probs, sample)
|
| 70 |
-
|
| 71 |
-
# TorchScript doesn't support super() method so that the scriptable Subclass
|
| 72 |
-
# can't access the base class model in Torchscript.
|
| 73 |
-
# Current workaround is to add a helper function with different name and
|
| 74 |
-
# call the helper function from scriptable Subclass.
|
| 75 |
-
def get_normalized_probs_scriptable(
|
| 76 |
-
self,
|
| 77 |
-
net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]],
|
| 78 |
-
log_probs: bool,
|
| 79 |
-
sample: Optional[Dict[str, Tensor]] = None,
|
| 80 |
-
):
|
| 81 |
-
"""Scriptable helper function for get_normalized_probs in ~BaseFairseqModel"""
|
| 82 |
-
if hasattr(self, "decoder"):
|
| 83 |
-
return self.decoder.get_normalized_probs(net_output, log_probs, sample)
|
| 84 |
-
elif torch.is_tensor(net_output):
|
| 85 |
-
# syntactic sugar for simple models which don't have a decoder
|
| 86 |
-
# (e.g., the classification tutorial)
|
| 87 |
-
logits = net_output.float()
|
| 88 |
-
if log_probs:
|
| 89 |
-
return F.log_softmax(logits, dim=-1)
|
| 90 |
-
else:
|
| 91 |
-
return F.softmax(logits, dim=-1)
|
| 92 |
-
raise NotImplementedError
|
| 93 |
-
|
| 94 |
-
def extract_features(self, *args, **kwargs):
|
| 95 |
-
"""Similar to *forward* but only return features."""
|
| 96 |
-
return self(*args, **kwargs)
|
| 97 |
-
|
| 98 |
-
def max_positions(self):
|
| 99 |
-
"""Maximum length supported by the model."""
|
| 100 |
-
return None
|
| 101 |
-
|
| 102 |
-
def load_state_dict(
|
| 103 |
-
self,
|
| 104 |
-
state_dict,
|
| 105 |
-
strict=True,
|
| 106 |
-
model_cfg: Optional[DictConfig] = None,
|
| 107 |
-
args: Optional[Namespace] = None,
|
| 108 |
-
):
|
| 109 |
-
"""Copies parameters and buffers from *state_dict* into this module and
|
| 110 |
-
its descendants.
|
| 111 |
-
|
| 112 |
-
Overrides the method in :class:`nn.Module`. Compared with that method
|
| 113 |
-
this additionally "upgrades" *state_dicts* from old checkpoints.
|
| 114 |
-
"""
|
| 115 |
-
|
| 116 |
-
if model_cfg is None and args is not None:
|
| 117 |
-
logger.warn(
|
| 118 |
-
"using 'args' is deprecated, please update your code to use dataclass config"
|
| 119 |
-
)
|
| 120 |
-
model_cfg = convert_namespace_to_omegaconf(args).model
|
| 121 |
-
|
| 122 |
-
self.upgrade_state_dict(state_dict)
|
| 123 |
-
|
| 124 |
-
from fairseq.checkpoint_utils import prune_state_dict
|
| 125 |
-
|
| 126 |
-
new_state_dict = prune_state_dict(state_dict, model_cfg)
|
| 127 |
-
return super().load_state_dict(new_state_dict, strict)
|
| 128 |
-
|
| 129 |
-
def upgrade_state_dict(self, state_dict):
|
| 130 |
-
"""Upgrade old state dicts to work with newer code."""
|
| 131 |
-
self.upgrade_state_dict_named(state_dict, "")
|
| 132 |
-
|
| 133 |
-
def upgrade_state_dict_named(self, state_dict, name):
|
| 134 |
-
"""Upgrade old state dicts to work with newer code.
|
| 135 |
-
|
| 136 |
-
Args:
|
| 137 |
-
state_dict (dict): state dictionary to upgrade, in place
|
| 138 |
-
name (str): the state dict key corresponding to the current module
|
| 139 |
-
"""
|
| 140 |
-
assert state_dict is not None
|
| 141 |
-
|
| 142 |
-
def do_upgrade(m, prefix):
|
| 143 |
-
if len(prefix) > 0:
|
| 144 |
-
prefix += "."
|
| 145 |
-
|
| 146 |
-
for n, c in m.named_children():
|
| 147 |
-
name = prefix + n
|
| 148 |
-
if hasattr(c, "upgrade_state_dict_named"):
|
| 149 |
-
c.upgrade_state_dict_named(state_dict, name)
|
| 150 |
-
elif hasattr(c, "upgrade_state_dict"):
|
| 151 |
-
c.upgrade_state_dict(state_dict)
|
| 152 |
-
do_upgrade(c, name)
|
| 153 |
-
|
| 154 |
-
do_upgrade(self, name)
|
| 155 |
-
|
| 156 |
-
def set_num_updates(self, num_updates):
|
| 157 |
-
"""State from trainer to pass along to model at every update."""
|
| 158 |
-
for m in self.modules():
|
| 159 |
-
if hasattr(m, "set_num_updates") and m != self:
|
| 160 |
-
m.set_num_updates(num_updates)
|
| 161 |
-
|
| 162 |
-
def prepare_for_inference_(self, cfg: DictConfig):
|
| 163 |
-
"""Prepare model for inference."""
|
| 164 |
-
kwargs = {}
|
| 165 |
-
kwargs["beamable_mm_beam_size"] = (
|
| 166 |
-
None
|
| 167 |
-
if getattr(cfg.generation, "no_beamable_mm", False)
|
| 168 |
-
else getattr(cfg.generation, "beam", 5)
|
| 169 |
-
)
|
| 170 |
-
kwargs["need_attn"] = getattr(cfg.generation, "print_alignment", False)
|
| 171 |
-
if getattr(cfg.generation, "retain_dropout", False):
|
| 172 |
-
kwargs["retain_dropout"] = cfg.generation.retain_dropout
|
| 173 |
-
kwargs["retain_dropout_modules"] = cfg.generation.retain_dropout_modules
|
| 174 |
-
self.make_generation_fast_(**kwargs)
|
| 175 |
-
|
| 176 |
-
def make_generation_fast_(self, **kwargs):
|
| 177 |
-
"""
|
| 178 |
-
Legacy entry point to optimize model for faster generation.
|
| 179 |
-
Prefer prepare_for_inference_.
|
| 180 |
-
"""
|
| 181 |
-
if self._is_generation_fast:
|
| 182 |
-
return # only apply once
|
| 183 |
-
self._is_generation_fast = True
|
| 184 |
-
|
| 185 |
-
# remove weight norm from all modules in the network
|
| 186 |
-
def apply_remove_weight_norm(module):
|
| 187 |
-
try:
|
| 188 |
-
nn.utils.remove_weight_norm(module)
|
| 189 |
-
except (AttributeError, ValueError): # this module didn't have weight norm
|
| 190 |
-
return
|
| 191 |
-
|
| 192 |
-
self.apply(apply_remove_weight_norm)
|
| 193 |
-
|
| 194 |
-
def apply_make_generation_fast_(module, prefix):
|
| 195 |
-
if len(prefix) > 0:
|
| 196 |
-
prefix += "."
|
| 197 |
-
|
| 198 |
-
base_func = BaseFairseqModel.make_generation_fast_
|
| 199 |
-
for n, m in module.named_modules():
|
| 200 |
-
if (
|
| 201 |
-
m != self
|
| 202 |
-
and hasattr(m, "make_generation_fast_")
|
| 203 |
-
# don't call this implementation again, e.g., if
|
| 204 |
-
# children modules also inherit from BaseFairseqModel
|
| 205 |
-
and m.make_generation_fast_.__func__ is not base_func
|
| 206 |
-
):
|
| 207 |
-
name = prefix + n
|
| 208 |
-
m.make_generation_fast_(name=name, **kwargs)
|
| 209 |
-
|
| 210 |
-
apply_make_generation_fast_(self, "")
|
| 211 |
-
|
| 212 |
-
def train(mode=True):
|
| 213 |
-
if mode:
|
| 214 |
-
raise RuntimeError("cannot train after make_generation_fast")
|
| 215 |
-
|
| 216 |
-
# this model should no longer be used for training
|
| 217 |
-
self.eval()
|
| 218 |
-
self.train = train
|
| 219 |
-
|
| 220 |
-
def prepare_for_onnx_export_(self, **kwargs):
|
| 221 |
-
"""Make model exportable via ONNX trace."""
|
| 222 |
-
seen = set()
|
| 223 |
-
|
| 224 |
-
def apply_prepare_for_onnx_export_(module):
|
| 225 |
-
if (
|
| 226 |
-
module != self
|
| 227 |
-
and hasattr(module, "prepare_for_onnx_export_")
|
| 228 |
-
and module not in seen
|
| 229 |
-
):
|
| 230 |
-
seen.add(module)
|
| 231 |
-
module.prepare_for_onnx_export_(**kwargs)
|
| 232 |
-
|
| 233 |
-
self.apply(apply_prepare_for_onnx_export_)
|
| 234 |
-
|
| 235 |
-
@classmethod
|
| 236 |
-
def from_pretrained(
|
| 237 |
-
cls,
|
| 238 |
-
model_name_or_path,
|
| 239 |
-
checkpoint_file="model.pt",
|
| 240 |
-
data_name_or_path=".",
|
| 241 |
-
**kwargs,
|
| 242 |
-
):
|
| 243 |
-
"""
|
| 244 |
-
Load a :class:`~fairseq.models.FairseqModel` from a pre-trained model
|
| 245 |
-
file. Downloads and caches the pre-trained model file if needed.
|
| 246 |
-
|
| 247 |
-
The base implementation returns a
|
| 248 |
-
:class:`~fairseq.hub_utils.GeneratorHubInterface`, which can be used to
|
| 249 |
-
generate translations or sample from language models. The underlying
|
| 250 |
-
:class:`~fairseq.models.FairseqModel` can be accessed via the
|
| 251 |
-
*generator.models* attribute.
|
| 252 |
-
|
| 253 |
-
Other models may override this to implement custom hub interfaces.
|
| 254 |
-
|
| 255 |
-
Args:
|
| 256 |
-
model_name_or_path (str): either the name of a pre-trained model to
|
| 257 |
-
load or a path/URL to a pre-trained model state dict
|
| 258 |
-
checkpoint_file (str, optional): colon-separated list of checkpoint
|
| 259 |
-
files in the model archive to ensemble (default: 'model.pt')
|
| 260 |
-
data_name_or_path (str, optional): point args.data to the archive
|
| 261 |
-
at the given path/URL. Can start with '.' or './' to reuse the
|
| 262 |
-
model archive path.
|
| 263 |
-
"""
|
| 264 |
-
from fairseq import hub_utils
|
| 265 |
-
|
| 266 |
-
x = hub_utils.from_pretrained(
|
| 267 |
-
model_name_or_path,
|
| 268 |
-
checkpoint_file,
|
| 269 |
-
data_name_or_path,
|
| 270 |
-
archive_map=cls.hub_models(),
|
| 271 |
-
**kwargs,
|
| 272 |
-
)
|
| 273 |
-
logger.info(x["args"])
|
| 274 |
-
return hub_utils.GeneratorHubInterface(x["args"], x["task"], x["models"])
|
| 275 |
-
|
| 276 |
-
@classmethod
|
| 277 |
-
def hub_models(cls):
|
| 278 |
-
return {}
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
class FairseqEncoderDecoderModel(BaseFairseqModel):
|
| 282 |
-
"""Base class for encoder-decoder models.
|
| 283 |
-
|
| 284 |
-
Args:
|
| 285 |
-
encoder (FairseqEncoder): the encoder
|
| 286 |
-
decoder (FairseqDecoder): the decoder
|
| 287 |
-
"""
|
| 288 |
-
|
| 289 |
-
def __init__(self, encoder, decoder):
|
| 290 |
-
super().__init__()
|
| 291 |
-
|
| 292 |
-
self.encoder = encoder
|
| 293 |
-
self.decoder = decoder
|
| 294 |
-
|
| 295 |
-
check_type(self.encoder, FairseqEncoder)
|
| 296 |
-
check_type(self.decoder, FairseqDecoder)
|
| 297 |
-
|
| 298 |
-
def forward(self, src_tokens, src_lengths, prev_output_tokens, **kwargs):
|
| 299 |
-
"""
|
| 300 |
-
Run the forward pass for an encoder-decoder model.
|
| 301 |
-
|
| 302 |
-
First feed a batch of source tokens through the encoder. Then, feed the
|
| 303 |
-
encoder output and previous decoder outputs (i.e., teacher forcing) to
|
| 304 |
-
the decoder to produce the next outputs::
|
| 305 |
-
|
| 306 |
-
encoder_out = self.encoder(src_tokens, src_lengths)
|
| 307 |
-
return self.decoder(prev_output_tokens, encoder_out)
|
| 308 |
-
|
| 309 |
-
Args:
|
| 310 |
-
src_tokens (LongTensor): tokens in the source language of shape
|
| 311 |
-
`(batch, src_len)`
|
| 312 |
-
src_lengths (LongTensor): source sentence lengths of shape `(batch)`
|
| 313 |
-
prev_output_tokens (LongTensor): previous decoder outputs of shape
|
| 314 |
-
`(batch, tgt_len)`, for teacher forcing
|
| 315 |
-
|
| 316 |
-
Returns:
|
| 317 |
-
tuple:
|
| 318 |
-
- the decoder's output of shape `(batch, tgt_len, vocab)`
|
| 319 |
-
- a dictionary with any model-specific outputs
|
| 320 |
-
"""
|
| 321 |
-
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
|
| 322 |
-
decoder_out = self.decoder(
|
| 323 |
-
prev_output_tokens, encoder_out=encoder_out, **kwargs
|
| 324 |
-
)
|
| 325 |
-
return decoder_out
|
| 326 |
-
|
| 327 |
-
def forward_decoder(self, prev_output_tokens, **kwargs):
|
| 328 |
-
return self.decoder(prev_output_tokens, **kwargs)
|
| 329 |
-
|
| 330 |
-
def extract_features(self, src_tokens, src_lengths, prev_output_tokens, **kwargs):
|
| 331 |
-
"""
|
| 332 |
-
Similar to *forward* but only return features.
|
| 333 |
-
|
| 334 |
-
Returns:
|
| 335 |
-
tuple:
|
| 336 |
-
- the decoder's features of shape `(batch, tgt_len, embed_dim)`
|
| 337 |
-
- a dictionary with any model-specific outputs
|
| 338 |
-
"""
|
| 339 |
-
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
|
| 340 |
-
features = self.decoder.extract_features(
|
| 341 |
-
prev_output_tokens, encoder_out=encoder_out, **kwargs
|
| 342 |
-
)
|
| 343 |
-
return features
|
| 344 |
-
|
| 345 |
-
def output_layer(self, features, **kwargs):
|
| 346 |
-
"""Project features to the default output size (typically vocabulary size)."""
|
| 347 |
-
return self.decoder.output_layer(features, **kwargs)
|
| 348 |
-
|
| 349 |
-
def max_positions(self):
|
| 350 |
-
"""Maximum length supported by the model."""
|
| 351 |
-
return (self.encoder.max_positions(), self.decoder.max_positions())
|
| 352 |
-
|
| 353 |
-
def max_decoder_positions(self):
|
| 354 |
-
"""Maximum length supported by the decoder."""
|
| 355 |
-
return self.decoder.max_positions()
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
class FairseqModel(FairseqEncoderDecoderModel):
|
| 359 |
-
def __init__(self, *args, **kwargs):
|
| 360 |
-
super().__init__(*args, **kwargs)
|
| 361 |
-
utils.deprecation_warning(
|
| 362 |
-
"FairseqModel is deprecated, please use FairseqEncoderDecoderModel "
|
| 363 |
-
"or BaseFairseqModel instead",
|
| 364 |
-
stacklevel=4,
|
| 365 |
-
)
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
class FairseqMultiModel(BaseFairseqModel):
|
| 369 |
-
"""Base class for combining multiple encoder-decoder models."""
|
| 370 |
-
|
| 371 |
-
def __init__(self, encoders, decoders):
|
| 372 |
-
super().__init__()
|
| 373 |
-
assert encoders.keys() == decoders.keys()
|
| 374 |
-
self.keys = list(encoders.keys())
|
| 375 |
-
for key in self.keys:
|
| 376 |
-
check_type(encoders[key], FairseqEncoder)
|
| 377 |
-
check_type(decoders[key], FairseqDecoder)
|
| 378 |
-
|
| 379 |
-
self.models = nn.ModuleDict(
|
| 380 |
-
{
|
| 381 |
-
key: FairseqEncoderDecoderModel(encoders[key], decoders[key])
|
| 382 |
-
for key in self.keys
|
| 383 |
-
}
|
| 384 |
-
)
|
| 385 |
-
|
| 386 |
-
@staticmethod
|
| 387 |
-
def build_shared_embeddings(
|
| 388 |
-
dicts: Dict[str, Dictionary],
|
| 389 |
-
langs: List[str],
|
| 390 |
-
embed_dim: int,
|
| 391 |
-
build_embedding: callable,
|
| 392 |
-
pretrained_embed_path: Optional[str] = None,
|
| 393 |
-
):
|
| 394 |
-
"""
|
| 395 |
-
Helper function to build shared embeddings for a set of languages after
|
| 396 |
-
checking that all dicts corresponding to those languages are equivalent.
|
| 397 |
-
|
| 398 |
-
Args:
|
| 399 |
-
dicts: Dict of lang_id to its corresponding Dictionary
|
| 400 |
-
langs: languages that we want to share embeddings for
|
| 401 |
-
embed_dim: embedding dimension
|
| 402 |
-
build_embedding: callable function to actually build the embedding
|
| 403 |
-
pretrained_embed_path: Optional path to load pretrained embeddings
|
| 404 |
-
"""
|
| 405 |
-
shared_dict = dicts[langs[0]]
|
| 406 |
-
if any(dicts[lang] != shared_dict for lang in langs):
|
| 407 |
-
raise ValueError(
|
| 408 |
-
"--share-*-embeddings requires a joined dictionary: "
|
| 409 |
-
"--share-encoder-embeddings requires a joined source "
|
| 410 |
-
"dictionary, --share-decoder-embeddings requires a joined "
|
| 411 |
-
"target dictionary, and --share-all-embeddings requires a "
|
| 412 |
-
"joint source + target dictionary."
|
| 413 |
-
)
|
| 414 |
-
return build_embedding(shared_dict, embed_dim, pretrained_embed_path)
|
| 415 |
-
|
| 416 |
-
def forward(self, src_tokens, src_lengths, prev_output_tokens, **kwargs):
|
| 417 |
-
raise NotImplementedError
|
| 418 |
-
|
| 419 |
-
def max_positions(self):
|
| 420 |
-
"""Maximum length supported by the model."""
|
| 421 |
-
return {
|
| 422 |
-
key: (
|
| 423 |
-
self.models[key].encoder.max_positions(),
|
| 424 |
-
self.models[key].decoder.max_positions(),
|
| 425 |
-
)
|
| 426 |
-
for key in self.keys
|
| 427 |
-
}
|
| 428 |
-
|
| 429 |
-
def max_decoder_positions(self):
|
| 430 |
-
"""Maximum length supported by the decoder."""
|
| 431 |
-
return min(model.decoder.max_positions() for model in self.models.values())
|
| 432 |
-
|
| 433 |
-
@property
|
| 434 |
-
def encoder(self):
|
| 435 |
-
return self.models[self.keys[0]].encoder
|
| 436 |
-
|
| 437 |
-
@property
|
| 438 |
-
def decoder(self):
|
| 439 |
-
return self.models[self.keys[0]].decoder
|
| 440 |
-
|
| 441 |
-
def forward_decoder(self, prev_output_tokens, **kwargs):
|
| 442 |
-
return self.decoder(prev_output_tokens, **kwargs)
|
| 443 |
-
|
| 444 |
-
def load_state_dict(
|
| 445 |
-
self,
|
| 446 |
-
state_dict,
|
| 447 |
-
strict=True,
|
| 448 |
-
model_cfg=None,
|
| 449 |
-
args: Optional[Namespace] = None,
|
| 450 |
-
):
|
| 451 |
-
"""Copies parameters and buffers from *state_dict* into this module and
|
| 452 |
-
its descendants.
|
| 453 |
-
|
| 454 |
-
Overrides the method in :class:`nn.Module`. Compared with that method
|
| 455 |
-
this additionally "upgrades" *state_dicts* from old checkpoints.
|
| 456 |
-
"""
|
| 457 |
-
|
| 458 |
-
if model_cfg is None and args is not None:
|
| 459 |
-
logger.warn(
|
| 460 |
-
"using 'args' is deprecated, please update your code to use dataclass config"
|
| 461 |
-
)
|
| 462 |
-
model_cfg = convert_namespace_to_omegaconf(args).model
|
| 463 |
-
|
| 464 |
-
self.upgrade_state_dict(state_dict)
|
| 465 |
-
|
| 466 |
-
from fairseq.checkpoint_utils import prune_state_dict
|
| 467 |
-
|
| 468 |
-
new_state_dict = prune_state_dict(state_dict, model_cfg)
|
| 469 |
-
return super().load_state_dict(new_state_dict, strict)
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
class FairseqLanguageModel(BaseFairseqModel):
|
| 473 |
-
"""Base class for decoder-only models.
|
| 474 |
-
|
| 475 |
-
Args:
|
| 476 |
-
decoder (FairseqDecoder): the decoder
|
| 477 |
-
"""
|
| 478 |
-
|
| 479 |
-
def __init__(self, decoder):
|
| 480 |
-
super().__init__()
|
| 481 |
-
self.decoder = decoder
|
| 482 |
-
check_type(self.decoder, FairseqDecoder)
|
| 483 |
-
|
| 484 |
-
def forward(self, src_tokens, **kwargs):
|
| 485 |
-
"""
|
| 486 |
-
Run the forward pass for a decoder-only model.
|
| 487 |
-
|
| 488 |
-
Feeds a batch of tokens through the decoder to predict the next tokens.
|
| 489 |
-
|
| 490 |
-
Args:
|
| 491 |
-
src_tokens (LongTensor): tokens on which to condition the decoder,
|
| 492 |
-
of shape `(batch, tgt_len)`
|
| 493 |
-
src_lengths (LongTensor): source sentence lengths of shape `(batch)`
|
| 494 |
-
|
| 495 |
-
Returns:
|
| 496 |
-
tuple:
|
| 497 |
-
- the decoder's output of shape `(batch, seq_len, vocab)`
|
| 498 |
-
- a dictionary with any model-specific outputs
|
| 499 |
-
"""
|
| 500 |
-
return self.decoder(src_tokens, **kwargs)
|
| 501 |
-
|
| 502 |
-
def forward_decoder(self, prev_output_tokens, **kwargs):
|
| 503 |
-
return self.decoder(prev_output_tokens, **kwargs)
|
| 504 |
-
|
| 505 |
-
def extract_features(self, src_tokens, **kwargs):
|
| 506 |
-
"""
|
| 507 |
-
Similar to *forward* but only return features.
|
| 508 |
-
|
| 509 |
-
Returns:
|
| 510 |
-
tuple:
|
| 511 |
-
- the decoder's features of shape `(batch, seq_len, embed_dim)`
|
| 512 |
-
- a dictionary with any model-specific outputs
|
| 513 |
-
"""
|
| 514 |
-
return self.decoder.extract_features(src_tokens, **kwargs)
|
| 515 |
-
|
| 516 |
-
def output_layer(self, features, **kwargs):
|
| 517 |
-
"""Project features to the default output size (typically vocabulary size)."""
|
| 518 |
-
return self.decoder.output_layer(features, **kwargs)
|
| 519 |
-
|
| 520 |
-
def max_positions(self):
|
| 521 |
-
"""Maximum length supported by the model."""
|
| 522 |
-
return self.decoder.max_positions()
|
| 523 |
-
|
| 524 |
-
def max_decoder_positions(self):
|
| 525 |
-
"""Maximum length supported by the decoder."""
|
| 526 |
-
return self.decoder.max_positions()
|
| 527 |
-
|
| 528 |
-
@property
|
| 529 |
-
def supported_targets(self):
|
| 530 |
-
return {"future"}
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
class FairseqEncoderModel(BaseFairseqModel):
|
| 534 |
-
"""Base class for encoder-only models.
|
| 535 |
-
|
| 536 |
-
Args:
|
| 537 |
-
encoder (FairseqEncoder): the encoder
|
| 538 |
-
"""
|
| 539 |
-
|
| 540 |
-
def __init__(self, encoder):
|
| 541 |
-
super().__init__()
|
| 542 |
-
self.encoder = encoder
|
| 543 |
-
check_type(self.encoder, FairseqEncoder)
|
| 544 |
-
|
| 545 |
-
def forward(self, src_tokens, src_lengths, **kwargs):
|
| 546 |
-
"""
|
| 547 |
-
Run the forward pass for a encoder-only model.
|
| 548 |
-
|
| 549 |
-
Feeds a batch of tokens through the encoder to generate features.
|
| 550 |
-
|
| 551 |
-
Args:
|
| 552 |
-
src_tokens (LongTensor): input tokens of shape `(batch, src_len)`
|
| 553 |
-
src_lengths (LongTensor): source sentence lengths of shape `(batch)`
|
| 554 |
-
|
| 555 |
-
Returns:
|
| 556 |
-
the encoder's output, typically of shape `(batch, src_len, features)`
|
| 557 |
-
"""
|
| 558 |
-
return self.encoder(src_tokens, src_lengths, **kwargs)
|
| 559 |
-
|
| 560 |
-
def get_normalized_probs(self, net_output, log_probs, sample=None):
|
| 561 |
-
"""Get normalized probabilities (or log probs) from a net's output."""
|
| 562 |
-
encoder_out = net_output["encoder_out"]
|
| 563 |
-
if torch.is_tensor(encoder_out):
|
| 564 |
-
logits = encoder_out.float()
|
| 565 |
-
if log_probs:
|
| 566 |
-
return F.log_softmax(logits, dim=-1)
|
| 567 |
-
else:
|
| 568 |
-
return F.softmax(logits, dim=-1)
|
| 569 |
-
raise NotImplementedError
|
| 570 |
-
|
| 571 |
-
def max_positions(self):
|
| 572 |
-
"""Maximum length supported by the model."""
|
| 573 |
-
return self.encoder.max_positions()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/fconv.py
DELETED
|
@@ -1,756 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import math
|
| 7 |
-
|
| 8 |
-
import torch
|
| 9 |
-
import torch.nn as nn
|
| 10 |
-
import torch.nn.functional as F
|
| 11 |
-
from fairseq import utils
|
| 12 |
-
from fairseq.models import (
|
| 13 |
-
FairseqEncoder,
|
| 14 |
-
FairseqEncoderDecoderModel,
|
| 15 |
-
FairseqIncrementalDecoder,
|
| 16 |
-
register_model,
|
| 17 |
-
register_model_architecture,
|
| 18 |
-
)
|
| 19 |
-
from fairseq.modules import (
|
| 20 |
-
AdaptiveSoftmax,
|
| 21 |
-
BeamableMM,
|
| 22 |
-
FairseqDropout,
|
| 23 |
-
GradMultiply,
|
| 24 |
-
LearnedPositionalEmbedding,
|
| 25 |
-
LinearizedConvolution,
|
| 26 |
-
)
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
@register_model("fconv")
|
| 30 |
-
class FConvModel(FairseqEncoderDecoderModel):
|
| 31 |
-
"""
|
| 32 |
-
A fully convolutional model, i.e. a convolutional encoder and a
|
| 33 |
-
convolutional decoder, as described in `"Convolutional Sequence to Sequence
|
| 34 |
-
Learning" (Gehring et al., 2017) <https://arxiv.org/abs/1705.03122>`_.
|
| 35 |
-
|
| 36 |
-
Args:
|
| 37 |
-
encoder (FConvEncoder): the encoder
|
| 38 |
-
decoder (FConvDecoder): the decoder
|
| 39 |
-
|
| 40 |
-
The Convolutional model provides the following named architectures and
|
| 41 |
-
command-line arguments:
|
| 42 |
-
|
| 43 |
-
.. argparse::
|
| 44 |
-
:ref: fairseq.models.fconv_parser
|
| 45 |
-
:prog:
|
| 46 |
-
"""
|
| 47 |
-
|
| 48 |
-
@classmethod
|
| 49 |
-
def hub_models(cls):
|
| 50 |
-
def moses_subword(path):
|
| 51 |
-
return {
|
| 52 |
-
"path": path,
|
| 53 |
-
"tokenizer": "moses",
|
| 54 |
-
"bpe": "subword_nmt",
|
| 55 |
-
}
|
| 56 |
-
|
| 57 |
-
return {
|
| 58 |
-
"conv.wmt14.en-fr": moses_subword(
|
| 59 |
-
"https://dl.fbaipublicfiles.com/fairseq/models/wmt14.v2.en-fr.fconv-py.tar.bz2"
|
| 60 |
-
),
|
| 61 |
-
"conv.wmt14.en-de": moses_subword(
|
| 62 |
-
"https://dl.fbaipublicfiles.com/fairseq/models/wmt14.en-de.fconv-py.tar.bz2"
|
| 63 |
-
),
|
| 64 |
-
"conv.wmt17.en-de": moses_subword(
|
| 65 |
-
"https://dl.fbaipublicfiles.com/fairseq/models/wmt17.v2.en-de.fconv-py.tar.bz2"
|
| 66 |
-
),
|
| 67 |
-
}
|
| 68 |
-
|
| 69 |
-
def __init__(self, encoder, decoder):
|
| 70 |
-
super().__init__(encoder, decoder)
|
| 71 |
-
self.encoder.num_attention_layers = sum(
|
| 72 |
-
layer is not None for layer in decoder.attention
|
| 73 |
-
)
|
| 74 |
-
|
| 75 |
-
@staticmethod
|
| 76 |
-
def add_args(parser):
|
| 77 |
-
"""Add model-specific arguments to the parser."""
|
| 78 |
-
# fmt: off
|
| 79 |
-
parser.add_argument('--dropout', type=float, metavar='D',
|
| 80 |
-
help='dropout probability')
|
| 81 |
-
parser.add_argument('--encoder-embed-dim', type=int, metavar='N',
|
| 82 |
-
help='encoder embedding dimension')
|
| 83 |
-
parser.add_argument('--encoder-embed-path', type=str, metavar='STR',
|
| 84 |
-
help='path to pre-trained encoder embedding')
|
| 85 |
-
parser.add_argument('--encoder-layers', type=str, metavar='EXPR',
|
| 86 |
-
help='encoder layers [(dim, kernel_size), ...]')
|
| 87 |
-
parser.add_argument('--decoder-embed-dim', type=int, metavar='N',
|
| 88 |
-
help='decoder embedding dimension')
|
| 89 |
-
parser.add_argument('--decoder-embed-path', type=str, metavar='STR',
|
| 90 |
-
help='path to pre-trained decoder embedding')
|
| 91 |
-
parser.add_argument('--decoder-layers', type=str, metavar='EXPR',
|
| 92 |
-
help='decoder layers [(dim, kernel_size), ...]')
|
| 93 |
-
parser.add_argument('--decoder-out-embed-dim', type=int, metavar='N',
|
| 94 |
-
help='decoder output embedding dimension')
|
| 95 |
-
parser.add_argument('--decoder-attention', type=str, metavar='EXPR',
|
| 96 |
-
help='decoder attention [True, ...]')
|
| 97 |
-
parser.add_argument('--share-input-output-embed', action='store_true',
|
| 98 |
-
help='share input and output embeddings (requires'
|
| 99 |
-
' --decoder-out-embed-dim and --decoder-embed-dim'
|
| 100 |
-
' to be equal)')
|
| 101 |
-
# fmt: on
|
| 102 |
-
|
| 103 |
-
@classmethod
|
| 104 |
-
def build_model(cls, args, task):
|
| 105 |
-
"""Build a new model instance."""
|
| 106 |
-
# make sure that all args are properly defaulted (in case there are any new ones)
|
| 107 |
-
base_architecture(args)
|
| 108 |
-
|
| 109 |
-
encoder_embed_dict = None
|
| 110 |
-
if args.encoder_embed_path:
|
| 111 |
-
encoder_embed_dict = utils.parse_embedding(args.encoder_embed_path)
|
| 112 |
-
utils.print_embed_overlap(encoder_embed_dict, task.source_dictionary)
|
| 113 |
-
|
| 114 |
-
decoder_embed_dict = None
|
| 115 |
-
if args.decoder_embed_path:
|
| 116 |
-
decoder_embed_dict = utils.parse_embedding(args.decoder_embed_path)
|
| 117 |
-
utils.print_embed_overlap(decoder_embed_dict, task.target_dictionary)
|
| 118 |
-
|
| 119 |
-
encoder = FConvEncoder(
|
| 120 |
-
dictionary=task.source_dictionary,
|
| 121 |
-
embed_dim=args.encoder_embed_dim,
|
| 122 |
-
embed_dict=encoder_embed_dict,
|
| 123 |
-
convolutions=eval(args.encoder_layers),
|
| 124 |
-
dropout=args.dropout,
|
| 125 |
-
max_positions=args.max_source_positions,
|
| 126 |
-
)
|
| 127 |
-
decoder = FConvDecoder(
|
| 128 |
-
dictionary=task.target_dictionary,
|
| 129 |
-
embed_dim=args.decoder_embed_dim,
|
| 130 |
-
embed_dict=decoder_embed_dict,
|
| 131 |
-
convolutions=eval(args.decoder_layers),
|
| 132 |
-
out_embed_dim=args.decoder_out_embed_dim,
|
| 133 |
-
attention=eval(args.decoder_attention),
|
| 134 |
-
dropout=args.dropout,
|
| 135 |
-
max_positions=args.max_target_positions,
|
| 136 |
-
share_embed=args.share_input_output_embed,
|
| 137 |
-
)
|
| 138 |
-
return FConvModel(encoder, decoder)
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
class FConvEncoder(FairseqEncoder):
|
| 142 |
-
"""
|
| 143 |
-
Convolutional encoder consisting of `len(convolutions)` layers.
|
| 144 |
-
|
| 145 |
-
Args:
|
| 146 |
-
dictionary (~fairseq.data.Dictionary): encoding dictionary
|
| 147 |
-
embed_dim (int, optional): embedding dimension
|
| 148 |
-
embed_dict (str, optional): filename from which to load pre-trained
|
| 149 |
-
embeddings
|
| 150 |
-
max_positions (int, optional): maximum supported input sequence length
|
| 151 |
-
convolutions (list, optional): the convolutional layer structure. Each
|
| 152 |
-
list item `i` corresponds to convolutional layer `i`. Layers are
|
| 153 |
-
given as ``(out_channels, kernel_width, [residual])``. Residual
|
| 154 |
-
connections are added between layers when ``residual=1`` (which is
|
| 155 |
-
the default behavior).
|
| 156 |
-
dropout (float, optional): dropout to be applied before each conv layer
|
| 157 |
-
"""
|
| 158 |
-
|
| 159 |
-
def __init__(
|
| 160 |
-
self,
|
| 161 |
-
dictionary,
|
| 162 |
-
embed_dim=512,
|
| 163 |
-
embed_dict=None,
|
| 164 |
-
max_positions=1024,
|
| 165 |
-
convolutions=((512, 3),) * 20,
|
| 166 |
-
dropout=0.1,
|
| 167 |
-
):
|
| 168 |
-
super().__init__(dictionary)
|
| 169 |
-
self.dropout_module = FairseqDropout(
|
| 170 |
-
dropout, module_name=self.__class__.__name__
|
| 171 |
-
)
|
| 172 |
-
self.num_attention_layers = None
|
| 173 |
-
|
| 174 |
-
num_embeddings = len(dictionary)
|
| 175 |
-
self.padding_idx = dictionary.pad()
|
| 176 |
-
self.embed_tokens = Embedding(num_embeddings, embed_dim, self.padding_idx)
|
| 177 |
-
if embed_dict:
|
| 178 |
-
self.embed_tokens = utils.load_embedding(
|
| 179 |
-
embed_dict, self.dictionary, self.embed_tokens
|
| 180 |
-
)
|
| 181 |
-
|
| 182 |
-
self.embed_positions = PositionalEmbedding(
|
| 183 |
-
max_positions,
|
| 184 |
-
embed_dim,
|
| 185 |
-
self.padding_idx,
|
| 186 |
-
)
|
| 187 |
-
|
| 188 |
-
convolutions = extend_conv_spec(convolutions)
|
| 189 |
-
in_channels = convolutions[0][0]
|
| 190 |
-
self.fc1 = Linear(embed_dim, in_channels, dropout=dropout)
|
| 191 |
-
self.projections = nn.ModuleList()
|
| 192 |
-
self.convolutions = nn.ModuleList()
|
| 193 |
-
self.residuals = []
|
| 194 |
-
|
| 195 |
-
layer_in_channels = [in_channels]
|
| 196 |
-
for _, (out_channels, kernel_size, residual) in enumerate(convolutions):
|
| 197 |
-
if residual == 0:
|
| 198 |
-
residual_dim = out_channels
|
| 199 |
-
else:
|
| 200 |
-
residual_dim = layer_in_channels[-residual]
|
| 201 |
-
self.projections.append(
|
| 202 |
-
Linear(residual_dim, out_channels)
|
| 203 |
-
if residual_dim != out_channels
|
| 204 |
-
else None
|
| 205 |
-
)
|
| 206 |
-
if kernel_size % 2 == 1:
|
| 207 |
-
padding = kernel_size // 2
|
| 208 |
-
else:
|
| 209 |
-
padding = 0
|
| 210 |
-
self.convolutions.append(
|
| 211 |
-
ConvTBC(
|
| 212 |
-
in_channels,
|
| 213 |
-
out_channels * 2,
|
| 214 |
-
kernel_size,
|
| 215 |
-
dropout=dropout,
|
| 216 |
-
padding=padding,
|
| 217 |
-
)
|
| 218 |
-
)
|
| 219 |
-
self.residuals.append(residual)
|
| 220 |
-
in_channels = out_channels
|
| 221 |
-
layer_in_channels.append(out_channels)
|
| 222 |
-
self.fc2 = Linear(in_channels, embed_dim)
|
| 223 |
-
|
| 224 |
-
def forward(self, src_tokens, src_lengths):
|
| 225 |
-
"""
|
| 226 |
-
Args:
|
| 227 |
-
src_tokens (LongTensor): tokens in the source language of shape
|
| 228 |
-
`(batch, src_len)`
|
| 229 |
-
src_lengths (LongTensor): lengths of each source sentence of shape
|
| 230 |
-
`(batch)`
|
| 231 |
-
|
| 232 |
-
Returns:
|
| 233 |
-
dict:
|
| 234 |
-
- **encoder_out** (tuple): a tuple with two elements, where the
|
| 235 |
-
first element is the last encoder layer's output and the
|
| 236 |
-
second element is the same quantity summed with the input
|
| 237 |
-
embedding (used for attention). The shape of both tensors is
|
| 238 |
-
`(batch, src_len, embed_dim)`.
|
| 239 |
-
- **encoder_padding_mask** (ByteTensor): the positions of
|
| 240 |
-
padding elements of shape `(batch, src_len)`
|
| 241 |
-
"""
|
| 242 |
-
# embed tokens and positions
|
| 243 |
-
x = self.embed_tokens(src_tokens) + self.embed_positions(src_tokens)
|
| 244 |
-
x = self.dropout_module(x)
|
| 245 |
-
input_embedding = x
|
| 246 |
-
|
| 247 |
-
# project to size of convolution
|
| 248 |
-
x = self.fc1(x)
|
| 249 |
-
|
| 250 |
-
# used to mask padding in input
|
| 251 |
-
encoder_padding_mask = src_tokens.eq(self.padding_idx).t() # -> T x B
|
| 252 |
-
if not encoder_padding_mask.any():
|
| 253 |
-
encoder_padding_mask = None
|
| 254 |
-
|
| 255 |
-
# B x T x C -> T x B x C
|
| 256 |
-
x = x.transpose(0, 1)
|
| 257 |
-
|
| 258 |
-
residuals = [x]
|
| 259 |
-
# temporal convolutions
|
| 260 |
-
for proj, conv, res_layer in zip(
|
| 261 |
-
self.projections, self.convolutions, self.residuals
|
| 262 |
-
):
|
| 263 |
-
if res_layer > 0:
|
| 264 |
-
residual = residuals[-res_layer]
|
| 265 |
-
residual = residual if proj is None else proj(residual)
|
| 266 |
-
else:
|
| 267 |
-
residual = None
|
| 268 |
-
|
| 269 |
-
if encoder_padding_mask is not None:
|
| 270 |
-
x = x.masked_fill(encoder_padding_mask.unsqueeze(-1), 0)
|
| 271 |
-
|
| 272 |
-
x = self.dropout_module(x)
|
| 273 |
-
if conv.kernel_size[0] % 2 == 1:
|
| 274 |
-
# padding is implicit in the conv
|
| 275 |
-
x = conv(x)
|
| 276 |
-
else:
|
| 277 |
-
padding_l = (conv.kernel_size[0] - 1) // 2
|
| 278 |
-
padding_r = conv.kernel_size[0] // 2
|
| 279 |
-
x = F.pad(x, (0, 0, 0, 0, padding_l, padding_r))
|
| 280 |
-
x = conv(x)
|
| 281 |
-
x = F.glu(x, dim=2)
|
| 282 |
-
|
| 283 |
-
if residual is not None:
|
| 284 |
-
x = (x + residual) * math.sqrt(0.5)
|
| 285 |
-
residuals.append(x)
|
| 286 |
-
|
| 287 |
-
# T x B x C -> B x T x C
|
| 288 |
-
x = x.transpose(1, 0)
|
| 289 |
-
|
| 290 |
-
# project back to size of embedding
|
| 291 |
-
x = self.fc2(x)
|
| 292 |
-
|
| 293 |
-
if encoder_padding_mask is not None:
|
| 294 |
-
encoder_padding_mask = encoder_padding_mask.t() # -> B x T
|
| 295 |
-
x = x.masked_fill(encoder_padding_mask.unsqueeze(-1), 0)
|
| 296 |
-
|
| 297 |
-
# scale gradients (this only affects backward, not forward)
|
| 298 |
-
x = GradMultiply.apply(x, 1.0 / (2.0 * self.num_attention_layers))
|
| 299 |
-
|
| 300 |
-
# add output to input embedding for attention
|
| 301 |
-
y = (x + input_embedding) * math.sqrt(0.5)
|
| 302 |
-
|
| 303 |
-
return {
|
| 304 |
-
"encoder_out": (x, y),
|
| 305 |
-
"encoder_padding_mask": encoder_padding_mask, # B x T
|
| 306 |
-
}
|
| 307 |
-
|
| 308 |
-
def reorder_encoder_out(self, encoder_out, new_order):
|
| 309 |
-
if encoder_out["encoder_out"] is not None:
|
| 310 |
-
encoder_out["encoder_out"] = (
|
| 311 |
-
encoder_out["encoder_out"][0].index_select(0, new_order),
|
| 312 |
-
encoder_out["encoder_out"][1].index_select(0, new_order),
|
| 313 |
-
)
|
| 314 |
-
if encoder_out["encoder_padding_mask"] is not None:
|
| 315 |
-
encoder_out["encoder_padding_mask"] = encoder_out[
|
| 316 |
-
"encoder_padding_mask"
|
| 317 |
-
].index_select(0, new_order)
|
| 318 |
-
return encoder_out
|
| 319 |
-
|
| 320 |
-
def max_positions(self):
|
| 321 |
-
"""Maximum input length supported by the encoder."""
|
| 322 |
-
return self.embed_positions.max_positions
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
class AttentionLayer(nn.Module):
|
| 326 |
-
def __init__(self, conv_channels, embed_dim, bmm=None):
|
| 327 |
-
super().__init__()
|
| 328 |
-
# projects from output of convolution to embedding dimension
|
| 329 |
-
self.in_projection = Linear(conv_channels, embed_dim)
|
| 330 |
-
# projects from embedding dimension to convolution size
|
| 331 |
-
self.out_projection = Linear(embed_dim, conv_channels)
|
| 332 |
-
|
| 333 |
-
self.bmm = bmm if bmm is not None else torch.bmm
|
| 334 |
-
|
| 335 |
-
def forward(self, x, target_embedding, encoder_out, encoder_padding_mask):
|
| 336 |
-
residual = x
|
| 337 |
-
|
| 338 |
-
# attention
|
| 339 |
-
x = (self.in_projection(x) + target_embedding) * math.sqrt(0.5)
|
| 340 |
-
x = self.bmm(x, encoder_out[0])
|
| 341 |
-
|
| 342 |
-
# don't attend over padding
|
| 343 |
-
if encoder_padding_mask is not None:
|
| 344 |
-
x = (
|
| 345 |
-
x.float()
|
| 346 |
-
.masked_fill(encoder_padding_mask.unsqueeze(1), float("-inf"))
|
| 347 |
-
.type_as(x)
|
| 348 |
-
) # FP16 support: cast to float and back
|
| 349 |
-
|
| 350 |
-
# softmax over last dim
|
| 351 |
-
sz = x.size()
|
| 352 |
-
x = F.softmax(x.view(sz[0] * sz[1], sz[2]), dim=1)
|
| 353 |
-
x = x.view(sz)
|
| 354 |
-
attn_scores = x
|
| 355 |
-
|
| 356 |
-
x = self.bmm(x, encoder_out[1])
|
| 357 |
-
|
| 358 |
-
# scale attention output (respecting potentially different lengths)
|
| 359 |
-
s = encoder_out[1].size(1)
|
| 360 |
-
if encoder_padding_mask is None:
|
| 361 |
-
x = x * (s * math.sqrt(1.0 / s))
|
| 362 |
-
else:
|
| 363 |
-
s = s - encoder_padding_mask.type_as(x).sum(
|
| 364 |
-
dim=1, keepdim=True
|
| 365 |
-
) # exclude padding
|
| 366 |
-
s = s.unsqueeze(-1)
|
| 367 |
-
x = x * (s * s.rsqrt())
|
| 368 |
-
|
| 369 |
-
# project back
|
| 370 |
-
x = (self.out_projection(x) + residual) * math.sqrt(0.5)
|
| 371 |
-
return x, attn_scores
|
| 372 |
-
|
| 373 |
-
def make_generation_fast_(self, beamable_mm_beam_size=None, **kwargs):
|
| 374 |
-
"""Replace torch.bmm with BeamableMM."""
|
| 375 |
-
if beamable_mm_beam_size is not None:
|
| 376 |
-
del self.bmm
|
| 377 |
-
self.add_module("bmm", BeamableMM(beamable_mm_beam_size))
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
class FConvDecoder(FairseqIncrementalDecoder):
|
| 381 |
-
"""Convolutional decoder"""
|
| 382 |
-
|
| 383 |
-
def __init__(
|
| 384 |
-
self,
|
| 385 |
-
dictionary,
|
| 386 |
-
embed_dim=512,
|
| 387 |
-
embed_dict=None,
|
| 388 |
-
out_embed_dim=256,
|
| 389 |
-
max_positions=1024,
|
| 390 |
-
convolutions=((512, 3),) * 20,
|
| 391 |
-
attention=True,
|
| 392 |
-
dropout=0.1,
|
| 393 |
-
share_embed=False,
|
| 394 |
-
positional_embeddings=True,
|
| 395 |
-
adaptive_softmax_cutoff=None,
|
| 396 |
-
adaptive_softmax_dropout=0.0,
|
| 397 |
-
):
|
| 398 |
-
super().__init__(dictionary)
|
| 399 |
-
self.register_buffer("version", torch.Tensor([2]))
|
| 400 |
-
self.dropout_module = FairseqDropout(
|
| 401 |
-
dropout, module_name=self.__class__.__name__
|
| 402 |
-
)
|
| 403 |
-
self.need_attn = True
|
| 404 |
-
|
| 405 |
-
convolutions = extend_conv_spec(convolutions)
|
| 406 |
-
in_channels = convolutions[0][0]
|
| 407 |
-
if isinstance(attention, bool):
|
| 408 |
-
# expand True into [True, True, ...] and do the same with False
|
| 409 |
-
attention = [attention] * len(convolutions)
|
| 410 |
-
if not isinstance(attention, list) or len(attention) != len(convolutions):
|
| 411 |
-
raise ValueError(
|
| 412 |
-
"Attention is expected to be a list of booleans of "
|
| 413 |
-
"length equal to the number of layers."
|
| 414 |
-
)
|
| 415 |
-
|
| 416 |
-
num_embeddings = len(dictionary)
|
| 417 |
-
padding_idx = dictionary.pad()
|
| 418 |
-
self.embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx)
|
| 419 |
-
if embed_dict:
|
| 420 |
-
self.embed_tokens = utils.load_embedding(
|
| 421 |
-
embed_dict, self.dictionary, self.embed_tokens
|
| 422 |
-
)
|
| 423 |
-
|
| 424 |
-
self.embed_positions = (
|
| 425 |
-
PositionalEmbedding(
|
| 426 |
-
max_positions,
|
| 427 |
-
embed_dim,
|
| 428 |
-
padding_idx,
|
| 429 |
-
)
|
| 430 |
-
if positional_embeddings
|
| 431 |
-
else None
|
| 432 |
-
)
|
| 433 |
-
|
| 434 |
-
self.fc1 = Linear(embed_dim, in_channels, dropout=dropout)
|
| 435 |
-
self.projections = nn.ModuleList()
|
| 436 |
-
self.convolutions = nn.ModuleList()
|
| 437 |
-
self.attention = nn.ModuleList()
|
| 438 |
-
self.residuals = []
|
| 439 |
-
|
| 440 |
-
layer_in_channels = [in_channels]
|
| 441 |
-
for i, (out_channels, kernel_size, residual) in enumerate(convolutions):
|
| 442 |
-
if residual == 0:
|
| 443 |
-
residual_dim = out_channels
|
| 444 |
-
else:
|
| 445 |
-
residual_dim = layer_in_channels[-residual]
|
| 446 |
-
self.projections.append(
|
| 447 |
-
Linear(residual_dim, out_channels)
|
| 448 |
-
if residual_dim != out_channels
|
| 449 |
-
else None
|
| 450 |
-
)
|
| 451 |
-
self.convolutions.append(
|
| 452 |
-
LinearizedConv1d(
|
| 453 |
-
in_channels,
|
| 454 |
-
out_channels * 2,
|
| 455 |
-
kernel_size,
|
| 456 |
-
padding=(kernel_size - 1),
|
| 457 |
-
dropout=dropout,
|
| 458 |
-
)
|
| 459 |
-
)
|
| 460 |
-
self.attention.append(
|
| 461 |
-
AttentionLayer(out_channels, embed_dim) if attention[i] else None
|
| 462 |
-
)
|
| 463 |
-
self.residuals.append(residual)
|
| 464 |
-
in_channels = out_channels
|
| 465 |
-
layer_in_channels.append(out_channels)
|
| 466 |
-
|
| 467 |
-
self.adaptive_softmax = None
|
| 468 |
-
self.fc2 = self.fc3 = None
|
| 469 |
-
|
| 470 |
-
if adaptive_softmax_cutoff is not None:
|
| 471 |
-
assert not share_embed
|
| 472 |
-
self.adaptive_softmax = AdaptiveSoftmax(
|
| 473 |
-
num_embeddings,
|
| 474 |
-
in_channels,
|
| 475 |
-
adaptive_softmax_cutoff,
|
| 476 |
-
dropout=adaptive_softmax_dropout,
|
| 477 |
-
)
|
| 478 |
-
else:
|
| 479 |
-
self.fc2 = Linear(in_channels, out_embed_dim)
|
| 480 |
-
if share_embed:
|
| 481 |
-
assert out_embed_dim == embed_dim, (
|
| 482 |
-
"Shared embed weights implies same dimensions "
|
| 483 |
-
" out_embed_dim={} vs embed_dim={}".format(out_embed_dim, embed_dim)
|
| 484 |
-
)
|
| 485 |
-
self.fc3 = nn.Linear(out_embed_dim, num_embeddings)
|
| 486 |
-
self.fc3.weight = self.embed_tokens.weight
|
| 487 |
-
else:
|
| 488 |
-
self.fc3 = Linear(out_embed_dim, num_embeddings, dropout=dropout)
|
| 489 |
-
|
| 490 |
-
def forward(
|
| 491 |
-
self, prev_output_tokens, encoder_out=None, incremental_state=None, **unused
|
| 492 |
-
):
|
| 493 |
-
if encoder_out is not None:
|
| 494 |
-
encoder_padding_mask = encoder_out["encoder_padding_mask"]
|
| 495 |
-
encoder_out = encoder_out["encoder_out"]
|
| 496 |
-
|
| 497 |
-
# split and transpose encoder outputs
|
| 498 |
-
encoder_a, encoder_b = self._split_encoder_out(
|
| 499 |
-
encoder_out, incremental_state
|
| 500 |
-
)
|
| 501 |
-
|
| 502 |
-
if self.embed_positions is not None:
|
| 503 |
-
pos_embed = self.embed_positions(prev_output_tokens, incremental_state)
|
| 504 |
-
else:
|
| 505 |
-
pos_embed = 0
|
| 506 |
-
|
| 507 |
-
if incremental_state is not None:
|
| 508 |
-
prev_output_tokens = prev_output_tokens[:, -1:]
|
| 509 |
-
x = self._embed_tokens(prev_output_tokens, incremental_state)
|
| 510 |
-
|
| 511 |
-
# embed tokens and combine with positional embeddings
|
| 512 |
-
x += pos_embed
|
| 513 |
-
x = self.dropout_module(x)
|
| 514 |
-
target_embedding = x
|
| 515 |
-
|
| 516 |
-
# project to size of convolution
|
| 517 |
-
x = self.fc1(x)
|
| 518 |
-
|
| 519 |
-
# B x T x C -> T x B x C
|
| 520 |
-
x = self._transpose_if_training(x, incremental_state)
|
| 521 |
-
|
| 522 |
-
# temporal convolutions
|
| 523 |
-
avg_attn_scores = None
|
| 524 |
-
num_attn_layers = len(self.attention)
|
| 525 |
-
residuals = [x]
|
| 526 |
-
for proj, conv, attention, res_layer in zip(
|
| 527 |
-
self.projections, self.convolutions, self.attention, self.residuals
|
| 528 |
-
):
|
| 529 |
-
if res_layer > 0:
|
| 530 |
-
residual = residuals[-res_layer]
|
| 531 |
-
residual = residual if proj is None else proj(residual)
|
| 532 |
-
else:
|
| 533 |
-
residual = None
|
| 534 |
-
|
| 535 |
-
x = self.dropout_module(x)
|
| 536 |
-
x = conv(x, incremental_state)
|
| 537 |
-
x = F.glu(x, dim=2)
|
| 538 |
-
|
| 539 |
-
# attention
|
| 540 |
-
if attention is not None:
|
| 541 |
-
x = self._transpose_if_training(x, incremental_state)
|
| 542 |
-
|
| 543 |
-
x, attn_scores = attention(
|
| 544 |
-
x, target_embedding, (encoder_a, encoder_b), encoder_padding_mask
|
| 545 |
-
)
|
| 546 |
-
|
| 547 |
-
if not self.training and self.need_attn:
|
| 548 |
-
attn_scores = attn_scores / num_attn_layers
|
| 549 |
-
if avg_attn_scores is None:
|
| 550 |
-
avg_attn_scores = attn_scores
|
| 551 |
-
else:
|
| 552 |
-
avg_attn_scores.add_(attn_scores)
|
| 553 |
-
|
| 554 |
-
x = self._transpose_if_training(x, incremental_state)
|
| 555 |
-
|
| 556 |
-
# residual
|
| 557 |
-
if residual is not None:
|
| 558 |
-
x = (x + residual) * math.sqrt(0.5)
|
| 559 |
-
residuals.append(x)
|
| 560 |
-
|
| 561 |
-
# T x B x C -> B x T x C
|
| 562 |
-
x = self._transpose_if_training(x, incremental_state)
|
| 563 |
-
|
| 564 |
-
# project back to size of vocabulary if not using adaptive softmax
|
| 565 |
-
if self.fc2 is not None and self.fc3 is not None:
|
| 566 |
-
x = self.fc2(x)
|
| 567 |
-
x = self.dropout_module(x)
|
| 568 |
-
x = self.fc3(x)
|
| 569 |
-
|
| 570 |
-
return x, avg_attn_scores
|
| 571 |
-
|
| 572 |
-
def reorder_incremental_state(self, incremental_state, new_order):
|
| 573 |
-
super().reorder_incremental_state(incremental_state, new_order)
|
| 574 |
-
encoder_out = utils.get_incremental_state(
|
| 575 |
-
self, incremental_state, "encoder_out"
|
| 576 |
-
)
|
| 577 |
-
if encoder_out is not None:
|
| 578 |
-
encoder_out = tuple(eo.index_select(0, new_order) for eo in encoder_out)
|
| 579 |
-
utils.set_incremental_state(
|
| 580 |
-
self, incremental_state, "encoder_out", encoder_out
|
| 581 |
-
)
|
| 582 |
-
|
| 583 |
-
def max_positions(self):
|
| 584 |
-
"""Maximum output length supported by the decoder."""
|
| 585 |
-
return (
|
| 586 |
-
self.embed_positions.max_positions
|
| 587 |
-
if self.embed_positions is not None
|
| 588 |
-
else float("inf")
|
| 589 |
-
)
|
| 590 |
-
|
| 591 |
-
def upgrade_state_dict(self, state_dict):
|
| 592 |
-
if utils.item(state_dict.get("decoder.version", torch.Tensor([1]))[0]) < 2:
|
| 593 |
-
# old models use incorrect weight norm dimension
|
| 594 |
-
for i, conv in enumerate(self.convolutions):
|
| 595 |
-
# reconfigure weight norm
|
| 596 |
-
nn.utils.remove_weight_norm(conv)
|
| 597 |
-
self.convolutions[i] = nn.utils.weight_norm(conv, dim=0)
|
| 598 |
-
state_dict["decoder.version"] = torch.Tensor([1])
|
| 599 |
-
return state_dict
|
| 600 |
-
|
| 601 |
-
def make_generation_fast_(self, need_attn=False, **kwargs):
|
| 602 |
-
self.need_attn = need_attn
|
| 603 |
-
|
| 604 |
-
def _embed_tokens(self, tokens, incremental_state):
|
| 605 |
-
if incremental_state is not None:
|
| 606 |
-
# keep only the last token for incremental forward pass
|
| 607 |
-
tokens = tokens[:, -1:]
|
| 608 |
-
return self.embed_tokens(tokens)
|
| 609 |
-
|
| 610 |
-
def _split_encoder_out(self, encoder_out, incremental_state):
|
| 611 |
-
"""Split and transpose encoder outputs.
|
| 612 |
-
|
| 613 |
-
This is cached when doing incremental inference.
|
| 614 |
-
"""
|
| 615 |
-
cached_result = utils.get_incremental_state(
|
| 616 |
-
self, incremental_state, "encoder_out"
|
| 617 |
-
)
|
| 618 |
-
if cached_result is not None:
|
| 619 |
-
return cached_result
|
| 620 |
-
|
| 621 |
-
# transpose only once to speed up attention layers
|
| 622 |
-
encoder_a, encoder_b = encoder_out
|
| 623 |
-
encoder_a = encoder_a.transpose(1, 2).contiguous()
|
| 624 |
-
result = (encoder_a, encoder_b)
|
| 625 |
-
|
| 626 |
-
if incremental_state is not None:
|
| 627 |
-
utils.set_incremental_state(self, incremental_state, "encoder_out", result)
|
| 628 |
-
return result
|
| 629 |
-
|
| 630 |
-
def _transpose_if_training(self, x, incremental_state):
|
| 631 |
-
if incremental_state is None:
|
| 632 |
-
x = x.transpose(0, 1)
|
| 633 |
-
return x
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
def extend_conv_spec(convolutions):
|
| 637 |
-
"""
|
| 638 |
-
Extends convolutional spec that is a list of tuples of 2 or 3 parameters
|
| 639 |
-
(kernel size, dim size and optionally how many layers behind to look for residual)
|
| 640 |
-
to default the residual propagation param if it is not specified
|
| 641 |
-
"""
|
| 642 |
-
extended = []
|
| 643 |
-
for spec in convolutions:
|
| 644 |
-
if len(spec) == 3:
|
| 645 |
-
extended.append(spec)
|
| 646 |
-
elif len(spec) == 2:
|
| 647 |
-
extended.append(spec + (1,))
|
| 648 |
-
else:
|
| 649 |
-
raise Exception(
|
| 650 |
-
"invalid number of parameters in convolution spec "
|
| 651 |
-
+ str(spec)
|
| 652 |
-
+ ". expected 2 or 3"
|
| 653 |
-
)
|
| 654 |
-
return tuple(extended)
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
def Embedding(num_embeddings, embedding_dim, padding_idx):
|
| 658 |
-
m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
|
| 659 |
-
nn.init.normal_(m.weight, 0, 0.1)
|
| 660 |
-
nn.init.constant_(m.weight[padding_idx], 0)
|
| 661 |
-
return m
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx):
|
| 665 |
-
m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx)
|
| 666 |
-
nn.init.normal_(m.weight, 0, 0.1)
|
| 667 |
-
nn.init.constant_(m.weight[padding_idx], 0)
|
| 668 |
-
return m
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
def Linear(in_features, out_features, dropout=0.0):
|
| 672 |
-
"""Weight-normalized Linear layer (input: N x T x C)"""
|
| 673 |
-
m = nn.Linear(in_features, out_features)
|
| 674 |
-
nn.init.normal_(m.weight, mean=0, std=math.sqrt((1 - dropout) / in_features))
|
| 675 |
-
nn.init.constant_(m.bias, 0)
|
| 676 |
-
return nn.utils.weight_norm(m)
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
def LinearizedConv1d(in_channels, out_channels, kernel_size, dropout=0.0, **kwargs):
|
| 680 |
-
"""Weight-normalized Conv1d layer optimized for decoding"""
|
| 681 |
-
m = LinearizedConvolution(in_channels, out_channels, kernel_size, **kwargs)
|
| 682 |
-
std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))
|
| 683 |
-
nn.init.normal_(m.weight, mean=0, std=std)
|
| 684 |
-
nn.init.constant_(m.bias, 0)
|
| 685 |
-
return nn.utils.weight_norm(m, dim=2)
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
def ConvTBC(in_channels, out_channels, kernel_size, dropout=0.0, **kwargs):
|
| 689 |
-
"""Weight-normalized Conv1d layer"""
|
| 690 |
-
from fairseq.modules import ConvTBC
|
| 691 |
-
|
| 692 |
-
m = ConvTBC(in_channels, out_channels, kernel_size, **kwargs)
|
| 693 |
-
std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))
|
| 694 |
-
nn.init.normal_(m.weight, mean=0, std=std)
|
| 695 |
-
nn.init.constant_(m.bias, 0)
|
| 696 |
-
return nn.utils.weight_norm(m, dim=2)
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
@register_model_architecture("fconv", "fconv")
|
| 700 |
-
def base_architecture(args):
|
| 701 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 702 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
|
| 703 |
-
args.encoder_embed_path = getattr(args, "encoder_embed_path", None)
|
| 704 |
-
args.encoder_layers = getattr(args, "encoder_layers", "[(512, 3)] * 20")
|
| 705 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 512)
|
| 706 |
-
args.decoder_embed_path = getattr(args, "decoder_embed_path", None)
|
| 707 |
-
args.decoder_layers = getattr(args, "decoder_layers", "[(512, 3)] * 20")
|
| 708 |
-
args.decoder_out_embed_dim = getattr(args, "decoder_out_embed_dim", 256)
|
| 709 |
-
args.decoder_attention = getattr(args, "decoder_attention", "True")
|
| 710 |
-
args.share_input_output_embed = getattr(args, "share_input_output_embed", False)
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
@register_model_architecture("fconv", "fconv_iwslt_de_en")
|
| 714 |
-
def fconv_iwslt_de_en(args):
|
| 715 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 256)
|
| 716 |
-
args.encoder_layers = getattr(args, "encoder_layers", "[(256, 3)] * 4")
|
| 717 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 256)
|
| 718 |
-
args.decoder_layers = getattr(args, "decoder_layers", "[(256, 3)] * 3")
|
| 719 |
-
args.decoder_out_embed_dim = getattr(args, "decoder_out_embed_dim", 256)
|
| 720 |
-
base_architecture(args)
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
@register_model_architecture("fconv", "fconv_wmt_en_ro")
|
| 724 |
-
def fconv_wmt_en_ro(args):
|
| 725 |
-
args.decoder_out_embed_dim = getattr(args, "decoder_out_embed_dim", 512)
|
| 726 |
-
base_architecture(args)
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
@register_model_architecture("fconv", "fconv_wmt_en_de")
|
| 730 |
-
def fconv_wmt_en_de(args):
|
| 731 |
-
convs = "[(512, 3)] * 9" # first 9 layers have 512 units
|
| 732 |
-
convs += " + [(1024, 3)] * 4" # next 4 layers have 1024 units
|
| 733 |
-
convs += " + [(2048, 1)] * 2" # final 2 layers use 1x1 convolutions
|
| 734 |
-
|
| 735 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 768)
|
| 736 |
-
args.encoder_layers = getattr(args, "encoder_layers", convs)
|
| 737 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 768)
|
| 738 |
-
args.decoder_layers = getattr(args, "decoder_layers", convs)
|
| 739 |
-
args.decoder_out_embed_dim = getattr(args, "decoder_out_embed_dim", 512)
|
| 740 |
-
base_architecture(args)
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
@register_model_architecture("fconv", "fconv_wmt_en_fr")
|
| 744 |
-
def fconv_wmt_en_fr(args):
|
| 745 |
-
convs = "[(512, 3)] * 6" # first 6 layers have 512 units
|
| 746 |
-
convs += " + [(768, 3)] * 4" # next 4 layers have 768 units
|
| 747 |
-
convs += " + [(1024, 3)] * 3" # next 3 layers have 1024 units
|
| 748 |
-
convs += " + [(2048, 1)] * 1" # next 1 layer uses 1x1 convolutions
|
| 749 |
-
convs += " + [(4096, 1)] * 1" # final 1 layer uses 1x1 convolutions
|
| 750 |
-
|
| 751 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 768)
|
| 752 |
-
args.encoder_layers = getattr(args, "encoder_layers", convs)
|
| 753 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 768)
|
| 754 |
-
args.decoder_layers = getattr(args, "decoder_layers", convs)
|
| 755 |
-
args.decoder_out_embed_dim = getattr(args, "decoder_out_embed_dim", 512)
|
| 756 |
-
base_architecture(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/fconv_lm.py
DELETED
|
@@ -1,136 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
from fairseq import utils
|
| 7 |
-
from fairseq.models import (
|
| 8 |
-
FairseqLanguageModel,
|
| 9 |
-
register_model,
|
| 10 |
-
register_model_architecture,
|
| 11 |
-
)
|
| 12 |
-
from fairseq.models.fconv import FConvDecoder
|
| 13 |
-
from fairseq.utils import safe_hasattr
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
@register_model("fconv_lm")
|
| 17 |
-
class FConvLanguageModel(FairseqLanguageModel):
|
| 18 |
-
def __init__(self, decoder):
|
| 19 |
-
super().__init__(decoder)
|
| 20 |
-
|
| 21 |
-
@staticmethod
|
| 22 |
-
def add_args(parser):
|
| 23 |
-
"""Add model-specific arguments to the parser."""
|
| 24 |
-
parser.add_argument(
|
| 25 |
-
"--dropout", type=float, metavar="D", help="dropout probability"
|
| 26 |
-
)
|
| 27 |
-
parser.add_argument(
|
| 28 |
-
"--decoder-embed-dim",
|
| 29 |
-
type=int,
|
| 30 |
-
metavar="N",
|
| 31 |
-
help="decoder embedding dimension",
|
| 32 |
-
)
|
| 33 |
-
parser.add_argument(
|
| 34 |
-
"--decoder-layers",
|
| 35 |
-
type=str,
|
| 36 |
-
metavar="EXPR",
|
| 37 |
-
help="decoder layers [(dim, kernel_size), ...]",
|
| 38 |
-
)
|
| 39 |
-
parser.add_argument(
|
| 40 |
-
"--decoder-out-embed-dim",
|
| 41 |
-
type=int,
|
| 42 |
-
metavar="N",
|
| 43 |
-
help="decoder output embedding dimension",
|
| 44 |
-
)
|
| 45 |
-
parser.add_argument(
|
| 46 |
-
"--adaptive-softmax-cutoff",
|
| 47 |
-
metavar="EXPR",
|
| 48 |
-
help="comma separated list of adaptive softmax cutoff points. "
|
| 49 |
-
"Must be used with adaptive_loss criterion",
|
| 50 |
-
)
|
| 51 |
-
parser.add_argument(
|
| 52 |
-
"--adaptive-softmax-dropout",
|
| 53 |
-
type=float,
|
| 54 |
-
metavar="D",
|
| 55 |
-
help="sets adaptive softmax dropout for the tail projections",
|
| 56 |
-
)
|
| 57 |
-
parser.add_argument(
|
| 58 |
-
"--decoder-attention",
|
| 59 |
-
type=str,
|
| 60 |
-
metavar="EXPR",
|
| 61 |
-
help="decoder attention [True, ...]",
|
| 62 |
-
)
|
| 63 |
-
|
| 64 |
-
@classmethod
|
| 65 |
-
def build_model(cls, args, task):
|
| 66 |
-
"""Build a new model instance."""
|
| 67 |
-
# make sure all arguments are present in older models
|
| 68 |
-
base_lm_architecture(args)
|
| 69 |
-
|
| 70 |
-
if safe_hasattr(args, "max_target_positions") and not safe_hasattr(
|
| 71 |
-
args, "tokens_per_sample"
|
| 72 |
-
):
|
| 73 |
-
args.tokens_per_sample = args.max_target_positions
|
| 74 |
-
|
| 75 |
-
decoder = FConvDecoder(
|
| 76 |
-
dictionary=task.target_dictionary,
|
| 77 |
-
embed_dim=args.decoder_embed_dim,
|
| 78 |
-
convolutions=eval(args.decoder_layers),
|
| 79 |
-
out_embed_dim=args.decoder_embed_dim,
|
| 80 |
-
attention=eval(args.decoder_attention),
|
| 81 |
-
dropout=args.dropout,
|
| 82 |
-
max_positions=args.tokens_per_sample,
|
| 83 |
-
share_embed=False,
|
| 84 |
-
positional_embeddings=False,
|
| 85 |
-
adaptive_softmax_cutoff=(
|
| 86 |
-
utils.eval_str_list(args.adaptive_softmax_cutoff, type=int)
|
| 87 |
-
if args.criterion == "adaptive_loss"
|
| 88 |
-
else None
|
| 89 |
-
),
|
| 90 |
-
adaptive_softmax_dropout=args.adaptive_softmax_dropout,
|
| 91 |
-
)
|
| 92 |
-
return FConvLanguageModel(decoder)
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
@register_model_architecture("fconv_lm", "fconv_lm")
|
| 96 |
-
def base_lm_architecture(args):
|
| 97 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 98 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 128)
|
| 99 |
-
args.decoder_layers = getattr(args, "decoder_layers", "[(1268, 4)] * 13")
|
| 100 |
-
args.decoder_attention = getattr(args, "decoder_attention", "False")
|
| 101 |
-
args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
|
| 102 |
-
args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
@register_model_architecture("fconv_lm", "fconv_lm_dauphin_wikitext103")
|
| 106 |
-
def fconv_lm_dauphin_wikitext103(args):
|
| 107 |
-
layers = "[(850, 6)] * 3"
|
| 108 |
-
layers += " + [(850, 1)] * 1"
|
| 109 |
-
layers += " + [(850, 5)] * 4"
|
| 110 |
-
layers += " + [(850, 1)] * 1"
|
| 111 |
-
layers += " + [(850, 4)] * 3"
|
| 112 |
-
layers += " + [(1024, 4)] * 1"
|
| 113 |
-
layers += " + [(2048, 4)] * 1"
|
| 114 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 280)
|
| 115 |
-
args.decoder_layers = getattr(args, "decoder_layers", layers)
|
| 116 |
-
args.decoder_attention = getattr(args, "decoder_attention", "False")
|
| 117 |
-
args.adaptive_softmax_cutoff = getattr(
|
| 118 |
-
args, "adaptive_softmax_cutoff", "10000,20000,200000"
|
| 119 |
-
)
|
| 120 |
-
base_lm_architecture(args)
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
@register_model_architecture("fconv_lm", "fconv_lm_dauphin_gbw")
|
| 124 |
-
def fconv_lm_dauphin_gbw(args):
|
| 125 |
-
layers = "[(512, 5)]"
|
| 126 |
-
layers += " + [(128, 1, 0), (128, 5, 0), (512, 1, 3)] * 3"
|
| 127 |
-
layers += " + [(512, 1, 0), (512, 5, 0), (1024, 1, 3)] * 3"
|
| 128 |
-
layers += " + [(1024, 1, 0), (1024, 5, 0), (2048, 1, 3)] * 6"
|
| 129 |
-
layers += " + [(1024, 1, 0), (1024, 5, 0), (4096, 1, 3)]"
|
| 130 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 128)
|
| 131 |
-
args.decoder_layers = getattr(args, "decoder_layers", layers)
|
| 132 |
-
args.decoder_attention = getattr(args, "decoder_attention", "False")
|
| 133 |
-
args.adaptive_softmax_cutoff = getattr(
|
| 134 |
-
args, "adaptive_softmax_cutoff", "10000,50000,200000"
|
| 135 |
-
)
|
| 136 |
-
base_lm_architecture(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/fconv_self_att.py
DELETED
|
@@ -1,673 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import logging
|
| 7 |
-
import math
|
| 8 |
-
import os
|
| 9 |
-
|
| 10 |
-
import torch
|
| 11 |
-
import torch.nn as nn
|
| 12 |
-
import torch.nn.functional as F
|
| 13 |
-
from fairseq import checkpoint_utils
|
| 14 |
-
from fairseq.incremental_decoding_utils import with_incremental_state
|
| 15 |
-
from fairseq.models import (
|
| 16 |
-
CompositeEncoder,
|
| 17 |
-
FairseqDecoder,
|
| 18 |
-
FairseqEncoder,
|
| 19 |
-
FairseqEncoderDecoderModel,
|
| 20 |
-
register_model,
|
| 21 |
-
register_model_architecture,
|
| 22 |
-
)
|
| 23 |
-
from fairseq.modules import (
|
| 24 |
-
DownsampledMultiHeadAttention,
|
| 25 |
-
FairseqDropout,
|
| 26 |
-
GradMultiply,
|
| 27 |
-
LayerNorm,
|
| 28 |
-
LearnedPositionalEmbedding,
|
| 29 |
-
LinearizedConvolution,
|
| 30 |
-
)
|
| 31 |
-
|
| 32 |
-
logger = logging.getLogger(__name__)
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
@register_model("fconv_self_att")
|
| 36 |
-
class FConvModelSelfAtt(FairseqEncoderDecoderModel):
|
| 37 |
-
@classmethod
|
| 38 |
-
def hub_models(cls):
|
| 39 |
-
return {
|
| 40 |
-
"conv.stories.pretrained": {
|
| 41 |
-
"path": "https://dl.fbaipublicfiles.com/fairseq/models/stories_checkpoint.tar.gz",
|
| 42 |
-
"checkpoint_file": "pretrained_checkpoint.pt",
|
| 43 |
-
"tokenizer": "nltk",
|
| 44 |
-
},
|
| 45 |
-
"conv.stories": {
|
| 46 |
-
"path": "https://dl.fbaipublicfiles.com/fairseq/models/stories_checkpoint.tar.gz",
|
| 47 |
-
"checkpoint_file": "fusion_checkpoint.pt",
|
| 48 |
-
"tokenizer": "nltk",
|
| 49 |
-
"pretrained": "True",
|
| 50 |
-
"pretrained_checkpoint": "./pretrained_checkpoint.pt",
|
| 51 |
-
},
|
| 52 |
-
# Test set containing dictionaries
|
| 53 |
-
"data.stories": "https://dl.fbaipublicfiles.com/fairseq/data/stories_test.tar.bz2",
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
def __init__(self, encoder, decoder, pretrained_encoder=None):
|
| 57 |
-
super().__init__(encoder, decoder)
|
| 58 |
-
self.encoder.num_attention_layers = sum(
|
| 59 |
-
layer is not None for layer in decoder.attention
|
| 60 |
-
)
|
| 61 |
-
self.pretrained_encoder = pretrained_encoder
|
| 62 |
-
if self.pretrained_encoder is None:
|
| 63 |
-
encoders = {"encoder": encoder}
|
| 64 |
-
else:
|
| 65 |
-
encoders = {"encoder": encoder, "pretrained": self.pretrained_encoder}
|
| 66 |
-
# for fusion model, CompositeEncoder contains both pretrained and training encoders
|
| 67 |
-
# these are forwarded and then combined in the decoder
|
| 68 |
-
self.encoder = CompositeEncoder(encoders)
|
| 69 |
-
|
| 70 |
-
@staticmethod
|
| 71 |
-
def add_args(parser):
|
| 72 |
-
"""Add model-specific arguments to the parser."""
|
| 73 |
-
# fmt: off
|
| 74 |
-
parser.add_argument('--dropout', type=float, metavar='D',
|
| 75 |
-
help='dropout probability')
|
| 76 |
-
parser.add_argument('--encoder-embed-dim', type=int, metavar='N',
|
| 77 |
-
help='encoder embedding dimension')
|
| 78 |
-
parser.add_argument('--encoder-layers', type=str, metavar='EXPR',
|
| 79 |
-
help='encoder layers [(dim, kernel_size), ...]')
|
| 80 |
-
parser.add_argument('--decoder-embed-dim', type=int, metavar='N',
|
| 81 |
-
help='decoder embedding dimension')
|
| 82 |
-
parser.add_argument('--decoder-layers', type=str, metavar='EXPR',
|
| 83 |
-
help='decoder layers [(dim, kernel_size), ...]')
|
| 84 |
-
parser.add_argument('--decoder-out-embed-dim', type=int, metavar='N',
|
| 85 |
-
help='decoder output embedding dimension')
|
| 86 |
-
parser.add_argument('--decoder-attention', type=str, metavar='EXPR',
|
| 87 |
-
help='decoder attention [True, ...]')
|
| 88 |
-
parser.add_argument('--self-attention', type=str, metavar='EXPR',
|
| 89 |
-
help='decoder self-attention layers, ex: [True] + [False]*5')
|
| 90 |
-
parser.add_argument('--multihead-attention-nheads', type=int,
|
| 91 |
-
help='Number of heads to use in attention')
|
| 92 |
-
parser.add_argument('--multihead-self-attention-nheads', type=int,
|
| 93 |
-
help='Number of heads to use in self-attention')
|
| 94 |
-
parser.add_argument('--encoder-attention', type=str, metavar='EXPR',
|
| 95 |
-
help='encoder attention [True, ...]')
|
| 96 |
-
parser.add_argument('--encoder-attention-nheads', type=int,
|
| 97 |
-
help='Number of heads to use in encoder attention')
|
| 98 |
-
parser.add_argument('--project-input', type=str, metavar='EXPR',
|
| 99 |
-
help='Use projections in self-attention [True, ...]')
|
| 100 |
-
parser.add_argument('--gated-attention', type=str, metavar='EXPR',
|
| 101 |
-
help='Use GLU layers in self-attention projections [True, ...]')
|
| 102 |
-
parser.add_argument('--downsample', type=str, metavar='EXPR',
|
| 103 |
-
help='Use downsampling in self-attention [True, ...]')
|
| 104 |
-
parser.add_argument('--pretrained-checkpoint', metavar='DIR',
|
| 105 |
-
help='path to load checkpoint from pretrained model')
|
| 106 |
-
parser.add_argument('--pretrained', type=str, metavar='EXPR',
|
| 107 |
-
help='use pretrained model when training [True, ...]')
|
| 108 |
-
# fmt: on
|
| 109 |
-
|
| 110 |
-
@classmethod
|
| 111 |
-
def build_model(cls, args, task):
|
| 112 |
-
"""Build a new model instance."""
|
| 113 |
-
trained_encoder, trained_decoder = None, None
|
| 114 |
-
pretrained = eval(args.pretrained)
|
| 115 |
-
if pretrained:
|
| 116 |
-
logger.info("loading pretrained model")
|
| 117 |
-
if not os.path.exists(args.pretrained_checkpoint):
|
| 118 |
-
new_pretrained_checkpoint = os.path.join(
|
| 119 |
-
args.data, args.pretrained_checkpoint
|
| 120 |
-
)
|
| 121 |
-
if os.path.exists(new_pretrained_checkpoint):
|
| 122 |
-
args.pretrained_checkpoint = new_pretrained_checkpoint
|
| 123 |
-
trained_model = checkpoint_utils.load_model_ensemble(
|
| 124 |
-
filenames=[args.pretrained_checkpoint],
|
| 125 |
-
task=task,
|
| 126 |
-
)[0][0]
|
| 127 |
-
trained_decoder = list(trained_model.children())[1]
|
| 128 |
-
trained_encoder = list(trained_model.children())[0]
|
| 129 |
-
|
| 130 |
-
# freeze pretrained model
|
| 131 |
-
for param in trained_decoder.parameters():
|
| 132 |
-
param.requires_grad = False
|
| 133 |
-
for param in trained_encoder.parameters():
|
| 134 |
-
param.requires_grad = False
|
| 135 |
-
|
| 136 |
-
encoder = FConvEncoder(
|
| 137 |
-
task.source_dictionary,
|
| 138 |
-
embed_dim=args.encoder_embed_dim,
|
| 139 |
-
convolutions=eval(args.encoder_layers),
|
| 140 |
-
dropout=args.dropout,
|
| 141 |
-
max_positions=args.max_source_positions,
|
| 142 |
-
attention=eval(args.encoder_attention),
|
| 143 |
-
attention_nheads=args.encoder_attention_nheads,
|
| 144 |
-
)
|
| 145 |
-
|
| 146 |
-
decoder = FConvDecoder(
|
| 147 |
-
task.target_dictionary,
|
| 148 |
-
embed_dim=args.decoder_embed_dim,
|
| 149 |
-
convolutions=eval(args.decoder_layers),
|
| 150 |
-
out_embed_dim=args.decoder_out_embed_dim,
|
| 151 |
-
attention=eval(args.decoder_attention),
|
| 152 |
-
dropout=args.dropout,
|
| 153 |
-
max_positions=args.max_target_positions,
|
| 154 |
-
selfattention=eval(args.self_attention),
|
| 155 |
-
attention_nheads=args.multihead_attention_nheads,
|
| 156 |
-
selfattention_nheads=args.multihead_self_attention_nheads,
|
| 157 |
-
project_input=eval(args.project_input),
|
| 158 |
-
gated_attention=eval(args.gated_attention),
|
| 159 |
-
downsample=eval(args.downsample),
|
| 160 |
-
pretrained=pretrained,
|
| 161 |
-
trained_decoder=trained_decoder,
|
| 162 |
-
)
|
| 163 |
-
model = FConvModelSelfAtt(encoder, decoder, trained_encoder)
|
| 164 |
-
|
| 165 |
-
return model
|
| 166 |
-
|
| 167 |
-
@property
|
| 168 |
-
def pretrained(self):
|
| 169 |
-
return self.pretrained_encoder is not None
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
class FConvEncoder(FairseqEncoder):
|
| 173 |
-
"""Convolutional encoder"""
|
| 174 |
-
|
| 175 |
-
def __init__(
|
| 176 |
-
self,
|
| 177 |
-
dictionary,
|
| 178 |
-
embed_dim=512,
|
| 179 |
-
max_positions=1024,
|
| 180 |
-
convolutions=((512, 3),) * 20,
|
| 181 |
-
dropout=0.1,
|
| 182 |
-
attention=False,
|
| 183 |
-
attention_nheads=1,
|
| 184 |
-
):
|
| 185 |
-
super().__init__(dictionary)
|
| 186 |
-
self.dropout_module = FairseqDropout(
|
| 187 |
-
dropout, module_name=self.__class__.__name__
|
| 188 |
-
)
|
| 189 |
-
self.num_attention_layers = None
|
| 190 |
-
|
| 191 |
-
num_embeddings = len(dictionary)
|
| 192 |
-
self.padding_idx = dictionary.pad()
|
| 193 |
-
self.embed_tokens = Embedding(num_embeddings, embed_dim, self.padding_idx)
|
| 194 |
-
self.embed_positions = PositionalEmbedding(
|
| 195 |
-
max_positions,
|
| 196 |
-
embed_dim,
|
| 197 |
-
self.padding_idx,
|
| 198 |
-
)
|
| 199 |
-
|
| 200 |
-
def expand_bool_array(val):
|
| 201 |
-
if isinstance(val, bool):
|
| 202 |
-
# expand True into [True, True, ...] and do the same with False
|
| 203 |
-
return [val] * len(convolutions)
|
| 204 |
-
return val
|
| 205 |
-
|
| 206 |
-
attention = expand_bool_array(attention)
|
| 207 |
-
|
| 208 |
-
in_channels = convolutions[0][0]
|
| 209 |
-
self.fc1 = Linear(embed_dim, in_channels, dropout=dropout)
|
| 210 |
-
self.projections = nn.ModuleList()
|
| 211 |
-
self.convolutions = nn.ModuleList()
|
| 212 |
-
self.attention = nn.ModuleList()
|
| 213 |
-
self.attproj = nn.ModuleList()
|
| 214 |
-
for i, (out_channels, kernel_size) in enumerate(convolutions):
|
| 215 |
-
self.projections.append(
|
| 216 |
-
Linear(in_channels, out_channels)
|
| 217 |
-
if in_channels != out_channels
|
| 218 |
-
else None
|
| 219 |
-
)
|
| 220 |
-
self.convolutions.append(
|
| 221 |
-
ConvTBC(in_channels, out_channels * 2, kernel_size, dropout=dropout)
|
| 222 |
-
)
|
| 223 |
-
|
| 224 |
-
self.attention.append(
|
| 225 |
-
SelfAttention(out_channels, embed_dim, attention_nheads)
|
| 226 |
-
if attention[i]
|
| 227 |
-
else None
|
| 228 |
-
)
|
| 229 |
-
in_channels = out_channels
|
| 230 |
-
|
| 231 |
-
self.fc2 = Linear(in_channels, embed_dim)
|
| 232 |
-
|
| 233 |
-
def forward(self, src_tokens, src_lengths):
|
| 234 |
-
# embed tokens and positions
|
| 235 |
-
x = self.embed_tokens(src_tokens) + self.embed_positions(src_tokens)
|
| 236 |
-
x = self.dropout_module(x)
|
| 237 |
-
input_embedding = x.transpose(0, 1)
|
| 238 |
-
|
| 239 |
-
# project to size of convolution
|
| 240 |
-
x = self.fc1(x)
|
| 241 |
-
|
| 242 |
-
encoder_padding_mask = src_tokens.eq(self.padding_idx).t() # -> T x B
|
| 243 |
-
if not encoder_padding_mask.any():
|
| 244 |
-
encoder_padding_mask = None
|
| 245 |
-
|
| 246 |
-
# B x T x C -> T x B x C
|
| 247 |
-
x = x.transpose(0, 1)
|
| 248 |
-
|
| 249 |
-
# temporal convolutions
|
| 250 |
-
for proj, conv, attention in zip(
|
| 251 |
-
self.projections, self.convolutions, self.attention
|
| 252 |
-
):
|
| 253 |
-
residual = x if proj is None else proj(x)
|
| 254 |
-
|
| 255 |
-
if encoder_padding_mask is not None:
|
| 256 |
-
x = x.masked_fill(encoder_padding_mask.unsqueeze(-1), 0)
|
| 257 |
-
|
| 258 |
-
x = self.dropout_module(x)
|
| 259 |
-
padding_l = (conv.kernel_size[0] - 1) // 2
|
| 260 |
-
padding_r = conv.kernel_size[0] // 2
|
| 261 |
-
x = F.pad(x, (0, 0, 0, 0, padding_l, padding_r))
|
| 262 |
-
x = conv(x)
|
| 263 |
-
x = F.glu(x, dim=2)
|
| 264 |
-
if attention is not None:
|
| 265 |
-
x = attention(x)
|
| 266 |
-
x = (x + residual) * math.sqrt(0.5)
|
| 267 |
-
|
| 268 |
-
# T x B x C -> B x T x C
|
| 269 |
-
x = x.transpose(1, 0)
|
| 270 |
-
|
| 271 |
-
# project back to size of embedding
|
| 272 |
-
x = self.fc2(x)
|
| 273 |
-
|
| 274 |
-
if encoder_padding_mask is not None:
|
| 275 |
-
encoder_padding_mask = encoder_padding_mask.t() # -> B x T
|
| 276 |
-
x = x.masked_fill(encoder_padding_mask.unsqueeze(-1), 0)
|
| 277 |
-
|
| 278 |
-
# scale gradients (this only affects backward, not forward)
|
| 279 |
-
x = GradMultiply.apply(x, 1.0 / (2.0 * self.num_attention_layers))
|
| 280 |
-
|
| 281 |
-
# add output to input embedding for attention
|
| 282 |
-
y = (x + input_embedding.transpose(0, 1)) * math.sqrt(0.5)
|
| 283 |
-
|
| 284 |
-
return {
|
| 285 |
-
"encoder_out": (x, y),
|
| 286 |
-
"encoder_padding_mask": encoder_padding_mask, # B x T
|
| 287 |
-
}
|
| 288 |
-
|
| 289 |
-
def reorder_encoder_out(self, encoder_out, new_order):
|
| 290 |
-
encoder_out["encoder_out"] = tuple(
|
| 291 |
-
eo.index_select(0, new_order) for eo in encoder_out["encoder_out"]
|
| 292 |
-
)
|
| 293 |
-
|
| 294 |
-
if encoder_out["encoder_padding_mask"] is not None:
|
| 295 |
-
encoder_out["encoder_padding_mask"] = encoder_out[
|
| 296 |
-
"encoder_padding_mask"
|
| 297 |
-
].index_select(0, new_order)
|
| 298 |
-
|
| 299 |
-
if "pretrained" in encoder_out:
|
| 300 |
-
encoder_out["pretrained"]["encoder_out"] = tuple(
|
| 301 |
-
eo.index_select(0, new_order)
|
| 302 |
-
for eo in encoder_out["pretrained"]["encoder_out"]
|
| 303 |
-
)
|
| 304 |
-
|
| 305 |
-
return encoder_out
|
| 306 |
-
|
| 307 |
-
def max_positions(self):
|
| 308 |
-
"""Maximum input length supported by the encoder."""
|
| 309 |
-
return self.embed_positions.max_positions
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
@with_incremental_state
|
| 313 |
-
class FConvDecoder(FairseqDecoder):
|
| 314 |
-
"""Convolutional decoder"""
|
| 315 |
-
|
| 316 |
-
def __init__(
|
| 317 |
-
self,
|
| 318 |
-
dictionary,
|
| 319 |
-
embed_dim=512,
|
| 320 |
-
out_embed_dim=256,
|
| 321 |
-
max_positions=1024,
|
| 322 |
-
convolutions=((512, 3),) * 8,
|
| 323 |
-
attention=True,
|
| 324 |
-
dropout=0.1,
|
| 325 |
-
selfattention=False,
|
| 326 |
-
attention_nheads=1,
|
| 327 |
-
selfattention_nheads=1,
|
| 328 |
-
project_input=False,
|
| 329 |
-
gated_attention=False,
|
| 330 |
-
downsample=False,
|
| 331 |
-
pretrained=False,
|
| 332 |
-
trained_decoder=None,
|
| 333 |
-
):
|
| 334 |
-
super().__init__(dictionary)
|
| 335 |
-
self.register_buffer("version", torch.Tensor([2]))
|
| 336 |
-
self.pretrained = pretrained
|
| 337 |
-
self.pretrained_decoder = trained_decoder
|
| 338 |
-
self.dropout_module = FairseqDropout(
|
| 339 |
-
dropout, module_name=self.__class__.__name__
|
| 340 |
-
)
|
| 341 |
-
self.need_attn = True
|
| 342 |
-
in_channels = convolutions[0][0]
|
| 343 |
-
|
| 344 |
-
def expand_bool_array(val):
|
| 345 |
-
if isinstance(val, bool):
|
| 346 |
-
# expand True into [True, True, ...] and do the same with False
|
| 347 |
-
return [val] * len(convolutions)
|
| 348 |
-
return val
|
| 349 |
-
|
| 350 |
-
attention = expand_bool_array(attention)
|
| 351 |
-
selfattention = expand_bool_array(selfattention)
|
| 352 |
-
|
| 353 |
-
if not isinstance(attention, list) or len(attention) != len(convolutions):
|
| 354 |
-
raise ValueError(
|
| 355 |
-
"Attention is expected to be a list of booleans of "
|
| 356 |
-
"length equal to the number of layers."
|
| 357 |
-
)
|
| 358 |
-
|
| 359 |
-
num_embeddings = len(dictionary)
|
| 360 |
-
padding_idx = dictionary.pad()
|
| 361 |
-
self.embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx)
|
| 362 |
-
|
| 363 |
-
self.embed_positions = PositionalEmbedding(
|
| 364 |
-
max_positions,
|
| 365 |
-
embed_dim,
|
| 366 |
-
padding_idx,
|
| 367 |
-
)
|
| 368 |
-
|
| 369 |
-
self.fc1 = Linear(embed_dim, in_channels, dropout=dropout)
|
| 370 |
-
self.projections = nn.ModuleList()
|
| 371 |
-
self.convolutions = nn.ModuleList()
|
| 372 |
-
self.attention = nn.ModuleList()
|
| 373 |
-
self.selfattention = nn.ModuleList()
|
| 374 |
-
self.attproj = nn.ModuleList()
|
| 375 |
-
for i, (out_channels, kernel_size) in enumerate(convolutions):
|
| 376 |
-
self.projections.append(
|
| 377 |
-
Linear(in_channels, out_channels)
|
| 378 |
-
if in_channels != out_channels
|
| 379 |
-
else None
|
| 380 |
-
)
|
| 381 |
-
self.convolutions.append(
|
| 382 |
-
LinearizedConv1d(
|
| 383 |
-
in_channels,
|
| 384 |
-
out_channels * 2,
|
| 385 |
-
kernel_size,
|
| 386 |
-
padding=(kernel_size - 1),
|
| 387 |
-
dropout=dropout,
|
| 388 |
-
)
|
| 389 |
-
)
|
| 390 |
-
|
| 391 |
-
self.attention.append(
|
| 392 |
-
DownsampledMultiHeadAttention(
|
| 393 |
-
out_channels,
|
| 394 |
-
embed_dim,
|
| 395 |
-
attention_nheads,
|
| 396 |
-
project_input=project_input,
|
| 397 |
-
gated=False,
|
| 398 |
-
downsample=False,
|
| 399 |
-
)
|
| 400 |
-
if attention[i]
|
| 401 |
-
else None
|
| 402 |
-
)
|
| 403 |
-
|
| 404 |
-
self.attproj.append(
|
| 405 |
-
Linear(out_channels, embed_dim, dropout=dropout)
|
| 406 |
-
if attention[i]
|
| 407 |
-
else None
|
| 408 |
-
)
|
| 409 |
-
self.selfattention.append(
|
| 410 |
-
SelfAttention(
|
| 411 |
-
out_channels,
|
| 412 |
-
embed_dim,
|
| 413 |
-
selfattention_nheads,
|
| 414 |
-
project_input=project_input,
|
| 415 |
-
gated=gated_attention,
|
| 416 |
-
downsample=downsample,
|
| 417 |
-
)
|
| 418 |
-
if selfattention[i]
|
| 419 |
-
else None
|
| 420 |
-
)
|
| 421 |
-
in_channels = out_channels
|
| 422 |
-
|
| 423 |
-
self.fc2 = Linear(in_channels, out_embed_dim)
|
| 424 |
-
self.fc3 = Linear(out_embed_dim, num_embeddings, dropout=dropout)
|
| 425 |
-
|
| 426 |
-
# model fusion
|
| 427 |
-
if self.pretrained:
|
| 428 |
-
# independent gates are learned from the concatenated input
|
| 429 |
-
self.gate1 = nn.Sequential(
|
| 430 |
-
Linear(out_embed_dim * 2, out_embed_dim), nn.Sigmoid()
|
| 431 |
-
)
|
| 432 |
-
self.gate2 = nn.Sequential(
|
| 433 |
-
Linear(out_embed_dim * 2, out_embed_dim), nn.Sigmoid()
|
| 434 |
-
)
|
| 435 |
-
# pretrained and trained models are joined
|
| 436 |
-
self.joining = nn.Sequential(
|
| 437 |
-
Linear(out_embed_dim * 2, out_embed_dim * 2),
|
| 438 |
-
LayerNorm(out_embed_dim * 2),
|
| 439 |
-
nn.GLU(),
|
| 440 |
-
Linear(out_embed_dim, out_embed_dim * 2),
|
| 441 |
-
LayerNorm(out_embed_dim * 2),
|
| 442 |
-
nn.GLU(),
|
| 443 |
-
Linear(out_embed_dim, out_embed_dim),
|
| 444 |
-
LayerNorm(out_embed_dim),
|
| 445 |
-
)
|
| 446 |
-
# pretrained model contains an output layer that is nhid -> vocab size
|
| 447 |
-
# but the models are combined in their hidden state
|
| 448 |
-
# the hook stores the output of the pretrained model forward
|
| 449 |
-
self.pretrained_outputs = {}
|
| 450 |
-
|
| 451 |
-
def save_output():
|
| 452 |
-
def hook(a, b, output):
|
| 453 |
-
self.pretrained_outputs["out"] = output
|
| 454 |
-
|
| 455 |
-
return hook
|
| 456 |
-
|
| 457 |
-
self.pretrained_decoder.fc2.register_forward_hook(save_output())
|
| 458 |
-
|
| 459 |
-
def forward(self, prev_output_tokens, encoder_out):
|
| 460 |
-
trained_encoder_out = encoder_out["pretrained"] if self.pretrained else None
|
| 461 |
-
encoder_out = encoder_out["encoder"]["encoder_out"]
|
| 462 |
-
|
| 463 |
-
encoder_a, encoder_b = self._split_encoder_out(encoder_out)
|
| 464 |
-
|
| 465 |
-
# embed positions
|
| 466 |
-
positions = self.embed_positions(prev_output_tokens)
|
| 467 |
-
|
| 468 |
-
# embed tokens and positions
|
| 469 |
-
x = self.embed_tokens(prev_output_tokens) + positions
|
| 470 |
-
x = self.dropout_module(x)
|
| 471 |
-
target_embedding = x.transpose(0, 1)
|
| 472 |
-
|
| 473 |
-
# project to size of convolution
|
| 474 |
-
x = self.fc1(x)
|
| 475 |
-
|
| 476 |
-
# B x T x C -> T x B x C
|
| 477 |
-
x = x.transpose(0, 1)
|
| 478 |
-
|
| 479 |
-
# temporal convolutions
|
| 480 |
-
avg_attn_scores = None
|
| 481 |
-
for proj, conv, attention, selfattention, attproj in zip(
|
| 482 |
-
self.projections,
|
| 483 |
-
self.convolutions,
|
| 484 |
-
self.attention,
|
| 485 |
-
self.selfattention,
|
| 486 |
-
self.attproj,
|
| 487 |
-
):
|
| 488 |
-
residual = x if proj is None else proj(x)
|
| 489 |
-
|
| 490 |
-
x = self.dropout_module(x)
|
| 491 |
-
x = conv(x)
|
| 492 |
-
x = F.glu(x, dim=2)
|
| 493 |
-
|
| 494 |
-
# attention
|
| 495 |
-
if attention is not None:
|
| 496 |
-
r = x
|
| 497 |
-
x, attn_scores = attention(
|
| 498 |
-
attproj(x) + target_embedding, encoder_a, encoder_b
|
| 499 |
-
)
|
| 500 |
-
x = x + r
|
| 501 |
-
if not self.training and self.need_attn:
|
| 502 |
-
if avg_attn_scores is None:
|
| 503 |
-
avg_attn_scores = attn_scores
|
| 504 |
-
else:
|
| 505 |
-
avg_attn_scores.add_(attn_scores)
|
| 506 |
-
|
| 507 |
-
if selfattention is not None:
|
| 508 |
-
x = selfattention(x)
|
| 509 |
-
|
| 510 |
-
x = (x + residual) * math.sqrt(0.5)
|
| 511 |
-
|
| 512 |
-
# T x B x C -> B x T x C
|
| 513 |
-
x = x.transpose(0, 1)
|
| 514 |
-
|
| 515 |
-
# project back to size of vocabulary
|
| 516 |
-
x = self.fc2(x)
|
| 517 |
-
x = self.dropout_module(x)
|
| 518 |
-
if not self.pretrained:
|
| 519 |
-
x = self.fc3(x)
|
| 520 |
-
|
| 521 |
-
# fusion gating
|
| 522 |
-
if self.pretrained:
|
| 523 |
-
trained_x, _ = self.pretrained_decoder.forward(
|
| 524 |
-
prev_output_tokens, trained_encoder_out
|
| 525 |
-
)
|
| 526 |
-
y = torch.cat([x, self.pretrained_outputs["out"]], dim=-1)
|
| 527 |
-
gate1 = self.gate1(y)
|
| 528 |
-
gate2 = self.gate2(y)
|
| 529 |
-
gated_x1 = gate1 * x
|
| 530 |
-
gated_x2 = gate2 * self.pretrained_outputs["out"]
|
| 531 |
-
fusion = torch.cat([gated_x1, gated_x2], dim=-1)
|
| 532 |
-
fusion = self.joining(fusion)
|
| 533 |
-
fusion_output = self.fc3(fusion)
|
| 534 |
-
return fusion_output, avg_attn_scores
|
| 535 |
-
else:
|
| 536 |
-
return x, avg_attn_scores
|
| 537 |
-
|
| 538 |
-
def max_positions(self):
|
| 539 |
-
"""Maximum output length supported by the decoder."""
|
| 540 |
-
return self.embed_positions.max_positions
|
| 541 |
-
|
| 542 |
-
def make_generation_fast_(self, need_attn=False, **kwargs):
|
| 543 |
-
self.need_attn = need_attn
|
| 544 |
-
|
| 545 |
-
def _split_encoder_out(self, encoder_out):
|
| 546 |
-
"""Split and transpose encoder outputs."""
|
| 547 |
-
# transpose only once to speed up attention layers
|
| 548 |
-
encoder_a, encoder_b = encoder_out
|
| 549 |
-
encoder_a = encoder_a.transpose(0, 1).contiguous()
|
| 550 |
-
encoder_b = encoder_b.transpose(0, 1).contiguous()
|
| 551 |
-
result = (encoder_a, encoder_b)
|
| 552 |
-
return result
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
class SelfAttention(nn.Module):
|
| 556 |
-
def __init__(
|
| 557 |
-
self,
|
| 558 |
-
out_channels,
|
| 559 |
-
embed_dim,
|
| 560 |
-
num_heads,
|
| 561 |
-
project_input=False,
|
| 562 |
-
gated=False,
|
| 563 |
-
downsample=False,
|
| 564 |
-
):
|
| 565 |
-
super().__init__()
|
| 566 |
-
self.attention = DownsampledMultiHeadAttention(
|
| 567 |
-
out_channels,
|
| 568 |
-
embed_dim,
|
| 569 |
-
num_heads,
|
| 570 |
-
dropout=0,
|
| 571 |
-
bias=True,
|
| 572 |
-
project_input=project_input,
|
| 573 |
-
gated=gated,
|
| 574 |
-
downsample=downsample,
|
| 575 |
-
)
|
| 576 |
-
self.in_proj_q = Linear(out_channels, embed_dim)
|
| 577 |
-
self.in_proj_k = Linear(out_channels, embed_dim)
|
| 578 |
-
self.in_proj_v = Linear(out_channels, embed_dim)
|
| 579 |
-
self.ln = LayerNorm(out_channels)
|
| 580 |
-
|
| 581 |
-
def forward(self, x):
|
| 582 |
-
residual = x
|
| 583 |
-
query = self.in_proj_q(x)
|
| 584 |
-
key = self.in_proj_k(x)
|
| 585 |
-
value = self.in_proj_v(x)
|
| 586 |
-
x, _ = self.attention(
|
| 587 |
-
query, key, value, mask_future_timesteps=True, use_scalar_bias=True
|
| 588 |
-
)
|
| 589 |
-
return self.ln(x + residual)
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
def Embedding(num_embeddings, embedding_dim, padding_idx):
|
| 593 |
-
m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
|
| 594 |
-
m.weight.data.normal_(0, 0.1)
|
| 595 |
-
return m
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx):
|
| 599 |
-
m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx)
|
| 600 |
-
m.weight.data.normal_(0, 0.1)
|
| 601 |
-
return m
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
def Linear(in_features, out_features, dropout=0.0):
|
| 605 |
-
"""Weight-normalized Linear layer (input: N x T x C)"""
|
| 606 |
-
m = nn.Linear(in_features, out_features)
|
| 607 |
-
m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features))
|
| 608 |
-
m.bias.data.zero_()
|
| 609 |
-
return m
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
def LinearizedConv1d(in_channels, out_channels, kernel_size, dropout=0.0, **kwargs):
|
| 613 |
-
"""Weight-normalized Conv1d layer optimized for decoding"""
|
| 614 |
-
m = LinearizedConvolution(in_channels, out_channels, kernel_size, **kwargs)
|
| 615 |
-
std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))
|
| 616 |
-
m.weight.data.normal_(mean=0, std=std)
|
| 617 |
-
m.bias.data.zero_()
|
| 618 |
-
return m
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
def ConvTBC(in_channels, out_channels, kernel_size, dropout=0.0, **kwargs):
|
| 622 |
-
"""Weight-normalized Conv1d layer"""
|
| 623 |
-
from fairseq.modules import ConvTBC
|
| 624 |
-
|
| 625 |
-
m = ConvTBC(in_channels, out_channels, kernel_size, **kwargs)
|
| 626 |
-
std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))
|
| 627 |
-
m.weight.data.normal_(mean=0, std=std)
|
| 628 |
-
m.bias.data.zero_()
|
| 629 |
-
return m
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
@register_model_architecture("fconv_self_att", "fconv_self_att")
|
| 633 |
-
def base_architecture(args):
|
| 634 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 635 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
|
| 636 |
-
args.encoder_layers = getattr(args, "encoder_layers", "[(512, 3)] * 3")
|
| 637 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 512)
|
| 638 |
-
args.decoder_layers = getattr(args, "decoder_layers", "[(512, 3)] * 8")
|
| 639 |
-
args.decoder_out_embed_dim = getattr(args, "decoder_out_embed_dim", 256)
|
| 640 |
-
args.decoder_attention = getattr(args, "decoder_attention", "True")
|
| 641 |
-
args.self_attention = getattr(args, "self_attention", "False")
|
| 642 |
-
args.encoder_attention = getattr(args, "encoder_attention", "False")
|
| 643 |
-
args.multihead_attention_nheads = getattr(args, "multihead_attention_nheads", 1)
|
| 644 |
-
args.multihead_self_attention_nheads = getattr(
|
| 645 |
-
args, "multihead_self_attention_nheads", 1
|
| 646 |
-
)
|
| 647 |
-
args.encoder_attention_nheads = getattr(args, "encoder_attention_nheads", 1)
|
| 648 |
-
args.project_input = getattr(args, "project_input", "False")
|
| 649 |
-
args.gated_attention = getattr(args, "gated_attention", "False")
|
| 650 |
-
args.downsample = getattr(args, "downsample", "False")
|
| 651 |
-
args.pretrained_checkpoint = getattr(args, "pretrained_checkpoint", "")
|
| 652 |
-
args.pretrained = getattr(args, "pretrained", "False")
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
@register_model_architecture("fconv_self_att", "fconv_self_att_wp")
|
| 656 |
-
def fconv_self_att_wp(args):
|
| 657 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 256)
|
| 658 |
-
args.encoder_layers = getattr(
|
| 659 |
-
args, "encoder_layers", "[(128, 3)] * 2 + [(512,3)] * 1"
|
| 660 |
-
)
|
| 661 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 256)
|
| 662 |
-
args.decoder_layers = getattr(
|
| 663 |
-
args, "decoder_layers", "[(512, 4)] * 4 + [(768, 4)] * 2 + [(1024, 4)] * 1"
|
| 664 |
-
)
|
| 665 |
-
args.decoder_out_embed_dim = getattr(args, "decoder_out_embed_dim", 256)
|
| 666 |
-
args.self_attention = getattr(args, "self_attention", "True")
|
| 667 |
-
args.multihead_self_attention_nheads = getattr(
|
| 668 |
-
args, "multihead_self_attention_nheads", 4
|
| 669 |
-
)
|
| 670 |
-
args.project_input = getattr(args, "project_input", "True")
|
| 671 |
-
args.gated_attention = getattr(args, "gated_attention", "True")
|
| 672 |
-
args.downsample = getattr(args, "downsample", "True")
|
| 673 |
-
base_architecture(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/hubert/__init__.py
DELETED
|
@@ -1,7 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
from .hubert import * # noqa
|
| 7 |
-
from .hubert_asr import * # noqa
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/hubert/hubert.py
DELETED
|
@@ -1,571 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import logging
|
| 7 |
-
from dataclasses import dataclass, field
|
| 8 |
-
from typing import Dict, List, Optional, Tuple
|
| 9 |
-
|
| 10 |
-
import numpy as np
|
| 11 |
-
import torch
|
| 12 |
-
import torch.nn as nn
|
| 13 |
-
from fairseq import utils
|
| 14 |
-
from fairseq.data.data_utils import compute_mask_indices
|
| 15 |
-
from fairseq.data.dictionary import Dictionary
|
| 16 |
-
from fairseq.dataclass import ChoiceEnum, FairseqDataclass
|
| 17 |
-
from fairseq.models import BaseFairseqModel, register_model
|
| 18 |
-
from fairseq.models.wav2vec.wav2vec2 import (
|
| 19 |
-
EXTRACTOR_MODE_CHOICES,
|
| 20 |
-
LAYER_TYPE_CHOICES,
|
| 21 |
-
MASKING_DISTRIBUTION_CHOICES,
|
| 22 |
-
ConvFeatureExtractionModel,
|
| 23 |
-
TransformerEncoder,
|
| 24 |
-
)
|
| 25 |
-
from fairseq.modules import GradMultiply, LayerNorm
|
| 26 |
-
from fairseq.tasks.hubert_pretraining import (
|
| 27 |
-
HubertPretrainingConfig,
|
| 28 |
-
HubertPretrainingTask,
|
| 29 |
-
)
|
| 30 |
-
from omegaconf import II
|
| 31 |
-
|
| 32 |
-
logger = logging.getLogger(__name__)
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
@dataclass
|
| 36 |
-
class HubertConfig(FairseqDataclass):
|
| 37 |
-
label_rate: float = II("task.label_rate")
|
| 38 |
-
|
| 39 |
-
extractor_mode: EXTRACTOR_MODE_CHOICES = field(
|
| 40 |
-
default="default",
|
| 41 |
-
metadata={
|
| 42 |
-
"help": "mode for feature extractor. default has a single group "
|
| 43 |
-
"norm with d groups in the first conv block, whereas layer_norm "
|
| 44 |
-
"has layer norms in every block (meant to use with normalize=True)"
|
| 45 |
-
},
|
| 46 |
-
)
|
| 47 |
-
encoder_layers: int = field(
|
| 48 |
-
default=12, metadata={"help": "num encoder layers in the transformer"}
|
| 49 |
-
)
|
| 50 |
-
encoder_embed_dim: int = field(
|
| 51 |
-
default=768, metadata={"help": "encoder embedding dimension"}
|
| 52 |
-
)
|
| 53 |
-
encoder_ffn_embed_dim: int = field(
|
| 54 |
-
default=3072, metadata={"help": "encoder embedding dimension for FFN"}
|
| 55 |
-
)
|
| 56 |
-
encoder_attention_heads: int = field(
|
| 57 |
-
default=12, metadata={"help": "num encoder attention heads"}
|
| 58 |
-
)
|
| 59 |
-
activation_fn: ChoiceEnum(utils.get_available_activation_fns()) = field(
|
| 60 |
-
default="gelu", metadata={"help": "activation function to use"}
|
| 61 |
-
)
|
| 62 |
-
layer_type: LAYER_TYPE_CHOICES = field(
|
| 63 |
-
default="transformer", metadata={"help": "layer type in encoder"}
|
| 64 |
-
)
|
| 65 |
-
|
| 66 |
-
# dropouts
|
| 67 |
-
dropout: float = field(
|
| 68 |
-
default=0.1,
|
| 69 |
-
metadata={"help": "dropout probability for the transformer"},
|
| 70 |
-
)
|
| 71 |
-
attention_dropout: float = field(
|
| 72 |
-
default=0.1,
|
| 73 |
-
metadata={"help": "dropout probability for attention weights"},
|
| 74 |
-
)
|
| 75 |
-
activation_dropout: float = field(
|
| 76 |
-
default=0.0,
|
| 77 |
-
metadata={"help": "dropout probability after activation in FFN"},
|
| 78 |
-
)
|
| 79 |
-
encoder_layerdrop: float = field(
|
| 80 |
-
default=0.0,
|
| 81 |
-
metadata={"help": "probability of dropping a tarnsformer layer"},
|
| 82 |
-
)
|
| 83 |
-
dropout_input: float = field(
|
| 84 |
-
default=0.0,
|
| 85 |
-
metadata={"help": "dropout to apply to the input (after feat extr)"},
|
| 86 |
-
)
|
| 87 |
-
dropout_features: float = field(
|
| 88 |
-
default=0.0,
|
| 89 |
-
metadata={"help": "dropout to apply to the features (after feat extr)"},
|
| 90 |
-
)
|
| 91 |
-
|
| 92 |
-
final_dim: int = field(
|
| 93 |
-
default=0,
|
| 94 |
-
metadata={
|
| 95 |
-
"help": "project final representations and targets to this many "
|
| 96 |
-
"dimensions. set to encoder_embed_dim is <= 0"
|
| 97 |
-
},
|
| 98 |
-
)
|
| 99 |
-
untie_final_proj: bool = field(
|
| 100 |
-
default=False,
|
| 101 |
-
metadata={"help": "use separate projection for each target"},
|
| 102 |
-
)
|
| 103 |
-
layer_norm_first: bool = field(
|
| 104 |
-
default=False,
|
| 105 |
-
metadata={"help": "apply layernorm first in the transformer"},
|
| 106 |
-
)
|
| 107 |
-
conv_feature_layers: str = field(
|
| 108 |
-
default="[(512,10,5)] + [(512,3,2)] * 4 + [(512,2,2)] * 2",
|
| 109 |
-
metadata={
|
| 110 |
-
"help": "string describing convolutional feature extraction "
|
| 111 |
-
"layers in form of a python list that contains "
|
| 112 |
-
"[(dim, kernel_size, stride), ...]"
|
| 113 |
-
},
|
| 114 |
-
)
|
| 115 |
-
conv_bias: bool = field(
|
| 116 |
-
default=False, metadata={"help": "include bias in conv encoder"}
|
| 117 |
-
)
|
| 118 |
-
logit_temp: float = field(
|
| 119 |
-
default=0.1, metadata={"help": "temperature to divide logits by"}
|
| 120 |
-
)
|
| 121 |
-
target_glu: bool = field(
|
| 122 |
-
default=False, metadata={"help": "adds projection + glu to targets"}
|
| 123 |
-
)
|
| 124 |
-
feature_grad_mult: float = field(
|
| 125 |
-
default=1.0,
|
| 126 |
-
metadata={"help": "multiply feature extractor var grads by this"},
|
| 127 |
-
)
|
| 128 |
-
|
| 129 |
-
# masking
|
| 130 |
-
mask_length: int = field(default=10, metadata={"help": "mask length"})
|
| 131 |
-
mask_prob: float = field(
|
| 132 |
-
default=0.65,
|
| 133 |
-
metadata={"help": "probability of replacing a token with mask"},
|
| 134 |
-
)
|
| 135 |
-
mask_selection: MASKING_DISTRIBUTION_CHOICES = field(
|
| 136 |
-
default="static", metadata={"help": "how to choose mask length"}
|
| 137 |
-
)
|
| 138 |
-
mask_other: float = field(
|
| 139 |
-
default=0,
|
| 140 |
-
metadata={
|
| 141 |
-
"help": "secondary mask argument "
|
| 142 |
-
"(used for more complex distributions), "
|
| 143 |
-
"see help in compute_mask_indicesh"
|
| 144 |
-
},
|
| 145 |
-
)
|
| 146 |
-
no_mask_overlap: bool = field(
|
| 147 |
-
default=False, metadata={"help": "whether to allow masks to overlap"}
|
| 148 |
-
)
|
| 149 |
-
mask_min_space: int = field(
|
| 150 |
-
default=1,
|
| 151 |
-
metadata={"help": "min space between spans (if no overlap is enabled)"},
|
| 152 |
-
)
|
| 153 |
-
|
| 154 |
-
# channel masking
|
| 155 |
-
mask_channel_length: int = field(
|
| 156 |
-
default=10,
|
| 157 |
-
metadata={"help": "length of the mask for features (channels)"},
|
| 158 |
-
)
|
| 159 |
-
mask_channel_prob: float = field(
|
| 160 |
-
default=0.0,
|
| 161 |
-
metadata={"help": "probability of replacing a feature with 0"},
|
| 162 |
-
)
|
| 163 |
-
mask_channel_selection: MASKING_DISTRIBUTION_CHOICES = field(
|
| 164 |
-
default="static",
|
| 165 |
-
metadata={"help": "how to choose mask length for channel masking"},
|
| 166 |
-
)
|
| 167 |
-
mask_channel_other: float = field(
|
| 168 |
-
default=0,
|
| 169 |
-
metadata={
|
| 170 |
-
"help": "secondary mask argument "
|
| 171 |
-
"(used for more complex distributions), "
|
| 172 |
-
"see help in compute_mask_indicesh"
|
| 173 |
-
},
|
| 174 |
-
)
|
| 175 |
-
no_mask_channel_overlap: bool = field(
|
| 176 |
-
default=False,
|
| 177 |
-
metadata={"help": "whether to allow channel masks to overlap"},
|
| 178 |
-
)
|
| 179 |
-
mask_channel_min_space: int = field(
|
| 180 |
-
default=1,
|
| 181 |
-
metadata={"help": "min space between spans (if no overlap is enabled)"},
|
| 182 |
-
)
|
| 183 |
-
|
| 184 |
-
# positional embeddings
|
| 185 |
-
conv_pos: int = field(
|
| 186 |
-
default=128,
|
| 187 |
-
metadata={"help": "number of filters for convolutional positional embeddings"},
|
| 188 |
-
)
|
| 189 |
-
conv_pos_groups: int = field(
|
| 190 |
-
default=16,
|
| 191 |
-
metadata={"help": "number of groups for convolutional positional embedding"},
|
| 192 |
-
)
|
| 193 |
-
|
| 194 |
-
latent_temp: Tuple[float, float, float] = field(
|
| 195 |
-
default=(2, 0.5, 0.999995),
|
| 196 |
-
metadata={"help": "legacy (to be removed)"},
|
| 197 |
-
)
|
| 198 |
-
|
| 199 |
-
# loss computation
|
| 200 |
-
skip_masked: bool = field(
|
| 201 |
-
default=False,
|
| 202 |
-
metadata={"help": "skip computing losses over masked frames"},
|
| 203 |
-
)
|
| 204 |
-
skip_nomask: bool = field(
|
| 205 |
-
default=False,
|
| 206 |
-
metadata={"help": "skip computing losses over unmasked frames"},
|
| 207 |
-
)
|
| 208 |
-
|
| 209 |
-
checkpoint_activations: bool = field(
|
| 210 |
-
default=False,
|
| 211 |
-
metadata={"help": "recompute activations and save memory for extra compute"},
|
| 212 |
-
)
|
| 213 |
-
|
| 214 |
-
# FP16 optimization
|
| 215 |
-
required_seq_len_multiple: int = field(
|
| 216 |
-
default=2,
|
| 217 |
-
metadata={
|
| 218 |
-
"help": "pad the input to encoder such that the sequence length is divisible by multiple"
|
| 219 |
-
},
|
| 220 |
-
)
|
| 221 |
-
|
| 222 |
-
# Conformer
|
| 223 |
-
depthwise_conv_kernel_size: int = field(
|
| 224 |
-
default=31,
|
| 225 |
-
metadata={
|
| 226 |
-
"help": "depthwise-conv-kernel-size for convolution in conformer layer"
|
| 227 |
-
},
|
| 228 |
-
)
|
| 229 |
-
attn_type: str = field(
|
| 230 |
-
default="",
|
| 231 |
-
metadata={"help": "if espnet use ESPNET MHA"},
|
| 232 |
-
)
|
| 233 |
-
pos_enc_type: str = field(
|
| 234 |
-
default="abs",
|
| 235 |
-
metadata={"help": "Positional encoding type to use in conformer"},
|
| 236 |
-
)
|
| 237 |
-
fp16: bool = field(default=False, metadata={"help": "If fp16 is being used"})
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
@register_model("hubert", dataclass=HubertConfig)
|
| 241 |
-
class HubertModel(BaseFairseqModel):
|
| 242 |
-
def __init__(
|
| 243 |
-
self,
|
| 244 |
-
cfg: HubertConfig,
|
| 245 |
-
task_cfg: HubertPretrainingConfig,
|
| 246 |
-
dictionaries: List[Dictionary],
|
| 247 |
-
) -> None:
|
| 248 |
-
super().__init__()
|
| 249 |
-
logger.info(f"HubertModel Config: {cfg}")
|
| 250 |
-
|
| 251 |
-
feature_enc_layers = eval(cfg.conv_feature_layers) # noqa
|
| 252 |
-
self.embed = feature_enc_layers[-1][0]
|
| 253 |
-
|
| 254 |
-
self.feature_extractor = ConvFeatureExtractionModel(
|
| 255 |
-
conv_layers=feature_enc_layers,
|
| 256 |
-
dropout=0.0,
|
| 257 |
-
mode=cfg.extractor_mode,
|
| 258 |
-
conv_bias=cfg.conv_bias,
|
| 259 |
-
)
|
| 260 |
-
feature_ds_rate = np.prod([s for _, _, s in feature_enc_layers])
|
| 261 |
-
self.feat2tar_ratio = cfg.label_rate * feature_ds_rate / task_cfg.sample_rate
|
| 262 |
-
|
| 263 |
-
self.post_extract_proj = (
|
| 264 |
-
nn.Linear(self.embed, cfg.encoder_embed_dim)
|
| 265 |
-
if self.embed != cfg.encoder_embed_dim
|
| 266 |
-
else None
|
| 267 |
-
)
|
| 268 |
-
|
| 269 |
-
self.mask_prob = cfg.mask_prob
|
| 270 |
-
self.mask_selection = cfg.mask_selection
|
| 271 |
-
self.mask_other = cfg.mask_other
|
| 272 |
-
self.mask_length = cfg.mask_length
|
| 273 |
-
self.no_mask_overlap = cfg.no_mask_overlap
|
| 274 |
-
self.mask_min_space = cfg.mask_min_space
|
| 275 |
-
|
| 276 |
-
self.mask_channel_prob = cfg.mask_channel_prob
|
| 277 |
-
self.mask_channel_selection = cfg.mask_channel_selection
|
| 278 |
-
self.mask_channel_other = cfg.mask_channel_other
|
| 279 |
-
self.mask_channel_length = cfg.mask_channel_length
|
| 280 |
-
self.no_mask_channel_overlap = cfg.no_mask_channel_overlap
|
| 281 |
-
self.mask_channel_min_space = cfg.mask_channel_min_space
|
| 282 |
-
|
| 283 |
-
self.dropout_input = nn.Dropout(cfg.dropout_input)
|
| 284 |
-
self.dropout_features = nn.Dropout(cfg.dropout_features)
|
| 285 |
-
|
| 286 |
-
self.feature_grad_mult = cfg.feature_grad_mult
|
| 287 |
-
self.logit_temp = cfg.logit_temp
|
| 288 |
-
self.skip_masked = cfg.skip_masked
|
| 289 |
-
self.skip_nomask = cfg.skip_nomask
|
| 290 |
-
|
| 291 |
-
final_dim = cfg.final_dim if cfg.final_dim > 0 else cfg.encoder_embed_dim
|
| 292 |
-
|
| 293 |
-
self.mask_emb = nn.Parameter(
|
| 294 |
-
torch.FloatTensor(cfg.encoder_embed_dim).uniform_()
|
| 295 |
-
)
|
| 296 |
-
|
| 297 |
-
self.encoder = TransformerEncoder(cfg)
|
| 298 |
-
self.layer_norm = LayerNorm(self.embed)
|
| 299 |
-
|
| 300 |
-
self.target_glu = None
|
| 301 |
-
if cfg.target_glu:
|
| 302 |
-
self.target_glu = nn.Sequential(
|
| 303 |
-
nn.Linear(final_dim, final_dim * 2), nn.GLU()
|
| 304 |
-
)
|
| 305 |
-
|
| 306 |
-
self.untie_final_proj = cfg.untie_final_proj
|
| 307 |
-
if self.untie_final_proj:
|
| 308 |
-
self.final_proj = nn.Linear(
|
| 309 |
-
cfg.encoder_embed_dim, final_dim * len(dictionaries)
|
| 310 |
-
)
|
| 311 |
-
else:
|
| 312 |
-
self.final_proj = nn.Linear(cfg.encoder_embed_dim, final_dim)
|
| 313 |
-
|
| 314 |
-
# modules below are not needed during fine-tuning
|
| 315 |
-
if any([d is None for d in dictionaries]):
|
| 316 |
-
logger.info("cannot find dictionary. assume will be used for fine-tuning")
|
| 317 |
-
else:
|
| 318 |
-
self.num_classes = [len(d) for d in dictionaries]
|
| 319 |
-
self.label_embs_concat = nn.Parameter(
|
| 320 |
-
torch.FloatTensor(sum(self.num_classes), final_dim)
|
| 321 |
-
)
|
| 322 |
-
nn.init.uniform_(self.label_embs_concat)
|
| 323 |
-
|
| 324 |
-
def upgrade_state_dict_named(self, state_dict, name):
|
| 325 |
-
"""Upgrade a (possibly old) state dict for new versions of fairseq."""
|
| 326 |
-
|
| 327 |
-
super().upgrade_state_dict_named(state_dict, name)
|
| 328 |
-
return state_dict
|
| 329 |
-
|
| 330 |
-
@classmethod
|
| 331 |
-
def build_model(cls, cfg: HubertConfig, task: HubertPretrainingTask):
|
| 332 |
-
"""Build a new model instance."""
|
| 333 |
-
|
| 334 |
-
model = HubertModel(cfg, task.cfg, task.dictionaries)
|
| 335 |
-
return model
|
| 336 |
-
|
| 337 |
-
def apply_mask(self, x, padding_mask, target_list):
|
| 338 |
-
B, T, C = x.shape
|
| 339 |
-
if self.mask_prob > 0:
|
| 340 |
-
mask_indices = compute_mask_indices(
|
| 341 |
-
(B, T),
|
| 342 |
-
padding_mask,
|
| 343 |
-
self.mask_prob,
|
| 344 |
-
self.mask_length,
|
| 345 |
-
self.mask_selection,
|
| 346 |
-
self.mask_other,
|
| 347 |
-
min_masks=2,
|
| 348 |
-
no_overlap=self.no_mask_overlap,
|
| 349 |
-
min_space=self.mask_min_space,
|
| 350 |
-
)
|
| 351 |
-
mask_indices = torch.from_numpy(mask_indices).to(x.device)
|
| 352 |
-
x[mask_indices] = self.mask_emb
|
| 353 |
-
else:
|
| 354 |
-
mask_indices = None
|
| 355 |
-
|
| 356 |
-
if self.mask_channel_prob > 0:
|
| 357 |
-
mask_channel_indices = compute_mask_indices(
|
| 358 |
-
(B, C),
|
| 359 |
-
None,
|
| 360 |
-
self.mask_channel_prob,
|
| 361 |
-
self.mask_channel_length,
|
| 362 |
-
self.mask_channel_selection,
|
| 363 |
-
self.mask_channel_other,
|
| 364 |
-
no_overlap=self.no_mask_channel_overlap,
|
| 365 |
-
min_space=self.mask_channel_min_space,
|
| 366 |
-
)
|
| 367 |
-
mask_channel_indices = (
|
| 368 |
-
torch.from_numpy(mask_channel_indices)
|
| 369 |
-
.to(x.device)
|
| 370 |
-
.unsqueeze(1)
|
| 371 |
-
.expand(-1, T, -1)
|
| 372 |
-
)
|
| 373 |
-
x[mask_channel_indices] = 0
|
| 374 |
-
|
| 375 |
-
return x, mask_indices
|
| 376 |
-
|
| 377 |
-
def compute_nce(self, x, pos, negs):
|
| 378 |
-
neg_is_pos = (pos == negs).all(-1)
|
| 379 |
-
pos = pos.unsqueeze(0)
|
| 380 |
-
targets = torch.cat([pos, negs], dim=0)
|
| 381 |
-
|
| 382 |
-
logits = torch.cosine_similarity(x.float(), targets.float(), dim=-1).type_as(x)
|
| 383 |
-
logits /= self.logit_temp
|
| 384 |
-
if neg_is_pos.any():
|
| 385 |
-
logits[1:][neg_is_pos] = float("-inf")
|
| 386 |
-
logits = logits.transpose(0, 1) # (num_x, num_cls+1)
|
| 387 |
-
return logits
|
| 388 |
-
|
| 389 |
-
def forward_features(self, source: torch.Tensor) -> torch.Tensor:
|
| 390 |
-
if self.feature_grad_mult > 0:
|
| 391 |
-
features = self.feature_extractor(source)
|
| 392 |
-
if self.feature_grad_mult != 1.0:
|
| 393 |
-
features = GradMultiply.apply(features, self.feature_grad_mult)
|
| 394 |
-
else:
|
| 395 |
-
with torch.no_grad():
|
| 396 |
-
features = self.feature_extractor(source)
|
| 397 |
-
return features
|
| 398 |
-
|
| 399 |
-
def forward_targets(
|
| 400 |
-
self,
|
| 401 |
-
features: torch.Tensor,
|
| 402 |
-
target_list: List[torch.Tensor],
|
| 403 |
-
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 404 |
-
# Trim features to ensure labels exist and then get aligned labels
|
| 405 |
-
feat_tsz = features.size(2)
|
| 406 |
-
targ_tsz = min([t.size(1) for t in target_list])
|
| 407 |
-
if self.feat2tar_ratio * feat_tsz > targ_tsz:
|
| 408 |
-
feat_tsz = int(targ_tsz / self.feat2tar_ratio)
|
| 409 |
-
features = features[..., :feat_tsz]
|
| 410 |
-
target_inds = torch.arange(feat_tsz).float() * self.feat2tar_ratio
|
| 411 |
-
target_list = [t[:, target_inds.long()] for t in target_list]
|
| 412 |
-
return features, target_list
|
| 413 |
-
|
| 414 |
-
def forward_padding_mask(
|
| 415 |
-
self,
|
| 416 |
-
features: torch.Tensor,
|
| 417 |
-
padding_mask: torch.Tensor,
|
| 418 |
-
) -> torch.Tensor:
|
| 419 |
-
extra = padding_mask.size(1) % features.size(1)
|
| 420 |
-
if extra > 0:
|
| 421 |
-
padding_mask = padding_mask[:, :-extra]
|
| 422 |
-
padding_mask = padding_mask.view(padding_mask.size(0), features.size(1), -1)
|
| 423 |
-
padding_mask = padding_mask.all(-1)
|
| 424 |
-
return padding_mask
|
| 425 |
-
|
| 426 |
-
def forward(
|
| 427 |
-
self,
|
| 428 |
-
source: torch.Tensor,
|
| 429 |
-
target_list: Optional[List[torch.Tensor]] = None,
|
| 430 |
-
padding_mask: Optional[torch.Tensor] = None,
|
| 431 |
-
mask: bool = True,
|
| 432 |
-
features_only: bool = False,
|
| 433 |
-
output_layer: Optional[int] = None,
|
| 434 |
-
) -> Dict[str, torch.Tensor]:
|
| 435 |
-
"""output layer is 1-based"""
|
| 436 |
-
features = self.forward_features(source)
|
| 437 |
-
if target_list is not None:
|
| 438 |
-
features, target_list = self.forward_targets(features, target_list)
|
| 439 |
-
|
| 440 |
-
features_pen = features.float().pow(2).mean()
|
| 441 |
-
|
| 442 |
-
features = features.transpose(1, 2)
|
| 443 |
-
features = self.layer_norm(features)
|
| 444 |
-
unmasked_features = features.clone()
|
| 445 |
-
|
| 446 |
-
if padding_mask is not None:
|
| 447 |
-
padding_mask = self.forward_padding_mask(features, padding_mask)
|
| 448 |
-
|
| 449 |
-
if self.post_extract_proj is not None:
|
| 450 |
-
features = self.post_extract_proj(features)
|
| 451 |
-
|
| 452 |
-
features = self.dropout_input(features)
|
| 453 |
-
unmasked_features = self.dropout_features(unmasked_features)
|
| 454 |
-
|
| 455 |
-
if mask:
|
| 456 |
-
x, mask_indices = self.apply_mask(features, padding_mask, target_list)
|
| 457 |
-
else:
|
| 458 |
-
x = features
|
| 459 |
-
mask_indices = None
|
| 460 |
-
|
| 461 |
-
# feature: (B, T, D), float
|
| 462 |
-
# target: (B, T), long
|
| 463 |
-
# x: (B, T, D), float
|
| 464 |
-
# padding_mask: (B, T), bool
|
| 465 |
-
# mask_indices: (B, T), bool
|
| 466 |
-
x, layer_results = self.encoder(
|
| 467 |
-
x,
|
| 468 |
-
padding_mask=padding_mask,
|
| 469 |
-
layer=None if output_layer is None else output_layer - 1,
|
| 470 |
-
)
|
| 471 |
-
|
| 472 |
-
if features_only:
|
| 473 |
-
return {"x": x, "padding_mask": padding_mask, "features": features,"layer_results":layer_results}
|
| 474 |
-
|
| 475 |
-
def compute_pred(proj_x, target, label_embs):
|
| 476 |
-
# compute logits for the i-th label set
|
| 477 |
-
y = torch.index_select(label_embs, 0, target.long())
|
| 478 |
-
negs = label_embs.unsqueeze(1).expand(-1, proj_x.size(0), -1)
|
| 479 |
-
if self.target_glu:
|
| 480 |
-
y = self.target_glu(y)
|
| 481 |
-
negs = self.target_glu(negs)
|
| 482 |
-
# proj_x: (S, D)
|
| 483 |
-
# y: (S, D)
|
| 484 |
-
# negs: (Neg, S, D)
|
| 485 |
-
return self.compute_nce(proj_x, y, negs)
|
| 486 |
-
|
| 487 |
-
label_embs_list = self.label_embs_concat.split(self.num_classes, 0)
|
| 488 |
-
|
| 489 |
-
if not self.skip_masked:
|
| 490 |
-
masked_indices = torch.logical_and(~padding_mask, mask_indices)
|
| 491 |
-
proj_x_m = self.final_proj(x[masked_indices])
|
| 492 |
-
if self.untie_final_proj:
|
| 493 |
-
proj_x_m_list = proj_x_m.chunk(len(target_list), dim=-1)
|
| 494 |
-
else:
|
| 495 |
-
proj_x_m_list = [proj_x_m for _ in range(len(target_list))]
|
| 496 |
-
logit_m_list = [
|
| 497 |
-
compute_pred(proj_x_m, t[masked_indices], label_embs_list[i])
|
| 498 |
-
for i, (proj_x_m, t) in enumerate(zip(proj_x_m_list, target_list))
|
| 499 |
-
]
|
| 500 |
-
else:
|
| 501 |
-
logit_m_list = [None for _ in target_list]
|
| 502 |
-
|
| 503 |
-
if not self.skip_nomask:
|
| 504 |
-
nomask_indices = torch.logical_and(~padding_mask, ~mask_indices)
|
| 505 |
-
proj_x_u = self.final_proj(x[nomask_indices])
|
| 506 |
-
if self.untie_final_proj:
|
| 507 |
-
proj_x_u_list = proj_x_u.chunk(len(target_list), dim=-1)
|
| 508 |
-
else:
|
| 509 |
-
proj_x_u_list = [proj_x_u for _ in range(len(target_list))]
|
| 510 |
-
|
| 511 |
-
logit_u_list = [
|
| 512 |
-
compute_pred(proj_x_u, t[nomask_indices], label_embs_list[i])
|
| 513 |
-
for i, (proj_x_u, t) in enumerate(zip(proj_x_u_list, target_list))
|
| 514 |
-
]
|
| 515 |
-
else:
|
| 516 |
-
logit_u_list = [None for _ in target_list]
|
| 517 |
-
|
| 518 |
-
result = {
|
| 519 |
-
"logit_m_list": logit_m_list,
|
| 520 |
-
"logit_u_list": logit_u_list,
|
| 521 |
-
"padding_mask": padding_mask,
|
| 522 |
-
"features_pen": features_pen,
|
| 523 |
-
}
|
| 524 |
-
return result
|
| 525 |
-
|
| 526 |
-
def extract_features(
|
| 527 |
-
self,
|
| 528 |
-
source: torch.Tensor,
|
| 529 |
-
padding_mask: Optional[torch.Tensor] = None,
|
| 530 |
-
mask: bool = False,
|
| 531 |
-
ret_conv: bool = False,
|
| 532 |
-
output_layer: Optional[int] = None,
|
| 533 |
-
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 534 |
-
res = self.forward(
|
| 535 |
-
source,
|
| 536 |
-
padding_mask=padding_mask,
|
| 537 |
-
mask=mask,
|
| 538 |
-
features_only=True,
|
| 539 |
-
output_layer=output_layer,
|
| 540 |
-
)
|
| 541 |
-
feature = res["features"] if ret_conv else res["x"]
|
| 542 |
-
layer_results = res["layer_results"]
|
| 543 |
-
avg_layer_results = sum([result[0] for result in layer_results]) / len(layer_results)
|
| 544 |
-
return feature, res["padding_mask"], avg_layer_results
|
| 545 |
-
|
| 546 |
-
def get_logits(self, net_output, is_masked=True):
|
| 547 |
-
if is_masked:
|
| 548 |
-
logits_list = net_output["logit_m_list"]
|
| 549 |
-
else:
|
| 550 |
-
logits_list = net_output["logit_u_list"]
|
| 551 |
-
logits_list = [x.float() for x in logits_list if x is not None]
|
| 552 |
-
return logits_list
|
| 553 |
-
|
| 554 |
-
def get_targets(self, net_output, is_masked=True):
|
| 555 |
-
logits_list = self.get_logits(net_output, is_masked)
|
| 556 |
-
targets_list = [x.new_zeros(x.size(0), dtype=torch.long) for x in logits_list]
|
| 557 |
-
return targets_list
|
| 558 |
-
|
| 559 |
-
def get_extra_losses(self, net_output):
|
| 560 |
-
extra_losses = []
|
| 561 |
-
names = []
|
| 562 |
-
|
| 563 |
-
if "features_pen" in net_output:
|
| 564 |
-
extra_losses.append(net_output["features_pen"])
|
| 565 |
-
names.append("features_pen")
|
| 566 |
-
|
| 567 |
-
return extra_losses, names
|
| 568 |
-
|
| 569 |
-
def remove_pretraining_modules(self):
|
| 570 |
-
self.target_glu = None
|
| 571 |
-
self.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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/hubert/hubert_asr.py
DELETED
|
@@ -1,363 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import contextlib
|
| 7 |
-
from argparse import Namespace
|
| 8 |
-
from dataclasses import dataclass, field
|
| 9 |
-
from typing import Any
|
| 10 |
-
|
| 11 |
-
import torch
|
| 12 |
-
import torch.nn as nn
|
| 13 |
-
from fairseq import checkpoint_utils, tasks, utils
|
| 14 |
-
from fairseq.dataclass import FairseqDataclass
|
| 15 |
-
from fairseq.dataclass.utils import convert_namespace_to_omegaconf
|
| 16 |
-
from fairseq.models import BaseFairseqModel, FairseqEncoder, register_model
|
| 17 |
-
from fairseq.models.hubert.hubert import MASKING_DISTRIBUTION_CHOICES
|
| 18 |
-
from fairseq.tasks import FairseqTask
|
| 19 |
-
from omegaconf import II, MISSING
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
@dataclass
|
| 23 |
-
class HubertAsrConfig(FairseqDataclass):
|
| 24 |
-
w2v_path: str = field(default=MISSING, metadata={"help": "path to hubert model"})
|
| 25 |
-
no_pretrained_weights: bool = field(
|
| 26 |
-
default=False,
|
| 27 |
-
metadata={"help": "if true, does not load pretrained weights"},
|
| 28 |
-
)
|
| 29 |
-
dropout_input: float = field(
|
| 30 |
-
default=0.0,
|
| 31 |
-
metadata={"help": "dropout to apply to the input (after feat extr)"},
|
| 32 |
-
)
|
| 33 |
-
final_dropout: float = field(
|
| 34 |
-
default=0.0,
|
| 35 |
-
metadata={"help": "dropout after transformer and before final projection"},
|
| 36 |
-
)
|
| 37 |
-
dropout: float = field(
|
| 38 |
-
default=0.0,
|
| 39 |
-
metadata={"help": "dropout probability inside hubert model"},
|
| 40 |
-
)
|
| 41 |
-
attention_dropout: float = field(
|
| 42 |
-
default=0.0,
|
| 43 |
-
metadata={
|
| 44 |
-
"help": "dropout probability for attention weights " "inside hubert model"
|
| 45 |
-
},
|
| 46 |
-
)
|
| 47 |
-
activation_dropout: float = field(
|
| 48 |
-
default=0.0,
|
| 49 |
-
metadata={
|
| 50 |
-
"help": "dropout probability after activation in FFN " "inside hubert model"
|
| 51 |
-
},
|
| 52 |
-
)
|
| 53 |
-
|
| 54 |
-
# masking
|
| 55 |
-
apply_mask: bool = field(
|
| 56 |
-
default=False, metadata={"help": "apply masking during fine-tuning"}
|
| 57 |
-
)
|
| 58 |
-
mask_length: int = field(
|
| 59 |
-
default=10, metadata={"help": "repeat the mask indices multiple times"}
|
| 60 |
-
)
|
| 61 |
-
mask_prob: float = field(
|
| 62 |
-
default=0.5,
|
| 63 |
-
metadata={
|
| 64 |
-
"help": "probability of replacing a token with mask "
|
| 65 |
-
"(normalized by length)"
|
| 66 |
-
},
|
| 67 |
-
)
|
| 68 |
-
mask_selection: MASKING_DISTRIBUTION_CHOICES = field(
|
| 69 |
-
default="static", metadata={"help": "how to choose masks"}
|
| 70 |
-
)
|
| 71 |
-
mask_other: float = field(
|
| 72 |
-
default=0,
|
| 73 |
-
metadata={
|
| 74 |
-
"help": "secondary mask argument "
|
| 75 |
-
"(used for more complex distributions), "
|
| 76 |
-
"see help in compute_mask_indices"
|
| 77 |
-
},
|
| 78 |
-
)
|
| 79 |
-
no_mask_overlap: bool = field(
|
| 80 |
-
default=False, metadata={"help": "whether to allow masks to overlap"}
|
| 81 |
-
)
|
| 82 |
-
|
| 83 |
-
# channel masking
|
| 84 |
-
mask_channel_length: int = field(
|
| 85 |
-
default=10,
|
| 86 |
-
metadata={"help": "length of the mask for features (channels)"},
|
| 87 |
-
)
|
| 88 |
-
mask_channel_prob: float = field(
|
| 89 |
-
default=0.0,
|
| 90 |
-
metadata={"help": "probability of replacing a feature with 0"},
|
| 91 |
-
)
|
| 92 |
-
mask_channel_selection: MASKING_DISTRIBUTION_CHOICES = field(
|
| 93 |
-
default="static",
|
| 94 |
-
metadata={"help": "how to choose mask length for channel masking"},
|
| 95 |
-
)
|
| 96 |
-
mask_channel_other: float = field(
|
| 97 |
-
default=0,
|
| 98 |
-
metadata={
|
| 99 |
-
"help": "secondary mask argument "
|
| 100 |
-
"(used for more complex distributions), "
|
| 101 |
-
"see help in compute_mask_indices"
|
| 102 |
-
},
|
| 103 |
-
)
|
| 104 |
-
no_mask_channel_overlap: bool = field(
|
| 105 |
-
default=False,
|
| 106 |
-
metadata={"help": "whether to allow channel masks to overlap"},
|
| 107 |
-
)
|
| 108 |
-
freeze_finetune_updates: int = field(
|
| 109 |
-
default=0,
|
| 110 |
-
metadata={"help": "dont finetune hubert for this many updates"},
|
| 111 |
-
)
|
| 112 |
-
feature_grad_mult: float = field(
|
| 113 |
-
default=0.0,
|
| 114 |
-
metadata={"help": "reset feature grad mult in hubert to this"},
|
| 115 |
-
)
|
| 116 |
-
layerdrop: float = field(
|
| 117 |
-
default=0.0,
|
| 118 |
-
metadata={"help": "probability of dropping a layer in hubert"},
|
| 119 |
-
)
|
| 120 |
-
normalize: bool = II("task.normalize")
|
| 121 |
-
data: str = II("task.data")
|
| 122 |
-
|
| 123 |
-
# this holds the loaded hubert args
|
| 124 |
-
w2v_args: Any = None
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
@dataclass
|
| 128 |
-
class HubertCtcConfig(HubertAsrConfig):
|
| 129 |
-
pass
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
@register_model("hubert_ctc", dataclass=HubertCtcConfig)
|
| 133 |
-
class HubertCtc(BaseFairseqModel):
|
| 134 |
-
def __init__(self, cfg: HubertCtcConfig, w2v_encoder: BaseFairseqModel):
|
| 135 |
-
super().__init__()
|
| 136 |
-
self.cfg = cfg
|
| 137 |
-
self.w2v_encoder = w2v_encoder
|
| 138 |
-
|
| 139 |
-
def upgrade_state_dict_named(self, state_dict, name):
|
| 140 |
-
super().upgrade_state_dict_named(state_dict, name)
|
| 141 |
-
return state_dict
|
| 142 |
-
|
| 143 |
-
@classmethod
|
| 144 |
-
def build_model(cls, cfg: HubertCtcConfig, task: FairseqTask):
|
| 145 |
-
"""Build a new model instance."""
|
| 146 |
-
w2v_encoder = HubertEncoder(cfg, task)
|
| 147 |
-
return cls(cfg, w2v_encoder)
|
| 148 |
-
|
| 149 |
-
def get_normalized_probs(self, net_output, log_probs):
|
| 150 |
-
"""Get normalized probabilities (or log probs) from a net's output."""
|
| 151 |
-
|
| 152 |
-
logits = net_output["encoder_out"]
|
| 153 |
-
if log_probs:
|
| 154 |
-
return utils.log_softmax(logits.float(), dim=-1)
|
| 155 |
-
else:
|
| 156 |
-
return utils.softmax(logits.float(), dim=-1)
|
| 157 |
-
|
| 158 |
-
def get_logits(self, net_output):
|
| 159 |
-
logits = net_output["encoder_out"]
|
| 160 |
-
padding = net_output["encoder_padding_mask"]
|
| 161 |
-
if padding is not None and padding.any():
|
| 162 |
-
padding = padding.T
|
| 163 |
-
logits[padding][..., 0] = 0
|
| 164 |
-
logits[padding][..., 1:] = float("-inf")
|
| 165 |
-
|
| 166 |
-
return logits
|
| 167 |
-
|
| 168 |
-
def forward(self, **kwargs):
|
| 169 |
-
x = self.w2v_encoder(**kwargs)
|
| 170 |
-
return x
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
@dataclass
|
| 174 |
-
class HubertSeq2SeqConfig(HubertAsrConfig):
|
| 175 |
-
decoder_embed_dim: int = field(
|
| 176 |
-
default=768, metadata={"help": "decoder embedding dimension"}
|
| 177 |
-
)
|
| 178 |
-
decoder_ffn_embed_dim: int = field(
|
| 179 |
-
default=3072, metadata={"help": "decoder embedding dimension for FFN"}
|
| 180 |
-
)
|
| 181 |
-
decoder_layers: int = field(default=6, metadata={"help": "num of decoder layers"})
|
| 182 |
-
decoder_layerdrop: float = field(
|
| 183 |
-
default=0.0, metadata={"help": "decoder layerdrop chance"}
|
| 184 |
-
)
|
| 185 |
-
decoder_attention_heads: int = field(
|
| 186 |
-
default=4, metadata={"help": "num decoder attention heads"}
|
| 187 |
-
)
|
| 188 |
-
decoder_learned_pos: bool = field(
|
| 189 |
-
default=False,
|
| 190 |
-
metadata={"help": "use learned positional embeddings in the decoder"},
|
| 191 |
-
)
|
| 192 |
-
decoder_normalize_before: bool = field(
|
| 193 |
-
default=False,
|
| 194 |
-
metadata={"help": "apply layernorm before each decoder block"},
|
| 195 |
-
)
|
| 196 |
-
no_token_positional_embeddings: bool = field(
|
| 197 |
-
default=False,
|
| 198 |
-
metadata={
|
| 199 |
-
"help": "if set, disables positional embeddings " "(outside self attention)"
|
| 200 |
-
},
|
| 201 |
-
)
|
| 202 |
-
decoder_dropout: float = field(
|
| 203 |
-
default=0.0, metadata={"help": "dropout probability in the decoder"}
|
| 204 |
-
)
|
| 205 |
-
decoder_attention_dropout: float = field(
|
| 206 |
-
default=0.0,
|
| 207 |
-
metadata={
|
| 208 |
-
"help": "dropout probability for attention weights " "inside the decoder"
|
| 209 |
-
},
|
| 210 |
-
)
|
| 211 |
-
decoder_activation_dropout: float = field(
|
| 212 |
-
default=0.0,
|
| 213 |
-
metadata={
|
| 214 |
-
"help": "dropout probability after activation in FFN " "inside the decoder"
|
| 215 |
-
},
|
| 216 |
-
)
|
| 217 |
-
max_target_positions: int = field(
|
| 218 |
-
default=2048, metadata={"help": "max target positions"}
|
| 219 |
-
)
|
| 220 |
-
share_decoder_input_output_embed: bool = field(
|
| 221 |
-
default=False,
|
| 222 |
-
metadata={"help": "share decoder input and output embeddings"},
|
| 223 |
-
)
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
class HubertEncoder(FairseqEncoder):
|
| 227 |
-
def __init__(self, cfg: HubertAsrConfig, task):
|
| 228 |
-
self.apply_mask = cfg.apply_mask
|
| 229 |
-
|
| 230 |
-
arg_overrides = {
|
| 231 |
-
"dropout": cfg.dropout,
|
| 232 |
-
"activation_dropout": cfg.activation_dropout,
|
| 233 |
-
"dropout_input": cfg.dropout_input,
|
| 234 |
-
"attention_dropout": cfg.attention_dropout,
|
| 235 |
-
"mask_length": cfg.mask_length,
|
| 236 |
-
"mask_prob": cfg.mask_prob,
|
| 237 |
-
"mask_selection": cfg.mask_selection,
|
| 238 |
-
"mask_other": cfg.mask_other,
|
| 239 |
-
"no_mask_overlap": cfg.no_mask_overlap,
|
| 240 |
-
"mask_channel_length": cfg.mask_channel_length,
|
| 241 |
-
"mask_channel_prob": cfg.mask_channel_prob,
|
| 242 |
-
"mask_channel_selection": cfg.mask_channel_selection,
|
| 243 |
-
"mask_channel_other": cfg.mask_channel_other,
|
| 244 |
-
"no_mask_channel_overlap": cfg.no_mask_channel_overlap,
|
| 245 |
-
"encoder_layerdrop": cfg.layerdrop,
|
| 246 |
-
"feature_grad_mult": cfg.feature_grad_mult,
|
| 247 |
-
}
|
| 248 |
-
|
| 249 |
-
if cfg.w2v_args is None:
|
| 250 |
-
state = checkpoint_utils.load_checkpoint_to_cpu(cfg.w2v_path, arg_overrides)
|
| 251 |
-
w2v_args = state.get("cfg", None)
|
| 252 |
-
if w2v_args is None:
|
| 253 |
-
w2v_args = convert_namespace_to_omegaconf(state["args"])
|
| 254 |
-
cfg.w2v_args = w2v_args
|
| 255 |
-
else:
|
| 256 |
-
state = None
|
| 257 |
-
w2v_args = cfg.w2v_args
|
| 258 |
-
if isinstance(w2v_args, Namespace):
|
| 259 |
-
cfg.w2v_args = w2v_args = convert_namespace_to_omegaconf(w2v_args)
|
| 260 |
-
|
| 261 |
-
assert cfg.normalize == w2v_args.task.normalize, (
|
| 262 |
-
"Fine-tuning works best when data normalization is the same. "
|
| 263 |
-
"Please check that --normalize is set or unset for "
|
| 264 |
-
"both pre-training and here"
|
| 265 |
-
)
|
| 266 |
-
|
| 267 |
-
w2v_args.task.data = cfg.data
|
| 268 |
-
pretrain_task = tasks.setup_task(w2v_args.task)
|
| 269 |
-
if state is not None and "task_state" in state:
|
| 270 |
-
# This will load the stored "dictionaries" object
|
| 271 |
-
pretrain_task.load_state_dict(state["task_state"])
|
| 272 |
-
else:
|
| 273 |
-
pretrain_task.load_state_dict(task.state_dict())
|
| 274 |
-
|
| 275 |
-
model = pretrain_task.build_model(w2v_args.model, from_checkpoint=True)
|
| 276 |
-
if state is not None and not cfg.no_pretrained_weights:
|
| 277 |
-
# set strict=False because we omit some modules
|
| 278 |
-
model.load_state_dict(state["model"], strict=False)
|
| 279 |
-
|
| 280 |
-
model.remove_pretraining_modules()
|
| 281 |
-
|
| 282 |
-
super().__init__(pretrain_task.source_dictionary)
|
| 283 |
-
|
| 284 |
-
d = w2v_args.model.encoder_embed_dim
|
| 285 |
-
|
| 286 |
-
self.w2v_model = model
|
| 287 |
-
|
| 288 |
-
self.final_dropout = nn.Dropout(cfg.final_dropout)
|
| 289 |
-
self.freeze_finetune_updates = cfg.freeze_finetune_updates
|
| 290 |
-
self.num_updates = 0
|
| 291 |
-
|
| 292 |
-
if task.target_dictionary is not None:
|
| 293 |
-
self.proj = Linear(d, len(task.target_dictionary))
|
| 294 |
-
elif getattr(cfg, "decoder_embed_dim", d) != d:
|
| 295 |
-
self.proj = Linear(d, cfg.decoder_embed_dim)
|
| 296 |
-
else:
|
| 297 |
-
self.proj = None
|
| 298 |
-
|
| 299 |
-
def set_num_updates(self, num_updates):
|
| 300 |
-
"""Set the number of parameters updates."""
|
| 301 |
-
super().set_num_updates(num_updates)
|
| 302 |
-
self.num_updates = num_updates
|
| 303 |
-
|
| 304 |
-
def forward(self, source, padding_mask, tbc=True, **kwargs):
|
| 305 |
-
|
| 306 |
-
w2v_args = {
|
| 307 |
-
"source": source,
|
| 308 |
-
"padding_mask": padding_mask,
|
| 309 |
-
"mask": self.apply_mask and self.training,
|
| 310 |
-
}
|
| 311 |
-
|
| 312 |
-
ft = self.freeze_finetune_updates <= self.num_updates
|
| 313 |
-
|
| 314 |
-
with torch.no_grad() if not ft else contextlib.ExitStack():
|
| 315 |
-
x, padding_mask = self.w2v_model.extract_features(**w2v_args)
|
| 316 |
-
|
| 317 |
-
if tbc:
|
| 318 |
-
# B x T x C -> T x B x C
|
| 319 |
-
x = x.transpose(0, 1)
|
| 320 |
-
|
| 321 |
-
x = self.final_dropout(x)
|
| 322 |
-
|
| 323 |
-
if self.proj:
|
| 324 |
-
x = self.proj(x)
|
| 325 |
-
|
| 326 |
-
return {
|
| 327 |
-
"encoder_out": x, # T x B x C
|
| 328 |
-
"encoder_padding_mask": padding_mask, # B x T
|
| 329 |
-
"padding_mask": padding_mask,
|
| 330 |
-
}
|
| 331 |
-
|
| 332 |
-
def reorder_encoder_out(self, encoder_out, new_order):
|
| 333 |
-
if encoder_out["encoder_out"] is not None:
|
| 334 |
-
encoder_out["encoder_out"] = encoder_out["encoder_out"].index_select(
|
| 335 |
-
1, new_order
|
| 336 |
-
)
|
| 337 |
-
if encoder_out["encoder_padding_mask"] is not None:
|
| 338 |
-
encoder_out["encoder_padding_mask"] = encoder_out[
|
| 339 |
-
"encoder_padding_mask"
|
| 340 |
-
].index_select(0, new_order)
|
| 341 |
-
return encoder_out
|
| 342 |
-
|
| 343 |
-
def max_positions(self):
|
| 344 |
-
"""Maximum input length supported by the encoder."""
|
| 345 |
-
return None
|
| 346 |
-
|
| 347 |
-
def upgrade_state_dict_named(self, state_dict, name):
|
| 348 |
-
return state_dict
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
def Embedding(num_embeddings, embedding_dim, padding_idx):
|
| 352 |
-
m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
|
| 353 |
-
nn.init.normal_(m.weight, mean=0, std=embedding_dim**-0.5)
|
| 354 |
-
nn.init.constant_(m.weight[padding_idx], 0)
|
| 355 |
-
return m
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
def Linear(in_features, out_features, bias=True):
|
| 359 |
-
m = nn.Linear(in_features, out_features, bias)
|
| 360 |
-
nn.init.xavier_uniform_(m.weight)
|
| 361 |
-
if bias:
|
| 362 |
-
nn.init.constant_(m.bias, 0.0)
|
| 363 |
-
return m
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/huggingface/__init__.py
DELETED
|
@@ -1,19 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import importlib
|
| 7 |
-
import os
|
| 8 |
-
|
| 9 |
-
# automatically import any Python files in the models/huggingface/ directory
|
| 10 |
-
models_dir = os.path.dirname(__file__)
|
| 11 |
-
for file in os.listdir(models_dir):
|
| 12 |
-
path = os.path.join(models_dir, file)
|
| 13 |
-
if (
|
| 14 |
-
not file.startswith("_")
|
| 15 |
-
and not file.startswith(".")
|
| 16 |
-
and (file.endswith(".py") or os.path.isdir(path))
|
| 17 |
-
):
|
| 18 |
-
model_name = file[: file.find(".py")] if file.endswith(".py") else file
|
| 19 |
-
module = importlib.import_module("fairseq.models.huggingface." + model_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/huggingface/hf_gpt2.py
DELETED
|
@@ -1,167 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import logging
|
| 7 |
-
import os
|
| 8 |
-
import sys
|
| 9 |
-
from typing import Dict, List, Optional
|
| 10 |
-
|
| 11 |
-
import torch
|
| 12 |
-
from fairseq.models import (
|
| 13 |
-
FairseqIncrementalDecoder,
|
| 14 |
-
FairseqLanguageModel,
|
| 15 |
-
register_model,
|
| 16 |
-
register_model_architecture,
|
| 17 |
-
)
|
| 18 |
-
|
| 19 |
-
logger = logging.getLogger(__name__)
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
DEFAULT_MAX_TARGET_POSITIONS = 1024
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
@register_model("hf_gpt2")
|
| 26 |
-
class HuggingFaceGPT2LanguageModel(FairseqLanguageModel):
|
| 27 |
-
def __init__(self, decoder):
|
| 28 |
-
super().__init__(decoder)
|
| 29 |
-
|
| 30 |
-
@staticmethod
|
| 31 |
-
def add_args(parser):
|
| 32 |
-
"""Add model-specific arguments to the parser."""
|
| 33 |
-
# fmt: off
|
| 34 |
-
parser.add_argument('--embed-dim', type=int, metavar='N',
|
| 35 |
-
help='embedding dimension')
|
| 36 |
-
parser.add_argument('--num-attention-heads', type=int, metavar='N',
|
| 37 |
-
help='num attention heads')
|
| 38 |
-
parser.add_argument('--num-layers', type=int, metavar='N',
|
| 39 |
-
help='num layers')
|
| 40 |
-
parser.add_argument('--dropout', type=float, metavar='D',
|
| 41 |
-
help='dropout probability for all fully connected layers '
|
| 42 |
-
'in the embeddings, encoder, and pooler')
|
| 43 |
-
parser.add_argument('--attention-dropout', type=float, metavar='D',
|
| 44 |
-
help='dropout probability for attention weights')
|
| 45 |
-
# fmt: on
|
| 46 |
-
|
| 47 |
-
@classmethod
|
| 48 |
-
def build_model(cls, args, task):
|
| 49 |
-
"""Build a new model instance."""
|
| 50 |
-
default_architecture(args)
|
| 51 |
-
return cls(HuggingFaceGPT2Decoder(args, task))
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
class HuggingFaceGPT2Decoder(FairseqIncrementalDecoder):
|
| 55 |
-
def __init__(self, args, task):
|
| 56 |
-
try:
|
| 57 |
-
from transformers import GPT2Config, GPT2LMHeadModel
|
| 58 |
-
except ImportError:
|
| 59 |
-
raise ImportError(
|
| 60 |
-
"\n\nPlease install huggingface/transformers with:"
|
| 61 |
-
"\n\n pip install transformers"
|
| 62 |
-
)
|
| 63 |
-
|
| 64 |
-
super().__init__(task.target_dictionary)
|
| 65 |
-
|
| 66 |
-
config = GPT2Config(
|
| 67 |
-
vocab_size=len(task.target_dictionary),
|
| 68 |
-
n_positions=args.max_target_positions + 1,
|
| 69 |
-
n_ctx=args.max_target_positions,
|
| 70 |
-
n_embd=args.embed_dim,
|
| 71 |
-
n_layer=args.num_layers,
|
| 72 |
-
n_head=args.num_attention_heads,
|
| 73 |
-
resid_pdrop=args.dropout,
|
| 74 |
-
embd_pdrop=args.dropout,
|
| 75 |
-
attn_pdrop=args.attention_dropout,
|
| 76 |
-
layer_norm_epsilon=1e-6,
|
| 77 |
-
)
|
| 78 |
-
self.model = GPT2LMHeadModel(config)
|
| 79 |
-
|
| 80 |
-
# set zero embedding for padding symbol
|
| 81 |
-
self.pad_idx = task.target_dictionary.pad()
|
| 82 |
-
self.model.transformer.wte.weight.data[self.pad_idx].zero_()
|
| 83 |
-
self.model.transformer.wpe.weight.data[0].zero_()
|
| 84 |
-
|
| 85 |
-
def forward(
|
| 86 |
-
self,
|
| 87 |
-
prev_output_tokens,
|
| 88 |
-
src_lengths=None,
|
| 89 |
-
incremental_state: Optional[Dict[str, List[torch.Tensor]]] = None,
|
| 90 |
-
encoder_out=None,
|
| 91 |
-
):
|
| 92 |
-
features = self.extract_features(prev_output_tokens, incremental_state)
|
| 93 |
-
lm_logits = self.model.lm_head(features)
|
| 94 |
-
return (lm_logits,)
|
| 95 |
-
|
| 96 |
-
def extract_features(
|
| 97 |
-
self,
|
| 98 |
-
prev_output_tokens,
|
| 99 |
-
incremental_state: Optional[Dict[str, List[torch.Tensor]]] = None,
|
| 100 |
-
):
|
| 101 |
-
if incremental_state:
|
| 102 |
-
past = self.get_incremental_state("past")
|
| 103 |
-
else:
|
| 104 |
-
past = None
|
| 105 |
-
|
| 106 |
-
# don't attend to padding symbols
|
| 107 |
-
attention_mask = prev_output_tokens.ne(self.pad_idx).int()
|
| 108 |
-
|
| 109 |
-
# set position ids to exclude padding symbols
|
| 110 |
-
position_ids = attention_mask * (
|
| 111 |
-
torch.arange(1, 1 + prev_output_tokens.size(1))
|
| 112 |
-
.to(prev_output_tokens)
|
| 113 |
-
.repeat(prev_output_tokens.size(0), 1)
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
-
outputs = self.model.transformer(
|
| 117 |
-
input_ids=prev_output_tokens,
|
| 118 |
-
past=past,
|
| 119 |
-
attention_mask=attention_mask,
|
| 120 |
-
position_ids=position_ids,
|
| 121 |
-
)
|
| 122 |
-
last_hidden_states = outputs[0]
|
| 123 |
-
|
| 124 |
-
if incremental_state:
|
| 125 |
-
self.set_incremental_state(incremental_state, "past", outputs[1])
|
| 126 |
-
|
| 127 |
-
return last_hidden_states
|
| 128 |
-
|
| 129 |
-
def max_positions(self):
|
| 130 |
-
return self.model.config.n_positions - 1
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
@register_model_architecture("hf_gpt2", "hf_gpt2")
|
| 134 |
-
def default_architecture(args):
|
| 135 |
-
if getattr(args, "max_target_positions", None) is None:
|
| 136 |
-
args.max_target_positions = getattr(
|
| 137 |
-
args, "tokens_per_sample", DEFAULT_MAX_TARGET_POSITIONS
|
| 138 |
-
)
|
| 139 |
-
args.embed_dim = getattr(args, "embed_dim", 768)
|
| 140 |
-
args.num_attention_heads = getattr(args, "num_attention_heads", 12)
|
| 141 |
-
args.num_layers = getattr(args, "num_layers", 12)
|
| 142 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 143 |
-
args.attention_dropout = getattr(args, "attention_dropout", 0.1)
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
@register_model_architecture("hf_gpt2", "hf_gpt2_medium")
|
| 147 |
-
def hf_gpt2_medium(args):
|
| 148 |
-
args.embed_dim = getattr(args, "embed_dim", 1024)
|
| 149 |
-
args.num_attention_heads = getattr(args, "num_attention_heads", 16)
|
| 150 |
-
args.num_layers = getattr(args, "num_layers", 24)
|
| 151 |
-
default_architecture(args)
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
@register_model_architecture("hf_gpt2", "hf_gpt2_large")
|
| 155 |
-
def hf_gpt2_large(args):
|
| 156 |
-
args.embed_dim = getattr(args, "embed_dim", 1280)
|
| 157 |
-
args.num_attention_heads = getattr(args, "num_attention_heads", 20)
|
| 158 |
-
args.num_layers = getattr(args, "num_layers", 36)
|
| 159 |
-
default_architecture(args)
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
@register_model_architecture("hf_gpt2", "hf_gpt2_xl")
|
| 163 |
-
def hf_gpt2_xl(args):
|
| 164 |
-
args.embed_dim = getattr(args, "embed_dim", 1600)
|
| 165 |
-
args.num_attention_heads = getattr(args, "num_attention_heads", 25)
|
| 166 |
-
args.num_layers = getattr(args, "num_layers", 48)
|
| 167 |
-
default_architecture(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/lightconv.py
DELETED
|
@@ -1,1019 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import math
|
| 7 |
-
|
| 8 |
-
import torch
|
| 9 |
-
import torch.nn as nn
|
| 10 |
-
import torch.nn.functional as F
|
| 11 |
-
from fairseq import utils
|
| 12 |
-
from fairseq.models import (
|
| 13 |
-
FairseqEncoder,
|
| 14 |
-
FairseqEncoderDecoderModel,
|
| 15 |
-
FairseqIncrementalDecoder,
|
| 16 |
-
register_model,
|
| 17 |
-
register_model_architecture,
|
| 18 |
-
)
|
| 19 |
-
from fairseq.modules import (
|
| 20 |
-
AdaptiveSoftmax,
|
| 21 |
-
DynamicConv,
|
| 22 |
-
FairseqDropout,
|
| 23 |
-
LayerNorm,
|
| 24 |
-
LightweightConv,
|
| 25 |
-
MultiheadAttention,
|
| 26 |
-
PositionalEmbedding,
|
| 27 |
-
)
|
| 28 |
-
from fairseq.utils import safe_hasattr
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
@register_model("lightconv")
|
| 32 |
-
class LightConvModel(FairseqEncoderDecoderModel):
|
| 33 |
-
"""
|
| 34 |
-
LightConv and DynamicConv model from `"Pay Less Attention with Lightweight and Dynamic Convolutions" (Wu, et al, 2019)
|
| 35 |
-
<https://openreview.net/pdf?id=SkVhlh09tX>`_.
|
| 36 |
-
To use LightConv please set ``--encoder-conv-type lightweight --decoder-conv-type lightweight``
|
| 37 |
-
To use DynamicConv please set ``--encoder-conv-type dynamic --decoder-conv-type dynamic``
|
| 38 |
-
|
| 39 |
-
Args:
|
| 40 |
-
encoder (LightConvEncoder): the encoder
|
| 41 |
-
decoder (LightConvDecoder): the decoder
|
| 42 |
-
|
| 43 |
-
The LightConv model provides the following named architectures and
|
| 44 |
-
command-line arguments:
|
| 45 |
-
|
| 46 |
-
.. argparse::
|
| 47 |
-
:ref: fairseq.models.lightconv_parser
|
| 48 |
-
:prog:
|
| 49 |
-
"""
|
| 50 |
-
|
| 51 |
-
@classmethod
|
| 52 |
-
def hub_models(cls):
|
| 53 |
-
# fmt: off
|
| 54 |
-
|
| 55 |
-
def moses_subword(path):
|
| 56 |
-
return {
|
| 57 |
-
'path': path,
|
| 58 |
-
'tokenizer': 'moses',
|
| 59 |
-
'bpe': 'subword_nmt',
|
| 60 |
-
}
|
| 61 |
-
|
| 62 |
-
return {
|
| 63 |
-
'lightconv.no_glu.iwslt14.de-en': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/dynamicconv/iwslt14.de-en.lightconv.tar.gz'),
|
| 64 |
-
'dynamicconv.no_glu.iwslt14.de-en': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/dynamicconv/iwslt14.de-en.dynamicconv.tar.gz'),
|
| 65 |
-
'lightconv.no_glu.wmt16.en-de': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/dynamicconv/wmt16.en-de.joined-dict.lightconv.tar.gz'),
|
| 66 |
-
'dynamicconv.no_glu.wmt16.en-de': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/dynamicconv/wmt16.en-de.joined-dict.dynamicconv.tar.gz'),
|
| 67 |
-
'lightconv.glu.wmt16.en-de': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/dynamicconv/wmt16.en-de.joined-dict.lightconv-glu.tar.gz'),
|
| 68 |
-
'dynamicconv.glu.wmt16.en-de': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/dynamicconv/wmt16.en-de.joined-dict.dynamicconv-glu.tar.gz'),
|
| 69 |
-
'lightconv.glu.wmt17.en-de': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/dynamicconv/wmt16.en-de.joined-dict.lightconv-glu.tar.gz'),
|
| 70 |
-
'dynamicconv.glu.wmt17.en-de': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/dynamicconv/wmt16.en-de.joined-dict.dynamicconv-glu.tar.gz'),
|
| 71 |
-
'lightconv.glu.wmt14.en-fr': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/dynamicconv/wmt14.en-fr.joined-dict.lightconv-glu.tar.gz'),
|
| 72 |
-
'dynamicconv.glu.wmt14.en-fr': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/dynamicconv/wmt14.en-fr.joined-dict.dynamicconv-glu.tar.gz'),
|
| 73 |
-
'lightconv.glu.wmt17.zh-en': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/dynamicconv/wmt17.zh-en.lightconv-glu.tar.gz'),
|
| 74 |
-
'dynamicconv.glu.wmt17.zh-en': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/dynamicconv/wmt17.zh-en.dynamicconv-glu.tar.gz'),
|
| 75 |
-
}
|
| 76 |
-
# fmt: on
|
| 77 |
-
|
| 78 |
-
def __init__(self, encoder, decoder):
|
| 79 |
-
super().__init__(encoder, decoder)
|
| 80 |
-
|
| 81 |
-
@staticmethod
|
| 82 |
-
def add_args(parser):
|
| 83 |
-
"""Add model-specific arguments to the parser."""
|
| 84 |
-
parser.add_argument(
|
| 85 |
-
"--dropout", type=float, metavar="D", help="dropout probability"
|
| 86 |
-
)
|
| 87 |
-
parser.add_argument(
|
| 88 |
-
"--attention-dropout",
|
| 89 |
-
type=float,
|
| 90 |
-
metavar="D",
|
| 91 |
-
help="dropout probability for attention weights",
|
| 92 |
-
)
|
| 93 |
-
parser.add_argument(
|
| 94 |
-
"--relu-dropout",
|
| 95 |
-
type=float,
|
| 96 |
-
metavar="D",
|
| 97 |
-
help="dropout probability after ReLU in FFN",
|
| 98 |
-
)
|
| 99 |
-
parser.add_argument(
|
| 100 |
-
"--input-dropout",
|
| 101 |
-
type=float,
|
| 102 |
-
metavar="D",
|
| 103 |
-
help="dropout probability of the inputs",
|
| 104 |
-
)
|
| 105 |
-
parser.add_argument(
|
| 106 |
-
"--encoder-embed-path",
|
| 107 |
-
type=str,
|
| 108 |
-
metavar="STR",
|
| 109 |
-
help="path to pre-trained encoder embedding",
|
| 110 |
-
)
|
| 111 |
-
parser.add_argument(
|
| 112 |
-
"--encoder-embed-dim",
|
| 113 |
-
type=int,
|
| 114 |
-
metavar="N",
|
| 115 |
-
help="encoder embedding dimension",
|
| 116 |
-
)
|
| 117 |
-
parser.add_argument(
|
| 118 |
-
"--encoder-conv-dim",
|
| 119 |
-
type=int,
|
| 120 |
-
metavar="N",
|
| 121 |
-
help="encoder embedding dimension",
|
| 122 |
-
)
|
| 123 |
-
parser.add_argument(
|
| 124 |
-
"--encoder-ffn-embed-dim",
|
| 125 |
-
type=int,
|
| 126 |
-
metavar="N",
|
| 127 |
-
help="encoder embedding dimension for FFN",
|
| 128 |
-
)
|
| 129 |
-
parser.add_argument(
|
| 130 |
-
"--encoder-layers", type=int, metavar="N", help="num encoder layers"
|
| 131 |
-
)
|
| 132 |
-
parser.add_argument(
|
| 133 |
-
"--encoder-attention-heads",
|
| 134 |
-
type=int,
|
| 135 |
-
metavar="N",
|
| 136 |
-
help="num encoder attention heads or LightConv/DynamicConv heads",
|
| 137 |
-
)
|
| 138 |
-
parser.add_argument(
|
| 139 |
-
"--encoder-normalize-before",
|
| 140 |
-
action="store_true",
|
| 141 |
-
help="apply layernorm before each encoder block",
|
| 142 |
-
)
|
| 143 |
-
parser.add_argument(
|
| 144 |
-
"--encoder-learned-pos",
|
| 145 |
-
action="store_true",
|
| 146 |
-
help="use learned positional embeddings in the encoder",
|
| 147 |
-
)
|
| 148 |
-
parser.add_argument(
|
| 149 |
-
"--decoder-embed-path",
|
| 150 |
-
type=str,
|
| 151 |
-
metavar="STR",
|
| 152 |
-
help="path to pre-trained decoder embedding",
|
| 153 |
-
)
|
| 154 |
-
parser.add_argument(
|
| 155 |
-
"--decoder-embed-dim",
|
| 156 |
-
type=int,
|
| 157 |
-
metavar="N",
|
| 158 |
-
help="decoder embedding dimension",
|
| 159 |
-
)
|
| 160 |
-
parser.add_argument(
|
| 161 |
-
"--decoder-conv-dim",
|
| 162 |
-
type=int,
|
| 163 |
-
metavar="N",
|
| 164 |
-
help="decoder embedding dimension",
|
| 165 |
-
)
|
| 166 |
-
parser.add_argument(
|
| 167 |
-
"--decoder-ffn-embed-dim",
|
| 168 |
-
type=int,
|
| 169 |
-
metavar="N",
|
| 170 |
-
help="decoder embedding dimension for FFN",
|
| 171 |
-
)
|
| 172 |
-
parser.add_argument(
|
| 173 |
-
"--decoder-layers", type=int, metavar="N", help="num decoder layers"
|
| 174 |
-
)
|
| 175 |
-
parser.add_argument(
|
| 176 |
-
"--decoder-attention-heads",
|
| 177 |
-
type=int,
|
| 178 |
-
metavar="N",
|
| 179 |
-
help="num decoder attention heads or LightConv/DynamicConv heads",
|
| 180 |
-
)
|
| 181 |
-
parser.add_argument(
|
| 182 |
-
"--decoder-learned-pos",
|
| 183 |
-
action="store_true",
|
| 184 |
-
help="use learned positional embeddings in the decoder",
|
| 185 |
-
)
|
| 186 |
-
parser.add_argument(
|
| 187 |
-
"--decoder-normalize-before",
|
| 188 |
-
action="store_true",
|
| 189 |
-
help="apply layernorm before each decoder block",
|
| 190 |
-
)
|
| 191 |
-
parser.add_argument(
|
| 192 |
-
"--share-decoder-input-output-embed",
|
| 193 |
-
action="store_true",
|
| 194 |
-
help="share decoder input and output embeddings",
|
| 195 |
-
)
|
| 196 |
-
parser.add_argument(
|
| 197 |
-
"--share-all-embeddings",
|
| 198 |
-
action="store_true",
|
| 199 |
-
help="share encoder, decoder and output embeddings"
|
| 200 |
-
" (requires shared dictionary and embed dim)",
|
| 201 |
-
)
|
| 202 |
-
parser.add_argument(
|
| 203 |
-
"--adaptive-softmax-cutoff",
|
| 204 |
-
metavar="EXPR",
|
| 205 |
-
help="comma separated list of adaptive softmax cutoff points. "
|
| 206 |
-
"Must be used with adaptive_loss criterion",
|
| 207 |
-
),
|
| 208 |
-
parser.add_argument(
|
| 209 |
-
"--adaptive-softmax-dropout",
|
| 210 |
-
type=float,
|
| 211 |
-
metavar="D",
|
| 212 |
-
help="sets adaptive softmax dropout for the tail projections",
|
| 213 |
-
)
|
| 214 |
-
|
| 215 |
-
"""LightConv and DynamicConv arguments"""
|
| 216 |
-
parser.add_argument(
|
| 217 |
-
"--encoder-kernel-size-list",
|
| 218 |
-
type=lambda x: utils.eval_str_list(x, int),
|
| 219 |
-
help='list of kernel size (default: "[3,7,15,31,31,31,31]")',
|
| 220 |
-
)
|
| 221 |
-
parser.add_argument(
|
| 222 |
-
"--decoder-kernel-size-list",
|
| 223 |
-
type=lambda x: utils.eval_str_list(x, int),
|
| 224 |
-
help='list of kernel size (default: "[3,7,15,31,31,31]")',
|
| 225 |
-
)
|
| 226 |
-
parser.add_argument(
|
| 227 |
-
"--encoder-glu", type=utils.eval_bool, help="glu after in proj"
|
| 228 |
-
)
|
| 229 |
-
parser.add_argument(
|
| 230 |
-
"--decoder-glu", type=utils.eval_bool, help="glu after in proj"
|
| 231 |
-
)
|
| 232 |
-
parser.add_argument(
|
| 233 |
-
"--encoder-conv-type",
|
| 234 |
-
default="dynamic",
|
| 235 |
-
type=str,
|
| 236 |
-
choices=["dynamic", "lightweight"],
|
| 237 |
-
help="type of convolution",
|
| 238 |
-
)
|
| 239 |
-
parser.add_argument(
|
| 240 |
-
"--decoder-conv-type",
|
| 241 |
-
default="dynamic",
|
| 242 |
-
type=str,
|
| 243 |
-
choices=["dynamic", "lightweight"],
|
| 244 |
-
help="type of convolution",
|
| 245 |
-
)
|
| 246 |
-
parser.add_argument("--weight-softmax", default=True, type=utils.eval_bool)
|
| 247 |
-
parser.add_argument(
|
| 248 |
-
"--weight-dropout",
|
| 249 |
-
type=float,
|
| 250 |
-
metavar="D",
|
| 251 |
-
help="dropout probability for conv weights",
|
| 252 |
-
)
|
| 253 |
-
|
| 254 |
-
@classmethod
|
| 255 |
-
def build_model(cls, args, task):
|
| 256 |
-
"""Build a new model instance."""
|
| 257 |
-
|
| 258 |
-
# make sure all arguments are present in older models
|
| 259 |
-
base_architecture(args)
|
| 260 |
-
|
| 261 |
-
if not safe_hasattr(args, "max_source_positions"):
|
| 262 |
-
args.max_source_positions = 1024
|
| 263 |
-
if not safe_hasattr(args, "max_target_positions"):
|
| 264 |
-
args.max_target_positions = 1024
|
| 265 |
-
|
| 266 |
-
src_dict, tgt_dict = task.source_dictionary, task.target_dictionary
|
| 267 |
-
|
| 268 |
-
def build_embedding(dictionary, embed_dim, path=None):
|
| 269 |
-
num_embeddings = len(dictionary)
|
| 270 |
-
padding_idx = dictionary.pad()
|
| 271 |
-
emb = Embedding(num_embeddings, embed_dim, padding_idx)
|
| 272 |
-
# if provided, load from preloaded dictionaries
|
| 273 |
-
if path:
|
| 274 |
-
embed_dict = utils.parse_embedding(path)
|
| 275 |
-
utils.load_embedding(embed_dict, dictionary, emb)
|
| 276 |
-
return emb
|
| 277 |
-
|
| 278 |
-
if args.share_all_embeddings:
|
| 279 |
-
if src_dict != tgt_dict:
|
| 280 |
-
raise RuntimeError(
|
| 281 |
-
"--share-all-embeddings requires a joined dictionary"
|
| 282 |
-
)
|
| 283 |
-
if args.encoder_embed_dim != args.decoder_embed_dim:
|
| 284 |
-
raise RuntimeError(
|
| 285 |
-
"--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim"
|
| 286 |
-
)
|
| 287 |
-
if args.decoder_embed_path and (
|
| 288 |
-
args.decoder_embed_path != args.encoder_embed_path
|
| 289 |
-
):
|
| 290 |
-
raise RuntimeError(
|
| 291 |
-
"--share-all-embeddings not compatible with --decoder-embed-path"
|
| 292 |
-
)
|
| 293 |
-
encoder_embed_tokens = build_embedding(
|
| 294 |
-
src_dict, args.encoder_embed_dim, args.encoder_embed_path
|
| 295 |
-
)
|
| 296 |
-
decoder_embed_tokens = encoder_embed_tokens
|
| 297 |
-
args.share_decoder_input_output_embed = True
|
| 298 |
-
else:
|
| 299 |
-
encoder_embed_tokens = build_embedding(
|
| 300 |
-
src_dict, args.encoder_embed_dim, args.encoder_embed_path
|
| 301 |
-
)
|
| 302 |
-
decoder_embed_tokens = build_embedding(
|
| 303 |
-
tgt_dict, args.decoder_embed_dim, args.decoder_embed_path
|
| 304 |
-
)
|
| 305 |
-
|
| 306 |
-
encoder = LightConvEncoder(args, src_dict, encoder_embed_tokens)
|
| 307 |
-
decoder = LightConvDecoder(args, tgt_dict, decoder_embed_tokens)
|
| 308 |
-
return LightConvModel(encoder, decoder)
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
class LightConvEncoder(FairseqEncoder):
|
| 312 |
-
"""
|
| 313 |
-
LightConv encoder consisting of *args.encoder_layers* layers. Each layer
|
| 314 |
-
is a :class:`LightConvEncoderLayer`.
|
| 315 |
-
|
| 316 |
-
Args:
|
| 317 |
-
args (argparse.Namespace): parsed command-line arguments
|
| 318 |
-
dictionary (~fairseq.data.Dictionary): encoding dictionary
|
| 319 |
-
embed_tokens (torch.nn.Embedding): input embedding
|
| 320 |
-
"""
|
| 321 |
-
|
| 322 |
-
def __init__(self, args, dictionary, embed_tokens):
|
| 323 |
-
super().__init__(dictionary)
|
| 324 |
-
self.dropout_module = FairseqDropout(
|
| 325 |
-
args.dropout, module_name=self.__class__.__name__
|
| 326 |
-
)
|
| 327 |
-
|
| 328 |
-
embed_dim = embed_tokens.embedding_dim
|
| 329 |
-
self.padding_idx = embed_tokens.padding_idx
|
| 330 |
-
self.max_source_positions = args.max_source_positions
|
| 331 |
-
|
| 332 |
-
self.embed_tokens = embed_tokens
|
| 333 |
-
self.embed_scale = math.sqrt(embed_dim)
|
| 334 |
-
self.embed_positions = (
|
| 335 |
-
PositionalEmbedding(
|
| 336 |
-
args.max_source_positions,
|
| 337 |
-
embed_dim,
|
| 338 |
-
self.padding_idx,
|
| 339 |
-
learned=args.encoder_learned_pos,
|
| 340 |
-
)
|
| 341 |
-
if not args.no_token_positional_embeddings
|
| 342 |
-
else None
|
| 343 |
-
)
|
| 344 |
-
|
| 345 |
-
self.layers = nn.ModuleList([])
|
| 346 |
-
self.layers.extend(
|
| 347 |
-
[
|
| 348 |
-
LightConvEncoderLayer(
|
| 349 |
-
args, kernel_size=args.encoder_kernel_size_list[i]
|
| 350 |
-
)
|
| 351 |
-
for i in range(args.encoder_layers)
|
| 352 |
-
]
|
| 353 |
-
)
|
| 354 |
-
self.register_buffer("version", torch.Tensor([2]))
|
| 355 |
-
self.normalize = args.encoder_normalize_before
|
| 356 |
-
if self.normalize:
|
| 357 |
-
self.layer_norm = LayerNorm(embed_dim)
|
| 358 |
-
|
| 359 |
-
def forward(self, src_tokens, **unused):
|
| 360 |
-
"""
|
| 361 |
-
Args:
|
| 362 |
-
src_tokens (LongTensor): tokens in the source language of shape
|
| 363 |
-
`(batch, src_len)`
|
| 364 |
-
|
| 365 |
-
Returns:
|
| 366 |
-
dict:
|
| 367 |
-
- **encoder_out** (Tensor): the last encoder layer's output of
|
| 368 |
-
shape `(src_len, batch, embed_dim)`
|
| 369 |
-
- **encoder_padding_mask** (ByteTensor): the positions of
|
| 370 |
-
padding elements of shape `(batch, src_len)`
|
| 371 |
-
"""
|
| 372 |
-
# embed tokens and positions
|
| 373 |
-
x = self.embed_scale * self.embed_tokens(src_tokens)
|
| 374 |
-
if self.embed_positions is not None:
|
| 375 |
-
x += self.embed_positions(src_tokens)
|
| 376 |
-
x = self.dropout_module(x)
|
| 377 |
-
|
| 378 |
-
# B x T x C -> T x B x C
|
| 379 |
-
x = x.transpose(0, 1)
|
| 380 |
-
|
| 381 |
-
# compute padding mask
|
| 382 |
-
encoder_padding_mask = src_tokens.eq(self.padding_idx)
|
| 383 |
-
if not encoder_padding_mask.any():
|
| 384 |
-
encoder_padding_mask = None
|
| 385 |
-
|
| 386 |
-
# encoder layers
|
| 387 |
-
for layer in self.layers:
|
| 388 |
-
x = layer(x, encoder_padding_mask)
|
| 389 |
-
|
| 390 |
-
if self.normalize:
|
| 391 |
-
x = self.layer_norm(x)
|
| 392 |
-
|
| 393 |
-
return {
|
| 394 |
-
"encoder_out": x, # T x B x C
|
| 395 |
-
"encoder_padding_mask": encoder_padding_mask, # B x T
|
| 396 |
-
}
|
| 397 |
-
|
| 398 |
-
def reorder_encoder_out(self, encoder_out, new_order):
|
| 399 |
-
"""
|
| 400 |
-
Reorder encoder output according to *new_order*.
|
| 401 |
-
|
| 402 |
-
Args:
|
| 403 |
-
encoder_out: output from the ``forward()`` method
|
| 404 |
-
new_order (LongTensor): desired order
|
| 405 |
-
|
| 406 |
-
Returns:
|
| 407 |
-
*encoder_out* rearranged according to *new_order*
|
| 408 |
-
"""
|
| 409 |
-
if encoder_out["encoder_out"] is not None:
|
| 410 |
-
encoder_out["encoder_out"] = encoder_out["encoder_out"].index_select(
|
| 411 |
-
1, new_order
|
| 412 |
-
)
|
| 413 |
-
if encoder_out["encoder_padding_mask"] is not None:
|
| 414 |
-
encoder_out["encoder_padding_mask"] = encoder_out[
|
| 415 |
-
"encoder_padding_mask"
|
| 416 |
-
].index_select(0, new_order)
|
| 417 |
-
return encoder_out
|
| 418 |
-
|
| 419 |
-
def max_positions(self):
|
| 420 |
-
"""Maximum input length supported by the encoder."""
|
| 421 |
-
if self.embed_positions is None:
|
| 422 |
-
return self.max_source_positions
|
| 423 |
-
return min(self.max_source_positions, self.embed_positions.max_positions)
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
class LightConvDecoder(FairseqIncrementalDecoder):
|
| 427 |
-
"""
|
| 428 |
-
LightConv decoder consisting of *args.decoder_layers* layers. Each layer
|
| 429 |
-
is a :class:`LightConvDecoderLayer`.
|
| 430 |
-
|
| 431 |
-
Args:
|
| 432 |
-
args (argparse.Namespace): parsed command-line arguments
|
| 433 |
-
dictionary (~fairseq.data.Dictionary): decoding dictionary
|
| 434 |
-
embed_tokens (torch.nn.Embedding): output embedding
|
| 435 |
-
no_encoder_attn (bool, optional): whether to attend to encoder outputs.
|
| 436 |
-
Default: ``False``
|
| 437 |
-
"""
|
| 438 |
-
|
| 439 |
-
def __init__(
|
| 440 |
-
self, args, dictionary, embed_tokens, no_encoder_attn=False, final_norm=True
|
| 441 |
-
):
|
| 442 |
-
super().__init__(dictionary)
|
| 443 |
-
self.dropout_module = FairseqDropout(
|
| 444 |
-
args.dropout, module_name=self.__class__.__name__
|
| 445 |
-
)
|
| 446 |
-
self.share_input_output_embed = args.share_decoder_input_output_embed
|
| 447 |
-
|
| 448 |
-
input_embed_dim = embed_tokens.embedding_dim
|
| 449 |
-
embed_dim = args.decoder_embed_dim
|
| 450 |
-
output_embed_dim = args.decoder_output_dim
|
| 451 |
-
|
| 452 |
-
padding_idx = embed_tokens.padding_idx
|
| 453 |
-
self.max_target_positions = args.max_target_positions
|
| 454 |
-
|
| 455 |
-
self.embed_tokens = embed_tokens
|
| 456 |
-
self.embed_scale = math.sqrt(embed_dim) # todo: try with input_embed_dim
|
| 457 |
-
|
| 458 |
-
self.project_in_dim = (
|
| 459 |
-
Linear(input_embed_dim, embed_dim, bias=False)
|
| 460 |
-
if embed_dim != input_embed_dim
|
| 461 |
-
else None
|
| 462 |
-
)
|
| 463 |
-
|
| 464 |
-
self.embed_positions = (
|
| 465 |
-
PositionalEmbedding(
|
| 466 |
-
args.max_target_positions,
|
| 467 |
-
embed_dim,
|
| 468 |
-
padding_idx,
|
| 469 |
-
learned=args.decoder_learned_pos,
|
| 470 |
-
)
|
| 471 |
-
if not args.no_token_positional_embeddings
|
| 472 |
-
else None
|
| 473 |
-
)
|
| 474 |
-
|
| 475 |
-
self.layers = nn.ModuleList([])
|
| 476 |
-
self.layers.extend(
|
| 477 |
-
[
|
| 478 |
-
LightConvDecoderLayer(
|
| 479 |
-
args, no_encoder_attn, kernel_size=args.decoder_kernel_size_list[i]
|
| 480 |
-
)
|
| 481 |
-
for i in range(args.decoder_layers)
|
| 482 |
-
]
|
| 483 |
-
)
|
| 484 |
-
|
| 485 |
-
self.adaptive_softmax = None
|
| 486 |
-
|
| 487 |
-
self.project_out_dim = (
|
| 488 |
-
Linear(embed_dim, output_embed_dim, bias=False)
|
| 489 |
-
if embed_dim != output_embed_dim and not args.tie_adaptive_weights
|
| 490 |
-
else None
|
| 491 |
-
)
|
| 492 |
-
|
| 493 |
-
if args.adaptive_softmax_cutoff is not None:
|
| 494 |
-
self.adaptive_softmax = AdaptiveSoftmax(
|
| 495 |
-
len(dictionary),
|
| 496 |
-
output_embed_dim,
|
| 497 |
-
utils.eval_str_list(args.adaptive_softmax_cutoff, type=int),
|
| 498 |
-
dropout=args.adaptive_softmax_dropout,
|
| 499 |
-
adaptive_inputs=embed_tokens if args.tie_adaptive_weights else None,
|
| 500 |
-
factor=args.adaptive_softmax_factor,
|
| 501 |
-
tie_proj=args.tie_adaptive_proj,
|
| 502 |
-
)
|
| 503 |
-
elif not self.share_input_output_embed:
|
| 504 |
-
self.embed_out = nn.Parameter(
|
| 505 |
-
torch.Tensor(len(dictionary), output_embed_dim)
|
| 506 |
-
)
|
| 507 |
-
nn.init.normal_(self.embed_out, mean=0, std=output_embed_dim**-0.5)
|
| 508 |
-
self.register_buffer("version", torch.Tensor([2]))
|
| 509 |
-
self.normalize = args.decoder_normalize_before and final_norm
|
| 510 |
-
if self.normalize:
|
| 511 |
-
self.layer_norm = LayerNorm(embed_dim)
|
| 512 |
-
|
| 513 |
-
def forward(
|
| 514 |
-
self, prev_output_tokens, encoder_out=None, incremental_state=None, **kwargs
|
| 515 |
-
):
|
| 516 |
-
"""
|
| 517 |
-
Args:
|
| 518 |
-
prev_output_tokens (LongTensor): previous decoder outputs of shape
|
| 519 |
-
`(batch, tgt_len)`, for teacher forcing
|
| 520 |
-
encoder_out (Tensor, optional): output from the encoder, used for
|
| 521 |
-
encoder-side attention
|
| 522 |
-
incremental_state (dict): dictionary used for storing state during
|
| 523 |
-
:ref:`Incremental decoding`
|
| 524 |
-
|
| 525 |
-
Returns:
|
| 526 |
-
tuple:
|
| 527 |
-
- the last decoder layer's output of shape `(batch, tgt_len,
|
| 528 |
-
vocab)`
|
| 529 |
-
- the last decoder layer's attention weights of shape `(batch,
|
| 530 |
-
tgt_len, src_len)`
|
| 531 |
-
"""
|
| 532 |
-
# embed positions
|
| 533 |
-
positions = (
|
| 534 |
-
self.embed_positions(
|
| 535 |
-
prev_output_tokens,
|
| 536 |
-
incremental_state=incremental_state,
|
| 537 |
-
)
|
| 538 |
-
if self.embed_positions is not None
|
| 539 |
-
else None
|
| 540 |
-
)
|
| 541 |
-
|
| 542 |
-
if incremental_state is not None:
|
| 543 |
-
prev_output_tokens = prev_output_tokens[:, -1:]
|
| 544 |
-
if positions is not None:
|
| 545 |
-
positions = positions[:, -1:]
|
| 546 |
-
|
| 547 |
-
# embed tokens and positions
|
| 548 |
-
x = self.embed_scale * self.embed_tokens(prev_output_tokens)
|
| 549 |
-
|
| 550 |
-
if self.project_in_dim is not None:
|
| 551 |
-
x = self.project_in_dim(x)
|
| 552 |
-
|
| 553 |
-
if positions is not None:
|
| 554 |
-
x += positions
|
| 555 |
-
x = self.dropout_module(x)
|
| 556 |
-
|
| 557 |
-
# B x T x C -> T x B x C
|
| 558 |
-
x = x.transpose(0, 1)
|
| 559 |
-
attn = None
|
| 560 |
-
|
| 561 |
-
inner_states = [x]
|
| 562 |
-
|
| 563 |
-
# decoder layers
|
| 564 |
-
for layer in self.layers:
|
| 565 |
-
x, attn = layer(
|
| 566 |
-
x,
|
| 567 |
-
encoder_out["encoder_out"] if encoder_out is not None else None,
|
| 568 |
-
encoder_out["encoder_padding_mask"]
|
| 569 |
-
if encoder_out is not None
|
| 570 |
-
else None,
|
| 571 |
-
incremental_state,
|
| 572 |
-
)
|
| 573 |
-
inner_states.append(x)
|
| 574 |
-
|
| 575 |
-
if self.normalize:
|
| 576 |
-
x = self.layer_norm(x)
|
| 577 |
-
|
| 578 |
-
# T x B x C -> B x T x C
|
| 579 |
-
x = x.transpose(0, 1)
|
| 580 |
-
|
| 581 |
-
if self.project_out_dim is not None:
|
| 582 |
-
x = self.project_out_dim(x)
|
| 583 |
-
|
| 584 |
-
if self.adaptive_softmax is None:
|
| 585 |
-
# project back to size of vocabulary
|
| 586 |
-
if self.share_input_output_embed:
|
| 587 |
-
x = F.linear(x, self.embed_tokens.weight)
|
| 588 |
-
else:
|
| 589 |
-
x = F.linear(x, self.embed_out)
|
| 590 |
-
|
| 591 |
-
return x, {"attn": attn, "inner_states": inner_states}
|
| 592 |
-
|
| 593 |
-
def max_positions(self):
|
| 594 |
-
"""Maximum output length supported by the decoder."""
|
| 595 |
-
if self.embed_positions is None:
|
| 596 |
-
return self.max_target_positions
|
| 597 |
-
return min(self.max_target_positions, self.embed_positions.max_positions)
|
| 598 |
-
|
| 599 |
-
def buffered_future_mask(self, tensor):
|
| 600 |
-
dim = tensor.size(0)
|
| 601 |
-
if (
|
| 602 |
-
not hasattr(self, "_future_mask")
|
| 603 |
-
or self._future_mask is None
|
| 604 |
-
or self._future_mask.device != tensor.device
|
| 605 |
-
):
|
| 606 |
-
self._future_mask = torch.triu(
|
| 607 |
-
utils.fill_with_neg_inf(tensor.new(dim, dim)), 1
|
| 608 |
-
)
|
| 609 |
-
if self._future_mask.size(0) < dim:
|
| 610 |
-
self._future_mask = torch.triu(
|
| 611 |
-
utils.fill_with_neg_inf(self._future_mask.resize_(dim, dim)), 1
|
| 612 |
-
)
|
| 613 |
-
return self._future_mask[:dim, :dim]
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
class LightConvEncoderLayer(nn.Module):
|
| 617 |
-
"""Encoder layer block.
|
| 618 |
-
|
| 619 |
-
Args:
|
| 620 |
-
args (argparse.Namespace): parsed command-line arguments
|
| 621 |
-
kernel_size: kernel size of the convolution
|
| 622 |
-
"""
|
| 623 |
-
|
| 624 |
-
def __init__(self, args, kernel_size=0):
|
| 625 |
-
super().__init__()
|
| 626 |
-
self.embed_dim = args.encoder_embed_dim
|
| 627 |
-
self.conv_dim = args.encoder_conv_dim
|
| 628 |
-
padding_l = (
|
| 629 |
-
kernel_size // 2
|
| 630 |
-
if kernel_size % 2 == 1
|
| 631 |
-
else ((kernel_size - 1) // 2, kernel_size // 2)
|
| 632 |
-
)
|
| 633 |
-
|
| 634 |
-
if args.encoder_glu:
|
| 635 |
-
self.linear1 = Linear(self.embed_dim, 2 * self.conv_dim)
|
| 636 |
-
self.act = nn.GLU()
|
| 637 |
-
else:
|
| 638 |
-
self.linear1 = Linear(self.embed_dim, self.conv_dim)
|
| 639 |
-
self.act = None
|
| 640 |
-
if args.encoder_conv_type == "lightweight":
|
| 641 |
-
self.conv = LightweightConv(
|
| 642 |
-
self.conv_dim,
|
| 643 |
-
kernel_size,
|
| 644 |
-
padding_l=padding_l,
|
| 645 |
-
weight_softmax=args.weight_softmax,
|
| 646 |
-
num_heads=args.encoder_attention_heads,
|
| 647 |
-
weight_dropout=args.weight_dropout,
|
| 648 |
-
)
|
| 649 |
-
elif args.encoder_conv_type == "dynamic":
|
| 650 |
-
self.conv = DynamicConv(
|
| 651 |
-
self.conv_dim,
|
| 652 |
-
kernel_size,
|
| 653 |
-
padding_l=padding_l,
|
| 654 |
-
weight_softmax=args.weight_softmax,
|
| 655 |
-
num_heads=args.encoder_attention_heads,
|
| 656 |
-
weight_dropout=args.weight_dropout,
|
| 657 |
-
)
|
| 658 |
-
else:
|
| 659 |
-
raise NotImplementedError
|
| 660 |
-
self.linear2 = Linear(self.conv_dim, self.embed_dim)
|
| 661 |
-
|
| 662 |
-
self.dropout_module = FairseqDropout(
|
| 663 |
-
args.dropout, module_name=self.__class__.__name__
|
| 664 |
-
)
|
| 665 |
-
self.relu_dropout_module = FairseqDropout(
|
| 666 |
-
args.relu_dropout, module_name=self.__class__.__name__
|
| 667 |
-
)
|
| 668 |
-
self.input_dropout_module = FairseqDropout(
|
| 669 |
-
args.input_dropout, module_name=self.__class__.__name__
|
| 670 |
-
)
|
| 671 |
-
self.normalize_before = args.encoder_normalize_before
|
| 672 |
-
self.fc1 = Linear(self.embed_dim, args.encoder_ffn_embed_dim)
|
| 673 |
-
self.fc2 = Linear(args.encoder_ffn_embed_dim, self.embed_dim)
|
| 674 |
-
self.layer_norms = nn.ModuleList([LayerNorm(self.embed_dim) for _ in range(2)])
|
| 675 |
-
|
| 676 |
-
def forward(self, x, encoder_padding_mask):
|
| 677 |
-
"""
|
| 678 |
-
Args:
|
| 679 |
-
x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
|
| 680 |
-
encoder_padding_mask (ByteTensor): binary ByteTensor of shape
|
| 681 |
-
`(batch, src_len)` where padding elements are indicated by ``1``.
|
| 682 |
-
|
| 683 |
-
Returns:
|
| 684 |
-
encoded output of shape `(batch, src_len, embed_dim)`
|
| 685 |
-
"""
|
| 686 |
-
residual = x
|
| 687 |
-
x = self.maybe_layer_norm(0, x, before=True)
|
| 688 |
-
x = self.input_dropout_module(x)
|
| 689 |
-
x = self.linear1(x)
|
| 690 |
-
if self.act is not None:
|
| 691 |
-
x = self.act(x)
|
| 692 |
-
if encoder_padding_mask is not None:
|
| 693 |
-
x = x.masked_fill(encoder_padding_mask.transpose(0, 1).unsqueeze(2), 0)
|
| 694 |
-
x = self.conv(x)
|
| 695 |
-
x = self.linear2(x)
|
| 696 |
-
x = self.dropout_module(x)
|
| 697 |
-
x = residual + x
|
| 698 |
-
x = self.maybe_layer_norm(0, x, after=True)
|
| 699 |
-
|
| 700 |
-
residual = x
|
| 701 |
-
x = self.maybe_layer_norm(1, x, before=True)
|
| 702 |
-
x = F.relu(self.fc1(x))
|
| 703 |
-
x = self.relu_dropout_module(x)
|
| 704 |
-
x = self.fc2(x)
|
| 705 |
-
x = self.dropout_module(x)
|
| 706 |
-
x = residual + x
|
| 707 |
-
x = self.maybe_layer_norm(1, x, after=True)
|
| 708 |
-
return x
|
| 709 |
-
|
| 710 |
-
def maybe_layer_norm(self, i, x, before=False, after=False):
|
| 711 |
-
assert before ^ after
|
| 712 |
-
if after ^ self.normalize_before:
|
| 713 |
-
return self.layer_norms[i](x)
|
| 714 |
-
else:
|
| 715 |
-
return x
|
| 716 |
-
|
| 717 |
-
def extra_repr(self):
|
| 718 |
-
return (
|
| 719 |
-
"dropout={}, relu_dropout={}, input_dropout={}, normalize_before={}".format(
|
| 720 |
-
self.dropout_module.p,
|
| 721 |
-
self.relu_dropout_module.p,
|
| 722 |
-
self.input_dropout_module.p,
|
| 723 |
-
self.normalize_before,
|
| 724 |
-
)
|
| 725 |
-
)
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
class LightConvDecoderLayer(nn.Module):
|
| 729 |
-
"""Decoder layer block.
|
| 730 |
-
|
| 731 |
-
Args:
|
| 732 |
-
args (argparse.Namespace): parsed command-line arguments
|
| 733 |
-
no_encoder_attn (bool, optional): whether to attend to encoder outputs.
|
| 734 |
-
Default: ``False``
|
| 735 |
-
kernel_size: kernel size of the convolution
|
| 736 |
-
"""
|
| 737 |
-
|
| 738 |
-
def __init__(self, args, no_encoder_attn=False, kernel_size=0):
|
| 739 |
-
super().__init__()
|
| 740 |
-
self.embed_dim = args.decoder_embed_dim
|
| 741 |
-
self.conv_dim = args.decoder_conv_dim
|
| 742 |
-
if args.decoder_glu:
|
| 743 |
-
self.linear1 = Linear(self.embed_dim, 2 * self.conv_dim)
|
| 744 |
-
self.act = nn.GLU()
|
| 745 |
-
else:
|
| 746 |
-
self.linear1 = Linear(self.embed_dim, self.conv_dim)
|
| 747 |
-
self.act = None
|
| 748 |
-
if args.decoder_conv_type == "lightweight":
|
| 749 |
-
self.conv = LightweightConv(
|
| 750 |
-
self.conv_dim,
|
| 751 |
-
kernel_size,
|
| 752 |
-
padding_l=kernel_size - 1,
|
| 753 |
-
weight_softmax=args.weight_softmax,
|
| 754 |
-
num_heads=args.decoder_attention_heads,
|
| 755 |
-
weight_dropout=args.weight_dropout,
|
| 756 |
-
)
|
| 757 |
-
elif args.decoder_conv_type == "dynamic":
|
| 758 |
-
self.conv = DynamicConv(
|
| 759 |
-
self.conv_dim,
|
| 760 |
-
kernel_size,
|
| 761 |
-
padding_l=kernel_size - 1,
|
| 762 |
-
weight_softmax=args.weight_softmax,
|
| 763 |
-
num_heads=args.decoder_attention_heads,
|
| 764 |
-
weight_dropout=args.weight_dropout,
|
| 765 |
-
)
|
| 766 |
-
else:
|
| 767 |
-
raise NotImplementedError
|
| 768 |
-
self.linear2 = Linear(self.conv_dim, self.embed_dim)
|
| 769 |
-
|
| 770 |
-
self.dropout_module = FairseqDropout(
|
| 771 |
-
args.dropout, module_name=self.__class__.__name__
|
| 772 |
-
)
|
| 773 |
-
self.relu_dropout_module = FairseqDropout(
|
| 774 |
-
args.relu_dropout, module_name=self.__class__.__name__
|
| 775 |
-
)
|
| 776 |
-
self.input_dropout_module = FairseqDropout(
|
| 777 |
-
args.input_dropout, module_name=self.__class__.__name__
|
| 778 |
-
)
|
| 779 |
-
self.normalize_before = args.decoder_normalize_before
|
| 780 |
-
|
| 781 |
-
self.conv_layer_norm = LayerNorm(self.embed_dim)
|
| 782 |
-
|
| 783 |
-
if no_encoder_attn:
|
| 784 |
-
self.encoder_attn = None
|
| 785 |
-
self.encoder_attn_layer_norm = None
|
| 786 |
-
else:
|
| 787 |
-
self.encoder_attn = MultiheadAttention(
|
| 788 |
-
self.embed_dim,
|
| 789 |
-
args.decoder_attention_heads,
|
| 790 |
-
dropout=args.attention_dropout,
|
| 791 |
-
encoder_decoder_attention=True,
|
| 792 |
-
)
|
| 793 |
-
self.encoder_attn_layer_norm = LayerNorm(self.embed_dim)
|
| 794 |
-
|
| 795 |
-
self.fc1 = Linear(self.embed_dim, args.decoder_ffn_embed_dim)
|
| 796 |
-
self.fc2 = Linear(args.decoder_ffn_embed_dim, self.embed_dim)
|
| 797 |
-
|
| 798 |
-
self.final_layer_norm = LayerNorm(self.embed_dim)
|
| 799 |
-
self.need_attn = True
|
| 800 |
-
|
| 801 |
-
def forward(
|
| 802 |
-
self,
|
| 803 |
-
x,
|
| 804 |
-
encoder_out,
|
| 805 |
-
encoder_padding_mask,
|
| 806 |
-
incremental_state,
|
| 807 |
-
prev_conv_state=None,
|
| 808 |
-
prev_attn_state=None,
|
| 809 |
-
conv_mask=None,
|
| 810 |
-
conv_padding_mask=None,
|
| 811 |
-
):
|
| 812 |
-
"""
|
| 813 |
-
Args:
|
| 814 |
-
x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
|
| 815 |
-
encoder_padding_mask (ByteTensor): binary ByteTensor of shape
|
| 816 |
-
`(batch, src_len)` where padding elements are indicated by ``1``.
|
| 817 |
-
|
| 818 |
-
Returns:
|
| 819 |
-
encoded output of shape `(batch, src_len, embed_dim)`
|
| 820 |
-
"""
|
| 821 |
-
residual = x
|
| 822 |
-
x = self.maybe_layer_norm(self.conv_layer_norm, x, before=True)
|
| 823 |
-
if prev_conv_state is not None:
|
| 824 |
-
if incremental_state is None:
|
| 825 |
-
incremental_state = {}
|
| 826 |
-
self.conv._set_input_buffer(incremental_state, prev_conv_state)
|
| 827 |
-
x = self.input_dropout_module(x)
|
| 828 |
-
x = self.linear1(x)
|
| 829 |
-
if self.act is not None:
|
| 830 |
-
x = self.act(x)
|
| 831 |
-
x = self.conv(x, incremental_state=incremental_state)
|
| 832 |
-
x = self.linear2(x)
|
| 833 |
-
x = self.dropout_module(x)
|
| 834 |
-
x = residual + x
|
| 835 |
-
x = self.maybe_layer_norm(self.conv_layer_norm, x, after=True)
|
| 836 |
-
|
| 837 |
-
attn = None
|
| 838 |
-
if self.encoder_attn is not None:
|
| 839 |
-
residual = x
|
| 840 |
-
x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, before=True)
|
| 841 |
-
if prev_attn_state is not None:
|
| 842 |
-
if incremental_state is None:
|
| 843 |
-
incremental_state = {}
|
| 844 |
-
prev_key, prev_value = prev_attn_state
|
| 845 |
-
saved_state = {"prev_key": prev_key, "prev_value": prev_value}
|
| 846 |
-
self.encoder_attn._set_input_buffer(incremental_state, saved_state)
|
| 847 |
-
x, attn = self.encoder_attn(
|
| 848 |
-
query=x,
|
| 849 |
-
key=encoder_out,
|
| 850 |
-
value=encoder_out,
|
| 851 |
-
key_padding_mask=encoder_padding_mask,
|
| 852 |
-
incremental_state=incremental_state,
|
| 853 |
-
static_kv=True,
|
| 854 |
-
need_weights=(not self.training and self.need_attn),
|
| 855 |
-
)
|
| 856 |
-
x = self.dropout_module(x)
|
| 857 |
-
x = residual + x
|
| 858 |
-
x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, after=True)
|
| 859 |
-
|
| 860 |
-
residual = x
|
| 861 |
-
x = self.maybe_layer_norm(self.final_layer_norm, x, before=True)
|
| 862 |
-
x = F.relu(self.fc1(x))
|
| 863 |
-
x = self.relu_dropout_module(x)
|
| 864 |
-
x = self.fc2(x)
|
| 865 |
-
x = self.dropout_module(x)
|
| 866 |
-
x = residual + x
|
| 867 |
-
x = self.maybe_layer_norm(self.final_layer_norm, x, after=True)
|
| 868 |
-
return x, attn
|
| 869 |
-
|
| 870 |
-
def maybe_layer_norm(self, layer_norm, x, before=False, after=False):
|
| 871 |
-
assert before ^ after
|
| 872 |
-
if after ^ self.normalize_before:
|
| 873 |
-
return layer_norm(x)
|
| 874 |
-
else:
|
| 875 |
-
return x
|
| 876 |
-
|
| 877 |
-
def make_generation_fast_(self, need_attn=False, **kwargs):
|
| 878 |
-
self.need_attn = need_attn
|
| 879 |
-
|
| 880 |
-
def extra_repr(self):
|
| 881 |
-
return (
|
| 882 |
-
"dropout={}, relu_dropout={}, input_dropout={}, normalize_before={}".format(
|
| 883 |
-
self.dropout_module.p,
|
| 884 |
-
self.relu_dropout_module.p,
|
| 885 |
-
self.input_dropout_module.p,
|
| 886 |
-
self.normalize_before,
|
| 887 |
-
)
|
| 888 |
-
)
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
def Embedding(num_embeddings, embedding_dim, padding_idx):
|
| 892 |
-
m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
|
| 893 |
-
nn.init.normal_(m.weight, mean=0, std=embedding_dim**-0.5)
|
| 894 |
-
nn.init.constant_(m.weight[padding_idx], 0)
|
| 895 |
-
return m
|
| 896 |
-
|
| 897 |
-
|
| 898 |
-
def Linear(in_features, out_features, bias=True):
|
| 899 |
-
m = nn.Linear(in_features, out_features, bias)
|
| 900 |
-
nn.init.xavier_uniform_(m.weight)
|
| 901 |
-
if bias:
|
| 902 |
-
nn.init.constant_(m.bias, 0.0)
|
| 903 |
-
return m
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
@register_model_architecture("lightconv", "lightconv")
|
| 907 |
-
def base_architecture(args):
|
| 908 |
-
args.encoder_embed_path = getattr(args, "encoder_embed_path", None)
|
| 909 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
|
| 910 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 2048)
|
| 911 |
-
args.encoder_layers = getattr(args, "encoder_layers", 7)
|
| 912 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8)
|
| 913 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
|
| 914 |
-
args.encoder_learned_pos = getattr(args, "encoder_learned_pos", False)
|
| 915 |
-
args.decoder_embed_path = getattr(args, "decoder_embed_path", None)
|
| 916 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", args.encoder_embed_dim)
|
| 917 |
-
args.decoder_ffn_embed_dim = getattr(
|
| 918 |
-
args, "decoder_ffn_embed_dim", args.encoder_ffn_embed_dim
|
| 919 |
-
)
|
| 920 |
-
args.decoder_layers = getattr(args, "decoder_layers", 6)
|
| 921 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 8)
|
| 922 |
-
args.decoder_normalize_before = getattr(args, "decoder_normalize_before", False)
|
| 923 |
-
args.decoder_learned_pos = getattr(args, "decoder_learned_pos", False)
|
| 924 |
-
args.attention_dropout = getattr(args, "attention_dropout", 0.0)
|
| 925 |
-
args.relu_dropout = getattr(args, "relu_dropout", 0.0)
|
| 926 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 927 |
-
args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
|
| 928 |
-
args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
|
| 929 |
-
args.share_decoder_input_output_embed = getattr(
|
| 930 |
-
args, "share_decoder_input_output_embed", False
|
| 931 |
-
)
|
| 932 |
-
args.share_all_embeddings = getattr(args, "share_all_embeddings", False)
|
| 933 |
-
args.no_token_positional_embeddings = getattr(
|
| 934 |
-
args, "no_token_positional_embeddings", False
|
| 935 |
-
)
|
| 936 |
-
|
| 937 |
-
args.decoder_output_dim = getattr(
|
| 938 |
-
args, "decoder_output_dim", args.decoder_embed_dim
|
| 939 |
-
)
|
| 940 |
-
args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim)
|
| 941 |
-
|
| 942 |
-
args.encoder_conv_dim = getattr(args, "encoder_conv_dim", args.encoder_embed_dim)
|
| 943 |
-
args.decoder_conv_dim = getattr(args, "decoder_conv_dim", args.decoder_embed_dim)
|
| 944 |
-
|
| 945 |
-
args.encoder_kernel_size_list = getattr(
|
| 946 |
-
args, "encoder_kernel_size_list", [3, 7, 15, 31, 31, 31, 31]
|
| 947 |
-
)
|
| 948 |
-
args.decoder_kernel_size_list = getattr(
|
| 949 |
-
args, "decoder_kernel_size_list", [3, 7, 15, 31, 31, 31]
|
| 950 |
-
)
|
| 951 |
-
if len(args.encoder_kernel_size_list) == 1:
|
| 952 |
-
args.encoder_kernel_size_list = (
|
| 953 |
-
args.encoder_kernel_size_list * args.encoder_layers
|
| 954 |
-
)
|
| 955 |
-
if len(args.decoder_kernel_size_list) == 1:
|
| 956 |
-
args.decoder_kernel_size_list = (
|
| 957 |
-
args.decoder_kernel_size_list * args.decoder_layers
|
| 958 |
-
)
|
| 959 |
-
assert (
|
| 960 |
-
len(args.encoder_kernel_size_list) == args.encoder_layers
|
| 961 |
-
), "encoder_kernel_size_list doesn't match encoder_layers"
|
| 962 |
-
assert (
|
| 963 |
-
len(args.decoder_kernel_size_list) == args.decoder_layers
|
| 964 |
-
), "decoder_kernel_size_list doesn't match decoder_layers"
|
| 965 |
-
args.encoder_glu = getattr(args, "encoder_glu", True)
|
| 966 |
-
args.decoder_glu = getattr(args, "decoder_glu", True)
|
| 967 |
-
args.input_dropout = getattr(args, "input_dropout", 0.1)
|
| 968 |
-
args.weight_dropout = getattr(args, "weight_dropout", args.attention_dropout)
|
| 969 |
-
|
| 970 |
-
|
| 971 |
-
@register_model_architecture("lightconv", "lightconv_iwslt_de_en")
|
| 972 |
-
def lightconv_iwslt_de_en(args):
|
| 973 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
|
| 974 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 1024)
|
| 975 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 4)
|
| 976 |
-
args.encoder_layers = getattr(args, "encoder_layers", 7)
|
| 977 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 512)
|
| 978 |
-
args.decoder_ffn_embed_dim = getattr(args, "decoder_ffn_embed_dim", 1024)
|
| 979 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 4)
|
| 980 |
-
args.decoder_layers = getattr(args, "decoder_layers", 6)
|
| 981 |
-
args.attention_dropout = getattr(args, "attention_dropout", 0.1)
|
| 982 |
-
args.weight_dropout = getattr(args, "weight_dropout", 0.1)
|
| 983 |
-
args.encoder_glu = getattr(args, "encoder_glu", False)
|
| 984 |
-
args.decoder_glu = getattr(args, "decoder_glu", False)
|
| 985 |
-
args.input_dropout = getattr(args, "input_dropout", 0.0)
|
| 986 |
-
base_architecture(args)
|
| 987 |
-
|
| 988 |
-
|
| 989 |
-
@register_model_architecture("lightconv", "lightconv_wmt_en_de")
|
| 990 |
-
def lightconv_wmt_en_de(args):
|
| 991 |
-
base_architecture(args)
|
| 992 |
-
|
| 993 |
-
|
| 994 |
-
@register_model_architecture("lightconv", "lightconv_wmt_en_de_big")
|
| 995 |
-
def lightconv_wmt_en_de_big(args):
|
| 996 |
-
args.attention_dropout = getattr(args, "attention_dropout", 0.1)
|
| 997 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 1024)
|
| 998 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4096)
|
| 999 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 16)
|
| 1000 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
|
| 1001 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 1024)
|
| 1002 |
-
args.decoder_ffn_embed_dim = getattr(args, "decoder_ffn_embed_dim", 4096)
|
| 1003 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 16)
|
| 1004 |
-
args.dropout = getattr(args, "dropout", 0.3)
|
| 1005 |
-
base_architecture(args)
|
| 1006 |
-
|
| 1007 |
-
|
| 1008 |
-
@register_model_architecture("lightconv", "lightconv_wmt_en_fr_big")
|
| 1009 |
-
def lightconv_wmt_en_fr_big(args):
|
| 1010 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 1011 |
-
lightconv_wmt_en_de_big(args)
|
| 1012 |
-
|
| 1013 |
-
|
| 1014 |
-
@register_model_architecture("lightconv", "lightconv_wmt_zh_en_big")
|
| 1015 |
-
def lightconv_wmt_zh_en_big(args):
|
| 1016 |
-
args.dropout = getattr(args, "dropout", 0.2)
|
| 1017 |
-
args.attention_dropout = getattr(args, "attention_dropout", 0.2)
|
| 1018 |
-
args.weight_dropout = getattr(args, "weight_dropout", 0.2)
|
| 1019 |
-
lightconv_wmt_en_de_big(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/lightconv_lm.py
DELETED
|
@@ -1,306 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
from fairseq import utils
|
| 7 |
-
from fairseq.models import (
|
| 8 |
-
FairseqLanguageModel,
|
| 9 |
-
register_model,
|
| 10 |
-
register_model_architecture,
|
| 11 |
-
)
|
| 12 |
-
from fairseq.models.lightconv import Embedding, LightConvDecoder
|
| 13 |
-
from fairseq.modules import AdaptiveInput, CharacterTokenEmbedder
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
@register_model("lightconv_lm")
|
| 17 |
-
class LightConvLanguageModel(FairseqLanguageModel):
|
| 18 |
-
def __init__(self, decoder):
|
| 19 |
-
super().__init__(decoder)
|
| 20 |
-
|
| 21 |
-
@staticmethod
|
| 22 |
-
def add_args(parser):
|
| 23 |
-
"""Add model-specific arguments to the parser."""
|
| 24 |
-
parser.add_argument(
|
| 25 |
-
"--dropout",
|
| 26 |
-
default=0.1,
|
| 27 |
-
type=float,
|
| 28 |
-
metavar="D",
|
| 29 |
-
help="dropout probability",
|
| 30 |
-
)
|
| 31 |
-
parser.add_argument(
|
| 32 |
-
"--attention-dropout",
|
| 33 |
-
default=0.0,
|
| 34 |
-
type=float,
|
| 35 |
-
metavar="D",
|
| 36 |
-
help="dropout probability for attention weights",
|
| 37 |
-
)
|
| 38 |
-
parser.add_argument(
|
| 39 |
-
"--relu-dropout",
|
| 40 |
-
default=0.0,
|
| 41 |
-
type=float,
|
| 42 |
-
metavar="D",
|
| 43 |
-
help="dropout probability after ReLU in FFN",
|
| 44 |
-
)
|
| 45 |
-
parser.add_argument(
|
| 46 |
-
"--input-dropout",
|
| 47 |
-
type=float,
|
| 48 |
-
metavar="D",
|
| 49 |
-
help="dropout probability of the inputs",
|
| 50 |
-
)
|
| 51 |
-
parser.add_argument(
|
| 52 |
-
"--decoder-embed-dim",
|
| 53 |
-
type=int,
|
| 54 |
-
metavar="N",
|
| 55 |
-
help="decoder embedding dimension",
|
| 56 |
-
)
|
| 57 |
-
parser.add_argument(
|
| 58 |
-
"--decoder-output-dim",
|
| 59 |
-
type=int,
|
| 60 |
-
metavar="N",
|
| 61 |
-
help="decoder output dimension",
|
| 62 |
-
)
|
| 63 |
-
parser.add_argument(
|
| 64 |
-
"--decoder-input-dim", type=int, metavar="N", help="decoder input dimension"
|
| 65 |
-
)
|
| 66 |
-
parser.add_argument(
|
| 67 |
-
"--decoder-ffn-embed-dim",
|
| 68 |
-
type=int,
|
| 69 |
-
metavar="N",
|
| 70 |
-
help="decoder embedding dimension for FFN",
|
| 71 |
-
)
|
| 72 |
-
parser.add_argument(
|
| 73 |
-
"--decoder-layers", type=int, metavar="N", help="num decoder layers"
|
| 74 |
-
)
|
| 75 |
-
parser.add_argument(
|
| 76 |
-
"--decoder-attention-heads",
|
| 77 |
-
type=int,
|
| 78 |
-
metavar="N",
|
| 79 |
-
help="num decoder attention heads or LightConv/DynamicConv heads",
|
| 80 |
-
)
|
| 81 |
-
parser.add_argument(
|
| 82 |
-
"--decoder-normalize-before",
|
| 83 |
-
default=False,
|
| 84 |
-
action="store_true",
|
| 85 |
-
help="apply layernorm before each decoder block",
|
| 86 |
-
)
|
| 87 |
-
parser.add_argument(
|
| 88 |
-
"--adaptive-softmax-cutoff",
|
| 89 |
-
metavar="EXPR",
|
| 90 |
-
help="comma separated list of adaptive softmax cutoff points. "
|
| 91 |
-
"Must be used with adaptive_loss criterion",
|
| 92 |
-
)
|
| 93 |
-
parser.add_argument(
|
| 94 |
-
"--adaptive-softmax-dropout",
|
| 95 |
-
type=float,
|
| 96 |
-
metavar="D",
|
| 97 |
-
help="sets adaptive softmax dropout for the tail projections",
|
| 98 |
-
)
|
| 99 |
-
parser.add_argument(
|
| 100 |
-
"--adaptive-softmax-factor",
|
| 101 |
-
type=float,
|
| 102 |
-
metavar="N",
|
| 103 |
-
help="adaptive input factor",
|
| 104 |
-
)
|
| 105 |
-
parser.add_argument(
|
| 106 |
-
"--no-token-positional-embeddings",
|
| 107 |
-
default=False,
|
| 108 |
-
action="store_true",
|
| 109 |
-
help="if set, disables positional embeddings (outside self attention)",
|
| 110 |
-
)
|
| 111 |
-
parser.add_argument(
|
| 112 |
-
"--share-decoder-input-output-embed",
|
| 113 |
-
default=False,
|
| 114 |
-
action="store_true",
|
| 115 |
-
help="share decoder input and output embeddings",
|
| 116 |
-
)
|
| 117 |
-
parser.add_argument(
|
| 118 |
-
"--character-embeddings",
|
| 119 |
-
default=False,
|
| 120 |
-
action="store_true",
|
| 121 |
-
help="if set, uses character embedding convolutions to produce token embeddings",
|
| 122 |
-
)
|
| 123 |
-
parser.add_argument(
|
| 124 |
-
"--character-filters",
|
| 125 |
-
type=str,
|
| 126 |
-
metavar="LIST",
|
| 127 |
-
default="[(1, 64), (2, 128), (3, 192), (4, 256), (5, 256), (6, 256), (7, 256)]",
|
| 128 |
-
help="size of character embeddings",
|
| 129 |
-
)
|
| 130 |
-
parser.add_argument(
|
| 131 |
-
"--character-embedding-dim",
|
| 132 |
-
type=int,
|
| 133 |
-
metavar="N",
|
| 134 |
-
default=4,
|
| 135 |
-
help="size of character embeddings",
|
| 136 |
-
)
|
| 137 |
-
parser.add_argument(
|
| 138 |
-
"--char-embedder-highway-layers",
|
| 139 |
-
type=int,
|
| 140 |
-
metavar="N",
|
| 141 |
-
default=2,
|
| 142 |
-
help="number of highway layers for character token embeddder",
|
| 143 |
-
)
|
| 144 |
-
parser.add_argument(
|
| 145 |
-
"--adaptive-input",
|
| 146 |
-
default=False,
|
| 147 |
-
action="store_true",
|
| 148 |
-
help="if set, uses adaptive input",
|
| 149 |
-
)
|
| 150 |
-
parser.add_argument(
|
| 151 |
-
"--adaptive-input-factor",
|
| 152 |
-
type=float,
|
| 153 |
-
metavar="N",
|
| 154 |
-
help="adaptive input factor",
|
| 155 |
-
)
|
| 156 |
-
parser.add_argument(
|
| 157 |
-
"--adaptive-input-cutoff",
|
| 158 |
-
metavar="EXPR",
|
| 159 |
-
help="comma separated list of adaptive input cutoff points.",
|
| 160 |
-
)
|
| 161 |
-
parser.add_argument(
|
| 162 |
-
"--tie-adaptive-weights",
|
| 163 |
-
action="store_true",
|
| 164 |
-
help="if set, ties the weights of adaptive softmax and adaptive input",
|
| 165 |
-
)
|
| 166 |
-
parser.add_argument(
|
| 167 |
-
"--tie-adaptive-proj",
|
| 168 |
-
action="store_true",
|
| 169 |
-
help="if set, ties the projection weights of adaptive softmax and adaptive input",
|
| 170 |
-
)
|
| 171 |
-
parser.add_argument(
|
| 172 |
-
"--decoder-learned-pos",
|
| 173 |
-
action="store_true",
|
| 174 |
-
help="use learned positional embeddings in the decoder",
|
| 175 |
-
)
|
| 176 |
-
|
| 177 |
-
"""LightConv and DynamicConv arguments"""
|
| 178 |
-
parser.add_argument(
|
| 179 |
-
"--decoder-kernel-size-list",
|
| 180 |
-
type=lambda x: utils.eval_str_list(x, int),
|
| 181 |
-
help='list of kernel size (default: "[3,7,15,31,31,31]")',
|
| 182 |
-
)
|
| 183 |
-
parser.add_argument(
|
| 184 |
-
"--decoder-glu", type=utils.eval_bool, help="glu after in proj"
|
| 185 |
-
)
|
| 186 |
-
parser.add_argument(
|
| 187 |
-
"--decoder-conv-type",
|
| 188 |
-
default="dynamic",
|
| 189 |
-
type=str,
|
| 190 |
-
choices=["dynamic", "lightweight"],
|
| 191 |
-
help="type of convolution",
|
| 192 |
-
)
|
| 193 |
-
parser.add_argument("--weight-softmax", default=True, type=utils.eval_bool)
|
| 194 |
-
parser.add_argument(
|
| 195 |
-
"--weight-dropout",
|
| 196 |
-
type=float,
|
| 197 |
-
metavar="D",
|
| 198 |
-
help="dropout probability for conv weights",
|
| 199 |
-
)
|
| 200 |
-
|
| 201 |
-
@classmethod
|
| 202 |
-
def build_model(cls, args, task):
|
| 203 |
-
"""Build a new model instance."""
|
| 204 |
-
|
| 205 |
-
# make sure all arguments are present in older models
|
| 206 |
-
base_lm_architecture(args)
|
| 207 |
-
|
| 208 |
-
if getattr(args, "max_source_positions", None) is None:
|
| 209 |
-
args.max_source_positions = args.tokens_per_sample
|
| 210 |
-
if getattr(args, "max_target_positions", None) is None:
|
| 211 |
-
args.max_target_positions = args.tokens_per_sample
|
| 212 |
-
|
| 213 |
-
if args.character_embeddings:
|
| 214 |
-
embed_tokens = CharacterTokenEmbedder(
|
| 215 |
-
task.dictionary,
|
| 216 |
-
eval(args.character_filters),
|
| 217 |
-
args.character_embedding_dim,
|
| 218 |
-
args.decoder_embed_dim,
|
| 219 |
-
args.char_embedder_highway_layers,
|
| 220 |
-
)
|
| 221 |
-
elif args.adaptive_input:
|
| 222 |
-
embed_tokens = AdaptiveInput(
|
| 223 |
-
len(task.dictionary),
|
| 224 |
-
task.dictionary.pad(),
|
| 225 |
-
args.decoder_input_dim,
|
| 226 |
-
args.adaptive_input_factor,
|
| 227 |
-
args.decoder_embed_dim,
|
| 228 |
-
utils.eval_str_list(args.adaptive_input_cutoff, type=int),
|
| 229 |
-
)
|
| 230 |
-
else:
|
| 231 |
-
embed_tokens = Embedding(
|
| 232 |
-
len(task.dictionary), args.decoder_input_dim, task.dictionary.pad()
|
| 233 |
-
)
|
| 234 |
-
|
| 235 |
-
if args.tie_adaptive_weights:
|
| 236 |
-
assert args.adaptive_input
|
| 237 |
-
assert args.adaptive_input_factor == args.adaptive_softmax_factor
|
| 238 |
-
assert (
|
| 239 |
-
args.adaptive_softmax_cutoff == args.adaptive_input_cutoff
|
| 240 |
-
), "{} != {}".format(
|
| 241 |
-
args.adaptive_softmax_cutoff, args.adaptive_input_cutoff
|
| 242 |
-
)
|
| 243 |
-
assert args.decoder_input_dim == args.decoder_output_dim
|
| 244 |
-
|
| 245 |
-
decoder = LightConvDecoder(
|
| 246 |
-
args,
|
| 247 |
-
task.output_dictionary,
|
| 248 |
-
embed_tokens,
|
| 249 |
-
no_encoder_attn=True,
|
| 250 |
-
final_norm=False,
|
| 251 |
-
)
|
| 252 |
-
return LightConvLanguageModel(decoder)
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
@register_model_architecture("lightconv_lm", "lightconv_lm")
|
| 256 |
-
def base_lm_architecture(args):
|
| 257 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 512)
|
| 258 |
-
args.decoder_ffn_embed_dim = getattr(args, "decoder_ffn_embed_dim", 2048)
|
| 259 |
-
args.decoder_layers = getattr(args, "decoder_layers", 6)
|
| 260 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 8)
|
| 261 |
-
args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
|
| 262 |
-
args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
|
| 263 |
-
args.adaptive_softmax_factor = getattr(args, "adaptive_softmax_factor", 4)
|
| 264 |
-
args.decoder_learned_pos = getattr(args, "decoder_learned_pos", False)
|
| 265 |
-
|
| 266 |
-
args.character_embeddings = getattr(args, "character_embeddings", False)
|
| 267 |
-
|
| 268 |
-
args.decoder_output_dim = getattr(
|
| 269 |
-
args, "decoder_output_dim", args.decoder_embed_dim
|
| 270 |
-
)
|
| 271 |
-
args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim)
|
| 272 |
-
args.decoder_conv_dim = getattr(args, "decoder_conv_dim", args.decoder_embed_dim)
|
| 273 |
-
|
| 274 |
-
# The model training is not stable without this
|
| 275 |
-
args.decoder_normalize_before = True
|
| 276 |
-
|
| 277 |
-
args.adaptive_input = getattr(args, "adaptive_input", False)
|
| 278 |
-
args.adaptive_input_factor = getattr(args, "adaptive_input_factor", 4)
|
| 279 |
-
args.adaptive_input_cutoff = getattr(args, "adaptive_input_cutoff", None)
|
| 280 |
-
|
| 281 |
-
args.tie_adaptive_weights = getattr(args, "tie_adaptive_weights", False)
|
| 282 |
-
args.tie_adaptive_proj = getattr(args, "tie_adaptive_proj", False)
|
| 283 |
-
|
| 284 |
-
args.decoder_kernel_size_list = getattr(
|
| 285 |
-
args, "decoder_kernel_size_list", [3, 7, 15, 31, 31, 31]
|
| 286 |
-
)
|
| 287 |
-
if len(args.decoder_kernel_size_list) == 1:
|
| 288 |
-
args.decoder_kernel_size_list = (
|
| 289 |
-
args.decoder_kernel_size_list * args.decoder_layers
|
| 290 |
-
)
|
| 291 |
-
assert (
|
| 292 |
-
len(args.decoder_kernel_size_list) == args.decoder_layers
|
| 293 |
-
), "decoder_kernel_size_list doesn't match decoder_layers"
|
| 294 |
-
args.decoder_glu = getattr(args, "decoder_glu", True)
|
| 295 |
-
args.input_dropout = getattr(args, "input_dropout", 0.1)
|
| 296 |
-
args.weight_dropout = getattr(args, "weight_dropout", args.attention_dropout)
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
@register_model_architecture("lightconv_lm", "lightconv_lm_gbw")
|
| 300 |
-
def lightconv_lm_gbw(args):
|
| 301 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 512)
|
| 302 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 303 |
-
args.attention_dropout = getattr(args, "attention_dropout", 0.1)
|
| 304 |
-
args.decoder_ffn_embed_dim = getattr(args, "decoder_ffn_embed_dim", 4096)
|
| 305 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 16)
|
| 306 |
-
base_lm_architecture(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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/safeear/safeear_repo/fairseq_ours/fairseq/models/lstm.py
DELETED
|
@@ -1,754 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
from typing import Dict, List, Optional, Tuple
|
| 7 |
-
|
| 8 |
-
import torch
|
| 9 |
-
import torch.nn as nn
|
| 10 |
-
import torch.nn.functional as F
|
| 11 |
-
from fairseq import utils
|
| 12 |
-
from fairseq.models import (
|
| 13 |
-
FairseqEncoder,
|
| 14 |
-
FairseqEncoderDecoderModel,
|
| 15 |
-
FairseqIncrementalDecoder,
|
| 16 |
-
register_model,
|
| 17 |
-
register_model_architecture,
|
| 18 |
-
)
|
| 19 |
-
from fairseq.modules import AdaptiveSoftmax, FairseqDropout
|
| 20 |
-
from torch import Tensor
|
| 21 |
-
|
| 22 |
-
DEFAULT_MAX_SOURCE_POSITIONS = 1e5
|
| 23 |
-
DEFAULT_MAX_TARGET_POSITIONS = 1e5
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
@register_model("lstm")
|
| 27 |
-
class LSTMModel(FairseqEncoderDecoderModel):
|
| 28 |
-
def __init__(self, encoder, decoder):
|
| 29 |
-
super().__init__(encoder, decoder)
|
| 30 |
-
|
| 31 |
-
@staticmethod
|
| 32 |
-
def add_args(parser):
|
| 33 |
-
"""Add model-specific arguments to the parser."""
|
| 34 |
-
# fmt: off
|
| 35 |
-
parser.add_argument('--dropout', type=float, metavar='D',
|
| 36 |
-
help='dropout probability')
|
| 37 |
-
parser.add_argument('--encoder-embed-dim', type=int, metavar='N',
|
| 38 |
-
help='encoder embedding dimension')
|
| 39 |
-
parser.add_argument('--encoder-embed-path', type=str, metavar='STR',
|
| 40 |
-
help='path to pre-trained encoder embedding')
|
| 41 |
-
parser.add_argument('--encoder-freeze-embed', action='store_true',
|
| 42 |
-
help='freeze encoder embeddings')
|
| 43 |
-
parser.add_argument('--encoder-hidden-size', type=int, metavar='N',
|
| 44 |
-
help='encoder hidden size')
|
| 45 |
-
parser.add_argument('--encoder-layers', type=int, metavar='N',
|
| 46 |
-
help='number of encoder layers')
|
| 47 |
-
parser.add_argument('--encoder-bidirectional', action='store_true',
|
| 48 |
-
help='make all layers of encoder bidirectional')
|
| 49 |
-
parser.add_argument('--decoder-embed-dim', type=int, metavar='N',
|
| 50 |
-
help='decoder embedding dimension')
|
| 51 |
-
parser.add_argument('--decoder-embed-path', type=str, metavar='STR',
|
| 52 |
-
help='path to pre-trained decoder embedding')
|
| 53 |
-
parser.add_argument('--decoder-freeze-embed', action='store_true',
|
| 54 |
-
help='freeze decoder embeddings')
|
| 55 |
-
parser.add_argument('--decoder-hidden-size', type=int, metavar='N',
|
| 56 |
-
help='decoder hidden size')
|
| 57 |
-
parser.add_argument('--decoder-layers', type=int, metavar='N',
|
| 58 |
-
help='number of decoder layers')
|
| 59 |
-
parser.add_argument('--decoder-out-embed-dim', type=int, metavar='N',
|
| 60 |
-
help='decoder output embedding dimension')
|
| 61 |
-
parser.add_argument('--decoder-attention', type=str, metavar='BOOL',
|
| 62 |
-
help='decoder attention')
|
| 63 |
-
parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR',
|
| 64 |
-
help='comma separated list of adaptive softmax cutoff points. '
|
| 65 |
-
'Must be used with adaptive_loss criterion')
|
| 66 |
-
parser.add_argument('--share-decoder-input-output-embed', default=False,
|
| 67 |
-
action='store_true',
|
| 68 |
-
help='share decoder input and output embeddings')
|
| 69 |
-
parser.add_argument('--share-all-embeddings', default=False, action='store_true',
|
| 70 |
-
help='share encoder, decoder and output embeddings'
|
| 71 |
-
' (requires shared dictionary and embed dim)')
|
| 72 |
-
|
| 73 |
-
# Granular dropout settings (if not specified these default to --dropout)
|
| 74 |
-
parser.add_argument('--encoder-dropout-in', type=float, metavar='D',
|
| 75 |
-
help='dropout probability for encoder input embedding')
|
| 76 |
-
parser.add_argument('--encoder-dropout-out', type=float, metavar='D',
|
| 77 |
-
help='dropout probability for encoder output')
|
| 78 |
-
parser.add_argument('--decoder-dropout-in', type=float, metavar='D',
|
| 79 |
-
help='dropout probability for decoder input embedding')
|
| 80 |
-
parser.add_argument('--decoder-dropout-out', type=float, metavar='D',
|
| 81 |
-
help='dropout probability for decoder output')
|
| 82 |
-
# fmt: on
|
| 83 |
-
|
| 84 |
-
@classmethod
|
| 85 |
-
def build_model(cls, args, task):
|
| 86 |
-
"""Build a new model instance."""
|
| 87 |
-
# make sure that all args are properly defaulted (in case there are any new ones)
|
| 88 |
-
base_architecture(args)
|
| 89 |
-
|
| 90 |
-
if args.encoder_layers != args.decoder_layers:
|
| 91 |
-
raise ValueError("--encoder-layers must match --decoder-layers")
|
| 92 |
-
|
| 93 |
-
max_source_positions = getattr(
|
| 94 |
-
args, "max_source_positions", DEFAULT_MAX_SOURCE_POSITIONS
|
| 95 |
-
)
|
| 96 |
-
max_target_positions = getattr(
|
| 97 |
-
args, "max_target_positions", DEFAULT_MAX_TARGET_POSITIONS
|
| 98 |
-
)
|
| 99 |
-
|
| 100 |
-
def load_pretrained_embedding_from_file(embed_path, dictionary, embed_dim):
|
| 101 |
-
num_embeddings = len(dictionary)
|
| 102 |
-
padding_idx = dictionary.pad()
|
| 103 |
-
embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx)
|
| 104 |
-
embed_dict = utils.parse_embedding(embed_path)
|
| 105 |
-
utils.print_embed_overlap(embed_dict, dictionary)
|
| 106 |
-
return utils.load_embedding(embed_dict, dictionary, embed_tokens)
|
| 107 |
-
|
| 108 |
-
if args.encoder_embed_path:
|
| 109 |
-
pretrained_encoder_embed = load_pretrained_embedding_from_file(
|
| 110 |
-
args.encoder_embed_path, task.source_dictionary, args.encoder_embed_dim
|
| 111 |
-
)
|
| 112 |
-
else:
|
| 113 |
-
num_embeddings = len(task.source_dictionary)
|
| 114 |
-
pretrained_encoder_embed = Embedding(
|
| 115 |
-
num_embeddings, args.encoder_embed_dim, task.source_dictionary.pad()
|
| 116 |
-
)
|
| 117 |
-
|
| 118 |
-
if args.share_all_embeddings:
|
| 119 |
-
# double check all parameters combinations are valid
|
| 120 |
-
if task.source_dictionary != task.target_dictionary:
|
| 121 |
-
raise ValueError("--share-all-embeddings requires a joint dictionary")
|
| 122 |
-
if args.decoder_embed_path and (
|
| 123 |
-
args.decoder_embed_path != args.encoder_embed_path
|
| 124 |
-
):
|
| 125 |
-
raise ValueError(
|
| 126 |
-
"--share-all-embed not compatible with --decoder-embed-path"
|
| 127 |
-
)
|
| 128 |
-
if args.encoder_embed_dim != args.decoder_embed_dim:
|
| 129 |
-
raise ValueError(
|
| 130 |
-
"--share-all-embeddings requires --encoder-embed-dim to "
|
| 131 |
-
"match --decoder-embed-dim"
|
| 132 |
-
)
|
| 133 |
-
pretrained_decoder_embed = pretrained_encoder_embed
|
| 134 |
-
args.share_decoder_input_output_embed = True
|
| 135 |
-
else:
|
| 136 |
-
# separate decoder input embeddings
|
| 137 |
-
pretrained_decoder_embed = None
|
| 138 |
-
if args.decoder_embed_path:
|
| 139 |
-
pretrained_decoder_embed = load_pretrained_embedding_from_file(
|
| 140 |
-
args.decoder_embed_path,
|
| 141 |
-
task.target_dictionary,
|
| 142 |
-
args.decoder_embed_dim,
|
| 143 |
-
)
|
| 144 |
-
# one last double check of parameter combinations
|
| 145 |
-
if args.share_decoder_input_output_embed and (
|
| 146 |
-
args.decoder_embed_dim != args.decoder_out_embed_dim
|
| 147 |
-
):
|
| 148 |
-
raise ValueError(
|
| 149 |
-
"--share-decoder-input-output-embeddings requires "
|
| 150 |
-
"--decoder-embed-dim to match --decoder-out-embed-dim"
|
| 151 |
-
)
|
| 152 |
-
|
| 153 |
-
if args.encoder_freeze_embed:
|
| 154 |
-
pretrained_encoder_embed.weight.requires_grad = False
|
| 155 |
-
if args.decoder_freeze_embed:
|
| 156 |
-
pretrained_decoder_embed.weight.requires_grad = False
|
| 157 |
-
|
| 158 |
-
encoder = LSTMEncoder(
|
| 159 |
-
dictionary=task.source_dictionary,
|
| 160 |
-
embed_dim=args.encoder_embed_dim,
|
| 161 |
-
hidden_size=args.encoder_hidden_size,
|
| 162 |
-
num_layers=args.encoder_layers,
|
| 163 |
-
dropout_in=args.encoder_dropout_in,
|
| 164 |
-
dropout_out=args.encoder_dropout_out,
|
| 165 |
-
bidirectional=args.encoder_bidirectional,
|
| 166 |
-
pretrained_embed=pretrained_encoder_embed,
|
| 167 |
-
max_source_positions=max_source_positions,
|
| 168 |
-
)
|
| 169 |
-
decoder = LSTMDecoder(
|
| 170 |
-
dictionary=task.target_dictionary,
|
| 171 |
-
embed_dim=args.decoder_embed_dim,
|
| 172 |
-
hidden_size=args.decoder_hidden_size,
|
| 173 |
-
out_embed_dim=args.decoder_out_embed_dim,
|
| 174 |
-
num_layers=args.decoder_layers,
|
| 175 |
-
dropout_in=args.decoder_dropout_in,
|
| 176 |
-
dropout_out=args.decoder_dropout_out,
|
| 177 |
-
attention=utils.eval_bool(args.decoder_attention),
|
| 178 |
-
encoder_output_units=encoder.output_units,
|
| 179 |
-
pretrained_embed=pretrained_decoder_embed,
|
| 180 |
-
share_input_output_embed=args.share_decoder_input_output_embed,
|
| 181 |
-
adaptive_softmax_cutoff=(
|
| 182 |
-
utils.eval_str_list(args.adaptive_softmax_cutoff, type=int)
|
| 183 |
-
if args.criterion == "adaptive_loss"
|
| 184 |
-
else None
|
| 185 |
-
),
|
| 186 |
-
max_target_positions=max_target_positions,
|
| 187 |
-
residuals=False,
|
| 188 |
-
)
|
| 189 |
-
return cls(encoder, decoder)
|
| 190 |
-
|
| 191 |
-
def forward(
|
| 192 |
-
self,
|
| 193 |
-
src_tokens,
|
| 194 |
-
src_lengths,
|
| 195 |
-
prev_output_tokens,
|
| 196 |
-
incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
|
| 197 |
-
):
|
| 198 |
-
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths)
|
| 199 |
-
decoder_out = self.decoder(
|
| 200 |
-
prev_output_tokens,
|
| 201 |
-
encoder_out=encoder_out,
|
| 202 |
-
incremental_state=incremental_state,
|
| 203 |
-
)
|
| 204 |
-
return decoder_out
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
class LSTMEncoder(FairseqEncoder):
|
| 208 |
-
"""LSTM encoder."""
|
| 209 |
-
|
| 210 |
-
def __init__(
|
| 211 |
-
self,
|
| 212 |
-
dictionary,
|
| 213 |
-
embed_dim=512,
|
| 214 |
-
hidden_size=512,
|
| 215 |
-
num_layers=1,
|
| 216 |
-
dropout_in=0.1,
|
| 217 |
-
dropout_out=0.1,
|
| 218 |
-
bidirectional=False,
|
| 219 |
-
left_pad=True,
|
| 220 |
-
pretrained_embed=None,
|
| 221 |
-
padding_idx=None,
|
| 222 |
-
max_source_positions=DEFAULT_MAX_SOURCE_POSITIONS,
|
| 223 |
-
):
|
| 224 |
-
super().__init__(dictionary)
|
| 225 |
-
self.num_layers = num_layers
|
| 226 |
-
self.dropout_in_module = FairseqDropout(
|
| 227 |
-
dropout_in * 1.0, module_name=self.__class__.__name__
|
| 228 |
-
)
|
| 229 |
-
self.dropout_out_module = FairseqDropout(
|
| 230 |
-
dropout_out * 1.0, module_name=self.__class__.__name__
|
| 231 |
-
)
|
| 232 |
-
self.bidirectional = bidirectional
|
| 233 |
-
self.hidden_size = hidden_size
|
| 234 |
-
self.max_source_positions = max_source_positions
|
| 235 |
-
|
| 236 |
-
num_embeddings = len(dictionary)
|
| 237 |
-
self.padding_idx = padding_idx if padding_idx is not None else dictionary.pad()
|
| 238 |
-
if pretrained_embed is None:
|
| 239 |
-
self.embed_tokens = Embedding(num_embeddings, embed_dim, self.padding_idx)
|
| 240 |
-
else:
|
| 241 |
-
self.embed_tokens = pretrained_embed
|
| 242 |
-
|
| 243 |
-
self.lstm = LSTM(
|
| 244 |
-
input_size=embed_dim,
|
| 245 |
-
hidden_size=hidden_size,
|
| 246 |
-
num_layers=num_layers,
|
| 247 |
-
dropout=self.dropout_out_module.p if num_layers > 1 else 0.0,
|
| 248 |
-
bidirectional=bidirectional,
|
| 249 |
-
)
|
| 250 |
-
self.left_pad = left_pad
|
| 251 |
-
|
| 252 |
-
self.output_units = hidden_size
|
| 253 |
-
if bidirectional:
|
| 254 |
-
self.output_units *= 2
|
| 255 |
-
|
| 256 |
-
def forward(
|
| 257 |
-
self,
|
| 258 |
-
src_tokens: Tensor,
|
| 259 |
-
src_lengths: Tensor,
|
| 260 |
-
enforce_sorted: bool = True,
|
| 261 |
-
):
|
| 262 |
-
"""
|
| 263 |
-
Args:
|
| 264 |
-
src_tokens (LongTensor): tokens in the source language of
|
| 265 |
-
shape `(batch, src_len)`
|
| 266 |
-
src_lengths (LongTensor): lengths of each source sentence of
|
| 267 |
-
shape `(batch)`
|
| 268 |
-
enforce_sorted (bool, optional): if True, `src_tokens` is
|
| 269 |
-
expected to contain sequences sorted by length in a
|
| 270 |
-
decreasing order. If False, this condition is not
|
| 271 |
-
required. Default: True.
|
| 272 |
-
"""
|
| 273 |
-
if self.left_pad:
|
| 274 |
-
# nn.utils.rnn.pack_padded_sequence requires right-padding;
|
| 275 |
-
# convert left-padding to right-padding
|
| 276 |
-
src_tokens = utils.convert_padding_direction(
|
| 277 |
-
src_tokens,
|
| 278 |
-
torch.zeros_like(src_tokens).fill_(self.padding_idx),
|
| 279 |
-
left_to_right=True,
|
| 280 |
-
)
|
| 281 |
-
|
| 282 |
-
bsz, seqlen = src_tokens.size()
|
| 283 |
-
|
| 284 |
-
# embed tokens
|
| 285 |
-
x = self.embed_tokens(src_tokens)
|
| 286 |
-
x = self.dropout_in_module(x)
|
| 287 |
-
|
| 288 |
-
# B x T x C -> T x B x C
|
| 289 |
-
x = x.transpose(0, 1)
|
| 290 |
-
|
| 291 |
-
# pack embedded source tokens into a PackedSequence
|
| 292 |
-
packed_x = nn.utils.rnn.pack_padded_sequence(
|
| 293 |
-
x, src_lengths.cpu(), enforce_sorted=enforce_sorted
|
| 294 |
-
)
|
| 295 |
-
|
| 296 |
-
# apply LSTM
|
| 297 |
-
if self.bidirectional:
|
| 298 |
-
state_size = 2 * self.num_layers, bsz, self.hidden_size
|
| 299 |
-
else:
|
| 300 |
-
state_size = self.num_layers, bsz, self.hidden_size
|
| 301 |
-
h0 = x.new_zeros(*state_size)
|
| 302 |
-
c0 = x.new_zeros(*state_size)
|
| 303 |
-
packed_outs, (final_hiddens, final_cells) = self.lstm(packed_x, (h0, c0))
|
| 304 |
-
|
| 305 |
-
# unpack outputs and apply dropout
|
| 306 |
-
x, _ = nn.utils.rnn.pad_packed_sequence(
|
| 307 |
-
packed_outs, padding_value=self.padding_idx * 1.0
|
| 308 |
-
)
|
| 309 |
-
x = self.dropout_out_module(x)
|
| 310 |
-
assert list(x.size()) == [seqlen, bsz, self.output_units]
|
| 311 |
-
|
| 312 |
-
if self.bidirectional:
|
| 313 |
-
final_hiddens = self.combine_bidir(final_hiddens, bsz)
|
| 314 |
-
final_cells = self.combine_bidir(final_cells, bsz)
|
| 315 |
-
|
| 316 |
-
encoder_padding_mask = src_tokens.eq(self.padding_idx).t()
|
| 317 |
-
|
| 318 |
-
return tuple(
|
| 319 |
-
(
|
| 320 |
-
x, # seq_len x batch x hidden
|
| 321 |
-
final_hiddens, # num_layers x batch x num_directions*hidden
|
| 322 |
-
final_cells, # num_layers x batch x num_directions*hidden
|
| 323 |
-
encoder_padding_mask, # seq_len x batch
|
| 324 |
-
)
|
| 325 |
-
)
|
| 326 |
-
|
| 327 |
-
def combine_bidir(self, outs, bsz: int):
|
| 328 |
-
out = outs.view(self.num_layers, 2, bsz, -1).transpose(1, 2).contiguous()
|
| 329 |
-
return out.view(self.num_layers, bsz, -1)
|
| 330 |
-
|
| 331 |
-
def reorder_encoder_out(
|
| 332 |
-
self, encoder_out: Tuple[Tensor, Tensor, Tensor, Tensor], new_order
|
| 333 |
-
):
|
| 334 |
-
return tuple(
|
| 335 |
-
(
|
| 336 |
-
encoder_out[0].index_select(1, new_order),
|
| 337 |
-
encoder_out[1].index_select(1, new_order),
|
| 338 |
-
encoder_out[2].index_select(1, new_order),
|
| 339 |
-
encoder_out[3].index_select(1, new_order),
|
| 340 |
-
)
|
| 341 |
-
)
|
| 342 |
-
|
| 343 |
-
def max_positions(self):
|
| 344 |
-
"""Maximum input length supported by the encoder."""
|
| 345 |
-
return self.max_source_positions
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
class AttentionLayer(nn.Module):
|
| 349 |
-
def __init__(self, input_embed_dim, source_embed_dim, output_embed_dim, bias=False):
|
| 350 |
-
super().__init__()
|
| 351 |
-
|
| 352 |
-
self.input_proj = Linear(input_embed_dim, source_embed_dim, bias=bias)
|
| 353 |
-
self.output_proj = Linear(
|
| 354 |
-
input_embed_dim + source_embed_dim, output_embed_dim, bias=bias
|
| 355 |
-
)
|
| 356 |
-
|
| 357 |
-
def forward(self, input, source_hids, encoder_padding_mask):
|
| 358 |
-
# input: bsz x input_embed_dim
|
| 359 |
-
# source_hids: srclen x bsz x source_embed_dim
|
| 360 |
-
|
| 361 |
-
# x: bsz x source_embed_dim
|
| 362 |
-
x = self.input_proj(input)
|
| 363 |
-
|
| 364 |
-
# compute attention
|
| 365 |
-
attn_scores = (source_hids * x.unsqueeze(0)).sum(dim=2)
|
| 366 |
-
|
| 367 |
-
# don't attend over padding
|
| 368 |
-
if encoder_padding_mask is not None:
|
| 369 |
-
attn_scores = (
|
| 370 |
-
attn_scores.float()
|
| 371 |
-
.masked_fill_(encoder_padding_mask, float("-inf"))
|
| 372 |
-
.type_as(attn_scores)
|
| 373 |
-
) # FP16 support: cast to float and back
|
| 374 |
-
|
| 375 |
-
attn_scores = F.softmax(attn_scores, dim=0) # srclen x bsz
|
| 376 |
-
|
| 377 |
-
# sum weighted sources
|
| 378 |
-
x = (attn_scores.unsqueeze(2) * source_hids).sum(dim=0)
|
| 379 |
-
|
| 380 |
-
x = torch.tanh(self.output_proj(torch.cat((x, input), dim=1)))
|
| 381 |
-
return x, attn_scores
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
class LSTMDecoder(FairseqIncrementalDecoder):
|
| 385 |
-
"""LSTM decoder."""
|
| 386 |
-
|
| 387 |
-
def __init__(
|
| 388 |
-
self,
|
| 389 |
-
dictionary,
|
| 390 |
-
embed_dim=512,
|
| 391 |
-
hidden_size=512,
|
| 392 |
-
out_embed_dim=512,
|
| 393 |
-
num_layers=1,
|
| 394 |
-
dropout_in=0.1,
|
| 395 |
-
dropout_out=0.1,
|
| 396 |
-
attention=True,
|
| 397 |
-
encoder_output_units=512,
|
| 398 |
-
pretrained_embed=None,
|
| 399 |
-
share_input_output_embed=False,
|
| 400 |
-
adaptive_softmax_cutoff=None,
|
| 401 |
-
max_target_positions=DEFAULT_MAX_TARGET_POSITIONS,
|
| 402 |
-
residuals=False,
|
| 403 |
-
):
|
| 404 |
-
super().__init__(dictionary)
|
| 405 |
-
self.dropout_in_module = FairseqDropout(
|
| 406 |
-
dropout_in * 1.0, module_name=self.__class__.__name__
|
| 407 |
-
)
|
| 408 |
-
self.dropout_out_module = FairseqDropout(
|
| 409 |
-
dropout_out * 1.0, module_name=self.__class__.__name__
|
| 410 |
-
)
|
| 411 |
-
self.hidden_size = hidden_size
|
| 412 |
-
self.share_input_output_embed = share_input_output_embed
|
| 413 |
-
self.need_attn = True
|
| 414 |
-
self.max_target_positions = max_target_positions
|
| 415 |
-
self.residuals = residuals
|
| 416 |
-
self.num_layers = num_layers
|
| 417 |
-
|
| 418 |
-
self.adaptive_softmax = None
|
| 419 |
-
num_embeddings = len(dictionary)
|
| 420 |
-
padding_idx = dictionary.pad()
|
| 421 |
-
if pretrained_embed is None:
|
| 422 |
-
self.embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx)
|
| 423 |
-
else:
|
| 424 |
-
self.embed_tokens = pretrained_embed
|
| 425 |
-
|
| 426 |
-
self.encoder_output_units = encoder_output_units
|
| 427 |
-
if encoder_output_units != hidden_size and encoder_output_units != 0:
|
| 428 |
-
self.encoder_hidden_proj = Linear(encoder_output_units, hidden_size)
|
| 429 |
-
self.encoder_cell_proj = Linear(encoder_output_units, hidden_size)
|
| 430 |
-
else:
|
| 431 |
-
self.encoder_hidden_proj = self.encoder_cell_proj = None
|
| 432 |
-
|
| 433 |
-
# disable input feeding if there is no encoder
|
| 434 |
-
# input feeding is described in arxiv.org/abs/1508.04025
|
| 435 |
-
input_feed_size = 0 if encoder_output_units == 0 else hidden_size
|
| 436 |
-
self.layers = nn.ModuleList(
|
| 437 |
-
[
|
| 438 |
-
LSTMCell(
|
| 439 |
-
input_size=input_feed_size + embed_dim
|
| 440 |
-
if layer == 0
|
| 441 |
-
else hidden_size,
|
| 442 |
-
hidden_size=hidden_size,
|
| 443 |
-
)
|
| 444 |
-
for layer in range(num_layers)
|
| 445 |
-
]
|
| 446 |
-
)
|
| 447 |
-
|
| 448 |
-
if attention:
|
| 449 |
-
# TODO make bias configurable
|
| 450 |
-
self.attention = AttentionLayer(
|
| 451 |
-
hidden_size, encoder_output_units, hidden_size, bias=False
|
| 452 |
-
)
|
| 453 |
-
else:
|
| 454 |
-
self.attention = None
|
| 455 |
-
|
| 456 |
-
if hidden_size != out_embed_dim:
|
| 457 |
-
self.additional_fc = Linear(hidden_size, out_embed_dim)
|
| 458 |
-
|
| 459 |
-
if adaptive_softmax_cutoff is not None:
|
| 460 |
-
# setting adaptive_softmax dropout to dropout_out for now but can be redefined
|
| 461 |
-
self.adaptive_softmax = AdaptiveSoftmax(
|
| 462 |
-
num_embeddings,
|
| 463 |
-
hidden_size,
|
| 464 |
-
adaptive_softmax_cutoff,
|
| 465 |
-
dropout=dropout_out,
|
| 466 |
-
)
|
| 467 |
-
elif not self.share_input_output_embed:
|
| 468 |
-
self.fc_out = Linear(out_embed_dim, num_embeddings, dropout=dropout_out)
|
| 469 |
-
|
| 470 |
-
def forward(
|
| 471 |
-
self,
|
| 472 |
-
prev_output_tokens,
|
| 473 |
-
encoder_out: Optional[Tuple[Tensor, Tensor, Tensor, Tensor]] = None,
|
| 474 |
-
incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
|
| 475 |
-
src_lengths: Optional[Tensor] = None,
|
| 476 |
-
):
|
| 477 |
-
x, attn_scores = self.extract_features(
|
| 478 |
-
prev_output_tokens, encoder_out, incremental_state
|
| 479 |
-
)
|
| 480 |
-
return self.output_layer(x), attn_scores
|
| 481 |
-
|
| 482 |
-
def extract_features(
|
| 483 |
-
self,
|
| 484 |
-
prev_output_tokens,
|
| 485 |
-
encoder_out: Optional[Tuple[Tensor, Tensor, Tensor, Tensor]] = None,
|
| 486 |
-
incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
|
| 487 |
-
):
|
| 488 |
-
"""
|
| 489 |
-
Similar to *forward* but only return features.
|
| 490 |
-
"""
|
| 491 |
-
# get outputs from encoder
|
| 492 |
-
if encoder_out is not None:
|
| 493 |
-
encoder_outs = encoder_out[0]
|
| 494 |
-
encoder_hiddens = encoder_out[1]
|
| 495 |
-
encoder_cells = encoder_out[2]
|
| 496 |
-
encoder_padding_mask = encoder_out[3]
|
| 497 |
-
else:
|
| 498 |
-
encoder_outs = torch.empty(0)
|
| 499 |
-
encoder_hiddens = torch.empty(0)
|
| 500 |
-
encoder_cells = torch.empty(0)
|
| 501 |
-
encoder_padding_mask = torch.empty(0)
|
| 502 |
-
srclen = encoder_outs.size(0)
|
| 503 |
-
|
| 504 |
-
if incremental_state is not None and len(incremental_state) > 0:
|
| 505 |
-
prev_output_tokens = prev_output_tokens[:, -1:]
|
| 506 |
-
|
| 507 |
-
bsz, seqlen = prev_output_tokens.size()
|
| 508 |
-
|
| 509 |
-
# embed tokens
|
| 510 |
-
x = self.embed_tokens(prev_output_tokens)
|
| 511 |
-
x = self.dropout_in_module(x)
|
| 512 |
-
|
| 513 |
-
# B x T x C -> T x B x C
|
| 514 |
-
x = x.transpose(0, 1)
|
| 515 |
-
|
| 516 |
-
# initialize previous states (or get from cache during incremental generation)
|
| 517 |
-
if incremental_state is not None and len(incremental_state) > 0:
|
| 518 |
-
prev_hiddens, prev_cells, input_feed = self.get_cached_state(
|
| 519 |
-
incremental_state
|
| 520 |
-
)
|
| 521 |
-
elif encoder_out is not None:
|
| 522 |
-
# setup recurrent cells
|
| 523 |
-
prev_hiddens = [encoder_hiddens[i] for i in range(self.num_layers)]
|
| 524 |
-
prev_cells = [encoder_cells[i] for i in range(self.num_layers)]
|
| 525 |
-
if self.encoder_hidden_proj is not None:
|
| 526 |
-
prev_hiddens = [self.encoder_hidden_proj(y) for y in prev_hiddens]
|
| 527 |
-
prev_cells = [self.encoder_cell_proj(y) for y in prev_cells]
|
| 528 |
-
input_feed = x.new_zeros(bsz, self.hidden_size)
|
| 529 |
-
else:
|
| 530 |
-
# setup zero cells, since there is no encoder
|
| 531 |
-
zero_state = x.new_zeros(bsz, self.hidden_size)
|
| 532 |
-
prev_hiddens = [zero_state for i in range(self.num_layers)]
|
| 533 |
-
prev_cells = [zero_state for i in range(self.num_layers)]
|
| 534 |
-
input_feed = None
|
| 535 |
-
|
| 536 |
-
assert (
|
| 537 |
-
srclen > 0 or self.attention is None
|
| 538 |
-
), "attention is not supported if there are no encoder outputs"
|
| 539 |
-
attn_scores: Optional[Tensor] = (
|
| 540 |
-
x.new_zeros(srclen, seqlen, bsz) if self.attention is not None else None
|
| 541 |
-
)
|
| 542 |
-
outs = []
|
| 543 |
-
for j in range(seqlen):
|
| 544 |
-
# input feeding: concatenate context vector from previous time step
|
| 545 |
-
if input_feed is not None:
|
| 546 |
-
input = torch.cat((x[j, :, :], input_feed), dim=1)
|
| 547 |
-
else:
|
| 548 |
-
input = x[j]
|
| 549 |
-
|
| 550 |
-
for i, rnn in enumerate(self.layers):
|
| 551 |
-
# recurrent cell
|
| 552 |
-
hidden, cell = rnn(input, (prev_hiddens[i], prev_cells[i]))
|
| 553 |
-
|
| 554 |
-
# hidden state becomes the input to the next layer
|
| 555 |
-
input = self.dropout_out_module(hidden)
|
| 556 |
-
if self.residuals:
|
| 557 |
-
input = input + prev_hiddens[i]
|
| 558 |
-
|
| 559 |
-
# save state for next time step
|
| 560 |
-
prev_hiddens[i] = hidden
|
| 561 |
-
prev_cells[i] = cell
|
| 562 |
-
|
| 563 |
-
# apply attention using the last layer's hidden state
|
| 564 |
-
if self.attention is not None:
|
| 565 |
-
assert attn_scores is not None
|
| 566 |
-
out, attn_scores[:, j, :] = self.attention(
|
| 567 |
-
hidden, encoder_outs, encoder_padding_mask
|
| 568 |
-
)
|
| 569 |
-
else:
|
| 570 |
-
out = hidden
|
| 571 |
-
out = self.dropout_out_module(out)
|
| 572 |
-
|
| 573 |
-
# input feeding
|
| 574 |
-
if input_feed is not None:
|
| 575 |
-
input_feed = out
|
| 576 |
-
|
| 577 |
-
# save final output
|
| 578 |
-
outs.append(out)
|
| 579 |
-
|
| 580 |
-
# Stack all the necessary tensors together and store
|
| 581 |
-
prev_hiddens_tensor = torch.stack(prev_hiddens)
|
| 582 |
-
prev_cells_tensor = torch.stack(prev_cells)
|
| 583 |
-
cache_state = torch.jit.annotate(
|
| 584 |
-
Dict[str, Optional[Tensor]],
|
| 585 |
-
{
|
| 586 |
-
"prev_hiddens": prev_hiddens_tensor,
|
| 587 |
-
"prev_cells": prev_cells_tensor,
|
| 588 |
-
"input_feed": input_feed,
|
| 589 |
-
},
|
| 590 |
-
)
|
| 591 |
-
self.set_incremental_state(incremental_state, "cached_state", cache_state)
|
| 592 |
-
|
| 593 |
-
# collect outputs across time steps
|
| 594 |
-
x = torch.cat(outs, dim=0).view(seqlen, bsz, self.hidden_size)
|
| 595 |
-
|
| 596 |
-
# T x B x C -> B x T x C
|
| 597 |
-
x = x.transpose(1, 0)
|
| 598 |
-
|
| 599 |
-
if hasattr(self, "additional_fc") and self.adaptive_softmax is None:
|
| 600 |
-
x = self.additional_fc(x)
|
| 601 |
-
x = self.dropout_out_module(x)
|
| 602 |
-
# srclen x tgtlen x bsz -> bsz x tgtlen x srclen
|
| 603 |
-
if not self.training and self.need_attn and self.attention is not None:
|
| 604 |
-
assert attn_scores is not None
|
| 605 |
-
attn_scores = attn_scores.transpose(0, 2)
|
| 606 |
-
else:
|
| 607 |
-
attn_scores = None
|
| 608 |
-
return x, attn_scores
|
| 609 |
-
|
| 610 |
-
def output_layer(self, x):
|
| 611 |
-
"""Project features to the vocabulary size."""
|
| 612 |
-
if self.adaptive_softmax is None:
|
| 613 |
-
if self.share_input_output_embed:
|
| 614 |
-
x = F.linear(x, self.embed_tokens.weight)
|
| 615 |
-
else:
|
| 616 |
-
x = self.fc_out(x)
|
| 617 |
-
return x
|
| 618 |
-
|
| 619 |
-
def get_cached_state(
|
| 620 |
-
self,
|
| 621 |
-
incremental_state: Dict[str, Dict[str, Optional[Tensor]]],
|
| 622 |
-
) -> Tuple[List[Tensor], List[Tensor], Optional[Tensor]]:
|
| 623 |
-
cached_state = self.get_incremental_state(incremental_state, "cached_state")
|
| 624 |
-
assert cached_state is not None
|
| 625 |
-
prev_hiddens_ = cached_state["prev_hiddens"]
|
| 626 |
-
assert prev_hiddens_ is not None
|
| 627 |
-
prev_cells_ = cached_state["prev_cells"]
|
| 628 |
-
assert prev_cells_ is not None
|
| 629 |
-
prev_hiddens = [prev_hiddens_[i] for i in range(self.num_layers)]
|
| 630 |
-
prev_cells = [prev_cells_[j] for j in range(self.num_layers)]
|
| 631 |
-
input_feed = cached_state[
|
| 632 |
-
"input_feed"
|
| 633 |
-
] # can be None for decoder-only language models
|
| 634 |
-
return prev_hiddens, prev_cells, input_feed
|
| 635 |
-
|
| 636 |
-
def reorder_incremental_state(
|
| 637 |
-
self,
|
| 638 |
-
incremental_state: Dict[str, Dict[str, Optional[Tensor]]],
|
| 639 |
-
new_order: Tensor,
|
| 640 |
-
):
|
| 641 |
-
if incremental_state is None or len(incremental_state) == 0:
|
| 642 |
-
return
|
| 643 |
-
prev_hiddens, prev_cells, input_feed = self.get_cached_state(incremental_state)
|
| 644 |
-
prev_hiddens = [p.index_select(0, new_order) for p in prev_hiddens]
|
| 645 |
-
prev_cells = [p.index_select(0, new_order) for p in prev_cells]
|
| 646 |
-
if input_feed is not None:
|
| 647 |
-
input_feed = input_feed.index_select(0, new_order)
|
| 648 |
-
cached_state_new = torch.jit.annotate(
|
| 649 |
-
Dict[str, Optional[Tensor]],
|
| 650 |
-
{
|
| 651 |
-
"prev_hiddens": torch.stack(prev_hiddens),
|
| 652 |
-
"prev_cells": torch.stack(prev_cells),
|
| 653 |
-
"input_feed": input_feed,
|
| 654 |
-
},
|
| 655 |
-
)
|
| 656 |
-
self.set_incremental_state(incremental_state, "cached_state", cached_state_new),
|
| 657 |
-
return
|
| 658 |
-
|
| 659 |
-
def max_positions(self):
|
| 660 |
-
"""Maximum output length supported by the decoder."""
|
| 661 |
-
return self.max_target_positions
|
| 662 |
-
|
| 663 |
-
def make_generation_fast_(self, need_attn=False, **kwargs):
|
| 664 |
-
self.need_attn = need_attn
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
def Embedding(num_embeddings, embedding_dim, padding_idx):
|
| 668 |
-
m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
|
| 669 |
-
nn.init.uniform_(m.weight, -0.1, 0.1)
|
| 670 |
-
nn.init.constant_(m.weight[padding_idx], 0)
|
| 671 |
-
return m
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
def LSTM(input_size, hidden_size, **kwargs):
|
| 675 |
-
m = nn.LSTM(input_size, hidden_size, **kwargs)
|
| 676 |
-
for name, param in m.named_parameters():
|
| 677 |
-
if "weight" in name or "bias" in name:
|
| 678 |
-
param.data.uniform_(-0.1, 0.1)
|
| 679 |
-
return m
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
def LSTMCell(input_size, hidden_size, **kwargs):
|
| 683 |
-
m = nn.LSTMCell(input_size, hidden_size, **kwargs)
|
| 684 |
-
for name, param in m.named_parameters():
|
| 685 |
-
if "weight" in name or "bias" in name:
|
| 686 |
-
param.data.uniform_(-0.1, 0.1)
|
| 687 |
-
return m
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
def Linear(in_features, out_features, bias=True, dropout=0.0):
|
| 691 |
-
"""Linear layer (input: N x T x C)"""
|
| 692 |
-
m = nn.Linear(in_features, out_features, bias=bias)
|
| 693 |
-
m.weight.data.uniform_(-0.1, 0.1)
|
| 694 |
-
if bias:
|
| 695 |
-
m.bias.data.uniform_(-0.1, 0.1)
|
| 696 |
-
return m
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
@register_model_architecture("lstm", "lstm")
|
| 700 |
-
def base_architecture(args):
|
| 701 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 702 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
|
| 703 |
-
args.encoder_embed_path = getattr(args, "encoder_embed_path", None)
|
| 704 |
-
args.encoder_freeze_embed = getattr(args, "encoder_freeze_embed", False)
|
| 705 |
-
args.encoder_hidden_size = getattr(
|
| 706 |
-
args, "encoder_hidden_size", args.encoder_embed_dim
|
| 707 |
-
)
|
| 708 |
-
args.encoder_layers = getattr(args, "encoder_layers", 1)
|
| 709 |
-
args.encoder_bidirectional = getattr(args, "encoder_bidirectional", False)
|
| 710 |
-
args.encoder_dropout_in = getattr(args, "encoder_dropout_in", args.dropout)
|
| 711 |
-
args.encoder_dropout_out = getattr(args, "encoder_dropout_out", args.dropout)
|
| 712 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 512)
|
| 713 |
-
args.decoder_embed_path = getattr(args, "decoder_embed_path", None)
|
| 714 |
-
args.decoder_freeze_embed = getattr(args, "decoder_freeze_embed", False)
|
| 715 |
-
args.decoder_hidden_size = getattr(
|
| 716 |
-
args, "decoder_hidden_size", args.decoder_embed_dim
|
| 717 |
-
)
|
| 718 |
-
args.decoder_layers = getattr(args, "decoder_layers", 1)
|
| 719 |
-
args.decoder_out_embed_dim = getattr(args, "decoder_out_embed_dim", 512)
|
| 720 |
-
args.decoder_attention = getattr(args, "decoder_attention", "1")
|
| 721 |
-
args.decoder_dropout_in = getattr(args, "decoder_dropout_in", args.dropout)
|
| 722 |
-
args.decoder_dropout_out = getattr(args, "decoder_dropout_out", args.dropout)
|
| 723 |
-
args.share_decoder_input_output_embed = getattr(
|
| 724 |
-
args, "share_decoder_input_output_embed", False
|
| 725 |
-
)
|
| 726 |
-
args.share_all_embeddings = getattr(args, "share_all_embeddings", False)
|
| 727 |
-
args.adaptive_softmax_cutoff = getattr(
|
| 728 |
-
args, "adaptive_softmax_cutoff", "10000,50000,200000"
|
| 729 |
-
)
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
@register_model_architecture("lstm", "lstm_wiseman_iwslt_de_en")
|
| 733 |
-
def lstm_wiseman_iwslt_de_en(args):
|
| 734 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 735 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 256)
|
| 736 |
-
args.encoder_dropout_in = getattr(args, "encoder_dropout_in", 0)
|
| 737 |
-
args.encoder_dropout_out = getattr(args, "encoder_dropout_out", 0)
|
| 738 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 256)
|
| 739 |
-
args.decoder_out_embed_dim = getattr(args, "decoder_out_embed_dim", 256)
|
| 740 |
-
args.decoder_dropout_in = getattr(args, "decoder_dropout_in", 0)
|
| 741 |
-
args.decoder_dropout_out = getattr(args, "decoder_dropout_out", args.dropout)
|
| 742 |
-
base_architecture(args)
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
@register_model_architecture("lstm", "lstm_luong_wmt_en_de")
|
| 746 |
-
def lstm_luong_wmt_en_de(args):
|
| 747 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 1000)
|
| 748 |
-
args.encoder_layers = getattr(args, "encoder_layers", 4)
|
| 749 |
-
args.encoder_dropout_out = getattr(args, "encoder_dropout_out", 0)
|
| 750 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 1000)
|
| 751 |
-
args.decoder_layers = getattr(args, "decoder_layers", 4)
|
| 752 |
-
args.decoder_out_embed_dim = getattr(args, "decoder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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/lstm_lm.py
DELETED
|
@@ -1,141 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
from fairseq import utils
|
| 7 |
-
from fairseq.models import (
|
| 8 |
-
FairseqLanguageModel,
|
| 9 |
-
register_model,
|
| 10 |
-
register_model_architecture,
|
| 11 |
-
)
|
| 12 |
-
from fairseq.models.lstm import Embedding, LSTMDecoder
|
| 13 |
-
|
| 14 |
-
DEFAULT_MAX_TARGET_POSITIONS = 1e5
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
@register_model("lstm_lm")
|
| 18 |
-
class LSTMLanguageModel(FairseqLanguageModel):
|
| 19 |
-
def __init__(self, decoder):
|
| 20 |
-
super().__init__(decoder)
|
| 21 |
-
|
| 22 |
-
@staticmethod
|
| 23 |
-
def add_args(parser):
|
| 24 |
-
"""Add model-specific arguments to the parser."""
|
| 25 |
-
# fmt: off
|
| 26 |
-
parser.add_argument('--dropout', type=float, metavar='D',
|
| 27 |
-
help='dropout probability')
|
| 28 |
-
parser.add_argument('--decoder-embed-dim', type=int, metavar='N',
|
| 29 |
-
help='decoder embedding dimension')
|
| 30 |
-
parser.add_argument('--decoder-embed-path', type=str, metavar='STR',
|
| 31 |
-
help='path to pre-trained decoder embedding')
|
| 32 |
-
parser.add_argument('--decoder-hidden-size', type=int, metavar='N',
|
| 33 |
-
help='decoder hidden size')
|
| 34 |
-
parser.add_argument('--decoder-layers', type=int, metavar='N',
|
| 35 |
-
help='number of decoder layers')
|
| 36 |
-
parser.add_argument('--decoder-out-embed-dim', type=int, metavar='N',
|
| 37 |
-
help='decoder output embedding dimension')
|
| 38 |
-
parser.add_argument('--decoder-attention', type=str, metavar='BOOL',
|
| 39 |
-
help='decoder attention')
|
| 40 |
-
parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR',
|
| 41 |
-
help='comma separated list of adaptive softmax cutoff points. '
|
| 42 |
-
'Must be used with adaptive_loss criterion')
|
| 43 |
-
parser.add_argument('--residuals', default=False,
|
| 44 |
-
action='store_true',
|
| 45 |
-
help='applying residuals between LSTM layers')
|
| 46 |
-
|
| 47 |
-
# Granular dropout settings (if not specified these default to --dropout)
|
| 48 |
-
parser.add_argument('--decoder-dropout-in', type=float, metavar='D',
|
| 49 |
-
help='dropout probability for decoder input embedding')
|
| 50 |
-
parser.add_argument('--decoder-dropout-out', type=float, metavar='D',
|
| 51 |
-
help='dropout probability for decoder output')
|
| 52 |
-
parser.add_argument('--share-decoder-input-output-embed', default=False,
|
| 53 |
-
action='store_true',
|
| 54 |
-
help='share decoder input and output embeddings')
|
| 55 |
-
# fmt: on
|
| 56 |
-
|
| 57 |
-
@classmethod
|
| 58 |
-
def build_model(cls, args, task):
|
| 59 |
-
"""Build a new model instance."""
|
| 60 |
-
|
| 61 |
-
# make sure all arguments are present in older models
|
| 62 |
-
base_architecture(args)
|
| 63 |
-
|
| 64 |
-
if getattr(args, "max_target_positions", None) is not None:
|
| 65 |
-
max_target_positions = args.max_target_positions
|
| 66 |
-
else:
|
| 67 |
-
max_target_positions = getattr(
|
| 68 |
-
args, "tokens_per_sample", DEFAULT_MAX_TARGET_POSITIONS
|
| 69 |
-
)
|
| 70 |
-
|
| 71 |
-
def load_pretrained_embedding_from_file(embed_path, dictionary, embed_dim):
|
| 72 |
-
num_embeddings = len(dictionary)
|
| 73 |
-
padding_idx = dictionary.pad()
|
| 74 |
-
embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx)
|
| 75 |
-
embed_dict = utils.parse_embedding(embed_path)
|
| 76 |
-
utils.print_embed_overlap(embed_dict, dictionary)
|
| 77 |
-
return utils.load_embedding(embed_dict, dictionary, embed_tokens)
|
| 78 |
-
|
| 79 |
-
pretrained_decoder_embed = None
|
| 80 |
-
if args.decoder_embed_path:
|
| 81 |
-
pretrained_decoder_embed = load_pretrained_embedding_from_file(
|
| 82 |
-
args.decoder_embed_path, task.target_dictionary, args.decoder_embed_dim
|
| 83 |
-
)
|
| 84 |
-
|
| 85 |
-
if args.share_decoder_input_output_embed:
|
| 86 |
-
# double check all parameters combinations are valid
|
| 87 |
-
if task.source_dictionary != task.target_dictionary:
|
| 88 |
-
raise ValueError(
|
| 89 |
-
"--share-decoder-input-output-embeddings requires a joint dictionary"
|
| 90 |
-
)
|
| 91 |
-
|
| 92 |
-
if args.decoder_embed_dim != args.decoder_out_embed_dim:
|
| 93 |
-
raise ValueError(
|
| 94 |
-
"--share-decoder-input-output-embeddings requires "
|
| 95 |
-
"--decoder-embed-dim to match --decoder-out-embed-dim"
|
| 96 |
-
)
|
| 97 |
-
|
| 98 |
-
decoder = LSTMDecoder(
|
| 99 |
-
dictionary=task.dictionary,
|
| 100 |
-
embed_dim=args.decoder_embed_dim,
|
| 101 |
-
hidden_size=args.decoder_hidden_size,
|
| 102 |
-
out_embed_dim=args.decoder_out_embed_dim,
|
| 103 |
-
num_layers=args.decoder_layers,
|
| 104 |
-
dropout_in=args.decoder_dropout_in,
|
| 105 |
-
dropout_out=args.decoder_dropout_out,
|
| 106 |
-
attention=False, # decoder-only language model doesn't support attention
|
| 107 |
-
encoder_output_units=0,
|
| 108 |
-
pretrained_embed=pretrained_decoder_embed,
|
| 109 |
-
share_input_output_embed=args.share_decoder_input_output_embed,
|
| 110 |
-
adaptive_softmax_cutoff=(
|
| 111 |
-
utils.eval_str_list(args.adaptive_softmax_cutoff, type=int)
|
| 112 |
-
if args.criterion == "adaptive_loss"
|
| 113 |
-
else None
|
| 114 |
-
),
|
| 115 |
-
max_target_positions=max_target_positions,
|
| 116 |
-
residuals=args.residuals,
|
| 117 |
-
)
|
| 118 |
-
|
| 119 |
-
return cls(decoder)
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
@register_model_architecture("lstm_lm", "lstm_lm")
|
| 123 |
-
def base_architecture(args):
|
| 124 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 125 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 512)
|
| 126 |
-
args.decoder_embed_path = getattr(args, "decoder_embed_path", None)
|
| 127 |
-
args.decoder_hidden_size = getattr(
|
| 128 |
-
args, "decoder_hidden_size", args.decoder_embed_dim
|
| 129 |
-
)
|
| 130 |
-
args.decoder_layers = getattr(args, "decoder_layers", 1)
|
| 131 |
-
args.decoder_out_embed_dim = getattr(args, "decoder_out_embed_dim", 512)
|
| 132 |
-
args.decoder_attention = getattr(args, "decoder_attention", "0")
|
| 133 |
-
args.decoder_dropout_in = getattr(args, "decoder_dropout_in", args.dropout)
|
| 134 |
-
args.decoder_dropout_out = getattr(args, "decoder_dropout_out", args.dropout)
|
| 135 |
-
args.share_decoder_input_output_embed = getattr(
|
| 136 |
-
args, "share_decoder_input_output_embed", False
|
| 137 |
-
)
|
| 138 |
-
args.adaptive_softmax_cutoff = getattr(
|
| 139 |
-
args, "adaptive_softmax_cutoff", "10000,50000,200000"
|
| 140 |
-
)
|
| 141 |
-
args.residuals = getattr(args, "residuals", False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/masked_lm.py
DELETED
|
@@ -1,403 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import logging
|
| 7 |
-
|
| 8 |
-
import torch
|
| 9 |
-
import torch.nn as nn
|
| 10 |
-
import torch.nn.functional as F
|
| 11 |
-
from fairseq import utils
|
| 12 |
-
from fairseq.models import (
|
| 13 |
-
FairseqEncoder,
|
| 14 |
-
FairseqEncoderModel,
|
| 15 |
-
register_model,
|
| 16 |
-
register_model_architecture,
|
| 17 |
-
)
|
| 18 |
-
from fairseq.modules import (
|
| 19 |
-
LayerNorm,
|
| 20 |
-
SinusoidalPositionalEmbedding,
|
| 21 |
-
TransformerSentenceEncoder,
|
| 22 |
-
)
|
| 23 |
-
from fairseq.modules.transformer_sentence_encoder import init_bert_params
|
| 24 |
-
from fairseq.utils import safe_hasattr
|
| 25 |
-
|
| 26 |
-
logger = logging.getLogger(__name__)
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
@register_model("masked_lm")
|
| 30 |
-
class MaskedLMModel(FairseqEncoderModel):
|
| 31 |
-
"""
|
| 32 |
-
Class for training a Masked Language Model. It also supports an
|
| 33 |
-
additional sentence level prediction if the sent-loss argument is set.
|
| 34 |
-
"""
|
| 35 |
-
|
| 36 |
-
def __init__(self, args, encoder):
|
| 37 |
-
super().__init__(encoder)
|
| 38 |
-
self.args = args
|
| 39 |
-
|
| 40 |
-
# if specified then apply bert initialization on the model. We need
|
| 41 |
-
# to explictly call this to make sure that the output embeddings
|
| 42 |
-
# and projection layers are also correctly initialized
|
| 43 |
-
if getattr(args, "apply_bert_init", False):
|
| 44 |
-
self.apply(init_bert_params)
|
| 45 |
-
|
| 46 |
-
@staticmethod
|
| 47 |
-
def add_args(parser):
|
| 48 |
-
"""Add model-specific arguments to the parser."""
|
| 49 |
-
# Arguments related to dropout
|
| 50 |
-
parser.add_argument(
|
| 51 |
-
"--dropout", type=float, metavar="D", help="dropout probability"
|
| 52 |
-
)
|
| 53 |
-
parser.add_argument(
|
| 54 |
-
"--attention-dropout",
|
| 55 |
-
type=float,
|
| 56 |
-
metavar="D",
|
| 57 |
-
help="dropout probability for" " attention weights",
|
| 58 |
-
)
|
| 59 |
-
parser.add_argument(
|
| 60 |
-
"--act-dropout",
|
| 61 |
-
type=float,
|
| 62 |
-
metavar="D",
|
| 63 |
-
help="dropout probability after" " activation in FFN",
|
| 64 |
-
)
|
| 65 |
-
|
| 66 |
-
# Arguments related to hidden states and self-attention
|
| 67 |
-
parser.add_argument(
|
| 68 |
-
"--encoder-ffn-embed-dim",
|
| 69 |
-
type=int,
|
| 70 |
-
metavar="N",
|
| 71 |
-
help="encoder embedding dimension for FFN",
|
| 72 |
-
)
|
| 73 |
-
parser.add_argument(
|
| 74 |
-
"--encoder-layers", type=int, metavar="N", help="num encoder layers"
|
| 75 |
-
)
|
| 76 |
-
parser.add_argument(
|
| 77 |
-
"--encoder-attention-heads",
|
| 78 |
-
type=int,
|
| 79 |
-
metavar="N",
|
| 80 |
-
help="num encoder attention heads",
|
| 81 |
-
)
|
| 82 |
-
|
| 83 |
-
# Arguments related to input and output embeddings
|
| 84 |
-
parser.add_argument(
|
| 85 |
-
"--encoder-embed-dim",
|
| 86 |
-
type=int,
|
| 87 |
-
metavar="N",
|
| 88 |
-
help="encoder embedding dimension",
|
| 89 |
-
)
|
| 90 |
-
parser.add_argument(
|
| 91 |
-
"--share-encoder-input-output-embed",
|
| 92 |
-
action="store_true",
|
| 93 |
-
help="share encoder input" " and output embeddings",
|
| 94 |
-
)
|
| 95 |
-
parser.add_argument(
|
| 96 |
-
"--encoder-learned-pos",
|
| 97 |
-
action="store_true",
|
| 98 |
-
help="use learned positional embeddings in the encoder",
|
| 99 |
-
)
|
| 100 |
-
parser.add_argument(
|
| 101 |
-
"--no-token-positional-embeddings",
|
| 102 |
-
action="store_true",
|
| 103 |
-
help="if set, disables positional embeddings" " (outside self attention)",
|
| 104 |
-
)
|
| 105 |
-
parser.add_argument(
|
| 106 |
-
"--num-segment", type=int, metavar="N", help="num segment in the input"
|
| 107 |
-
)
|
| 108 |
-
parser.add_argument(
|
| 109 |
-
"--max-positions", type=int, help="number of positional embeddings to learn"
|
| 110 |
-
)
|
| 111 |
-
|
| 112 |
-
# Arguments related to sentence level prediction
|
| 113 |
-
parser.add_argument(
|
| 114 |
-
"--sentence-class-num",
|
| 115 |
-
type=int,
|
| 116 |
-
metavar="N",
|
| 117 |
-
help="number of classes for sentence task",
|
| 118 |
-
)
|
| 119 |
-
parser.add_argument(
|
| 120 |
-
"--sent-loss",
|
| 121 |
-
action="store_true",
|
| 122 |
-
help="if set," " calculate sentence level predictions",
|
| 123 |
-
)
|
| 124 |
-
|
| 125 |
-
# Arguments related to parameter initialization
|
| 126 |
-
parser.add_argument(
|
| 127 |
-
"--apply-bert-init",
|
| 128 |
-
action="store_true",
|
| 129 |
-
help="use custom param initialization for BERT",
|
| 130 |
-
)
|
| 131 |
-
|
| 132 |
-
# misc params
|
| 133 |
-
parser.add_argument(
|
| 134 |
-
"--activation-fn",
|
| 135 |
-
choices=utils.get_available_activation_fns(),
|
| 136 |
-
help="activation function to use",
|
| 137 |
-
)
|
| 138 |
-
parser.add_argument(
|
| 139 |
-
"--pooler-activation-fn",
|
| 140 |
-
choices=utils.get_available_activation_fns(),
|
| 141 |
-
help="Which activation function to use for pooler layer.",
|
| 142 |
-
)
|
| 143 |
-
parser.add_argument(
|
| 144 |
-
"--encoder-normalize-before",
|
| 145 |
-
action="store_true",
|
| 146 |
-
help="apply layernorm before each encoder block",
|
| 147 |
-
)
|
| 148 |
-
|
| 149 |
-
def forward(self, src_tokens, segment_labels=None, **kwargs):
|
| 150 |
-
return self.encoder(src_tokens, segment_labels=segment_labels, **kwargs)
|
| 151 |
-
|
| 152 |
-
def max_positions(self):
|
| 153 |
-
return self.encoder.max_positions
|
| 154 |
-
|
| 155 |
-
@classmethod
|
| 156 |
-
def build_model(cls, args, task):
|
| 157 |
-
"""Build a new model instance."""
|
| 158 |
-
# make sure all arguments are present in older models
|
| 159 |
-
base_architecture(args)
|
| 160 |
-
|
| 161 |
-
if not safe_hasattr(args, "max_positions"):
|
| 162 |
-
args.max_positions = args.tokens_per_sample
|
| 163 |
-
|
| 164 |
-
logger.info(args)
|
| 165 |
-
|
| 166 |
-
encoder = MaskedLMEncoder(args, task.dictionary)
|
| 167 |
-
return cls(args, encoder)
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
class MaskedLMEncoder(FairseqEncoder):
|
| 171 |
-
"""
|
| 172 |
-
Encoder for Masked Language Modelling.
|
| 173 |
-
"""
|
| 174 |
-
|
| 175 |
-
def __init__(self, args, dictionary):
|
| 176 |
-
super().__init__(dictionary)
|
| 177 |
-
|
| 178 |
-
self.padding_idx = dictionary.pad()
|
| 179 |
-
self.vocab_size = dictionary.__len__()
|
| 180 |
-
self.max_positions = args.max_positions
|
| 181 |
-
|
| 182 |
-
self.sentence_encoder = TransformerSentenceEncoder(
|
| 183 |
-
padding_idx=self.padding_idx,
|
| 184 |
-
vocab_size=self.vocab_size,
|
| 185 |
-
num_encoder_layers=args.encoder_layers,
|
| 186 |
-
embedding_dim=args.encoder_embed_dim,
|
| 187 |
-
ffn_embedding_dim=args.encoder_ffn_embed_dim,
|
| 188 |
-
num_attention_heads=args.encoder_attention_heads,
|
| 189 |
-
dropout=args.dropout,
|
| 190 |
-
attention_dropout=args.attention_dropout,
|
| 191 |
-
activation_dropout=args.act_dropout,
|
| 192 |
-
max_seq_len=self.max_positions,
|
| 193 |
-
num_segments=args.num_segment,
|
| 194 |
-
use_position_embeddings=not args.no_token_positional_embeddings,
|
| 195 |
-
encoder_normalize_before=args.encoder_normalize_before,
|
| 196 |
-
apply_bert_init=args.apply_bert_init,
|
| 197 |
-
activation_fn=args.activation_fn,
|
| 198 |
-
learned_pos_embedding=args.encoder_learned_pos,
|
| 199 |
-
)
|
| 200 |
-
|
| 201 |
-
self.share_input_output_embed = args.share_encoder_input_output_embed
|
| 202 |
-
self.embed_out = None
|
| 203 |
-
self.sentence_projection_layer = None
|
| 204 |
-
self.sentence_out_dim = args.sentence_class_num
|
| 205 |
-
self.lm_output_learned_bias = None
|
| 206 |
-
|
| 207 |
-
# Remove head is set to true during fine-tuning
|
| 208 |
-
self.load_softmax = not getattr(args, "remove_head", False)
|
| 209 |
-
|
| 210 |
-
self.masked_lm_pooler = nn.Linear(
|
| 211 |
-
args.encoder_embed_dim, args.encoder_embed_dim
|
| 212 |
-
)
|
| 213 |
-
self.pooler_activation = utils.get_activation_fn(args.pooler_activation_fn)
|
| 214 |
-
|
| 215 |
-
self.lm_head_transform_weight = nn.Linear(
|
| 216 |
-
args.encoder_embed_dim, args.encoder_embed_dim
|
| 217 |
-
)
|
| 218 |
-
self.activation_fn = utils.get_activation_fn(args.activation_fn)
|
| 219 |
-
self.layer_norm = LayerNorm(args.encoder_embed_dim)
|
| 220 |
-
|
| 221 |
-
self.lm_output_learned_bias = None
|
| 222 |
-
if self.load_softmax:
|
| 223 |
-
self.lm_output_learned_bias = nn.Parameter(torch.zeros(self.vocab_size))
|
| 224 |
-
|
| 225 |
-
if not self.share_input_output_embed:
|
| 226 |
-
self.embed_out = nn.Linear(
|
| 227 |
-
args.encoder_embed_dim, self.vocab_size, bias=False
|
| 228 |
-
)
|
| 229 |
-
|
| 230 |
-
if args.sent_loss:
|
| 231 |
-
self.sentence_projection_layer = nn.Linear(
|
| 232 |
-
args.encoder_embed_dim, self.sentence_out_dim, bias=False
|
| 233 |
-
)
|
| 234 |
-
|
| 235 |
-
def forward(self, src_tokens, segment_labels=None, masked_tokens=None, **unused):
|
| 236 |
-
"""
|
| 237 |
-
Forward pass for Masked LM encoder. This first computes the token
|
| 238 |
-
embedding using the token embedding matrix, position embeddings (if
|
| 239 |
-
specified) and segment embeddings (if specified).
|
| 240 |
-
|
| 241 |
-
Here we assume that the sentence representation corresponds to the
|
| 242 |
-
output of the classification_token (see bert_task or cross_lingual_lm
|
| 243 |
-
task for more details).
|
| 244 |
-
Args:
|
| 245 |
-
- src_tokens: B x T matrix representing sentences
|
| 246 |
-
- segment_labels: B x T matrix representing segment label for tokens
|
| 247 |
-
Returns:
|
| 248 |
-
- a tuple of the following:
|
| 249 |
-
- logits for predictions in format B x T x C to be used in
|
| 250 |
-
softmax afterwards
|
| 251 |
-
- a dictionary of additional data, where 'pooled_output' contains
|
| 252 |
-
the representation for classification_token and 'inner_states'
|
| 253 |
-
is a list of internal model states used to compute the
|
| 254 |
-
predictions (similar in ELMO). 'sentence_logits'
|
| 255 |
-
is the prediction logit for NSP task and is only computed if
|
| 256 |
-
this is specified in the input arguments.
|
| 257 |
-
"""
|
| 258 |
-
|
| 259 |
-
inner_states, sentence_rep = self.sentence_encoder(
|
| 260 |
-
src_tokens,
|
| 261 |
-
segment_labels=segment_labels,
|
| 262 |
-
)
|
| 263 |
-
|
| 264 |
-
x = inner_states[-1].transpose(0, 1)
|
| 265 |
-
# project masked tokens only
|
| 266 |
-
if masked_tokens is not None:
|
| 267 |
-
x = x[masked_tokens, :]
|
| 268 |
-
x = self.layer_norm(self.activation_fn(self.lm_head_transform_weight(x)))
|
| 269 |
-
|
| 270 |
-
pooled_output = self.pooler_activation(self.masked_lm_pooler(sentence_rep))
|
| 271 |
-
|
| 272 |
-
# project back to size of vocabulary
|
| 273 |
-
if self.share_input_output_embed and hasattr(
|
| 274 |
-
self.sentence_encoder.embed_tokens, "weight"
|
| 275 |
-
):
|
| 276 |
-
x = F.linear(x, self.sentence_encoder.embed_tokens.weight)
|
| 277 |
-
elif self.embed_out is not None:
|
| 278 |
-
x = self.embed_out(x)
|
| 279 |
-
if self.lm_output_learned_bias is not None:
|
| 280 |
-
x = x + self.lm_output_learned_bias
|
| 281 |
-
sentence_logits = None
|
| 282 |
-
if self.sentence_projection_layer:
|
| 283 |
-
sentence_logits = self.sentence_projection_layer(pooled_output)
|
| 284 |
-
|
| 285 |
-
return x, {
|
| 286 |
-
"inner_states": inner_states,
|
| 287 |
-
"pooled_output": pooled_output,
|
| 288 |
-
"sentence_logits": sentence_logits,
|
| 289 |
-
}
|
| 290 |
-
|
| 291 |
-
def max_positions(self):
|
| 292 |
-
"""Maximum output length supported by the encoder."""
|
| 293 |
-
return self.max_positions
|
| 294 |
-
|
| 295 |
-
def upgrade_state_dict_named(self, state_dict, name):
|
| 296 |
-
if isinstance(
|
| 297 |
-
self.sentence_encoder.embed_positions, SinusoidalPositionalEmbedding
|
| 298 |
-
):
|
| 299 |
-
state_dict[
|
| 300 |
-
name + ".sentence_encoder.embed_positions._float_tensor"
|
| 301 |
-
] = torch.FloatTensor(1)
|
| 302 |
-
if not self.load_softmax:
|
| 303 |
-
for k in list(state_dict.keys()):
|
| 304 |
-
if (
|
| 305 |
-
"embed_out.weight" in k
|
| 306 |
-
or "sentence_projection_layer.weight" in k
|
| 307 |
-
or "lm_output_learned_bias" in k
|
| 308 |
-
):
|
| 309 |
-
del state_dict[k]
|
| 310 |
-
return state_dict
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
@register_model_architecture("masked_lm", "masked_lm")
|
| 314 |
-
def base_architecture(args):
|
| 315 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 316 |
-
args.attention_dropout = getattr(args, "attention_dropout", 0.1)
|
| 317 |
-
args.act_dropout = getattr(args, "act_dropout", 0.0)
|
| 318 |
-
|
| 319 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4096)
|
| 320 |
-
args.encoder_layers = getattr(args, "encoder_layers", 6)
|
| 321 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8)
|
| 322 |
-
|
| 323 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 1024)
|
| 324 |
-
args.share_encoder_input_output_embed = getattr(
|
| 325 |
-
args, "share_encoder_input_output_embed", False
|
| 326 |
-
)
|
| 327 |
-
args.encoder_learned_pos = getattr(args, "encoder_learned_pos", False)
|
| 328 |
-
args.no_token_positional_embeddings = getattr(
|
| 329 |
-
args, "no_token_positional_embeddings", False
|
| 330 |
-
)
|
| 331 |
-
args.num_segment = getattr(args, "num_segment", 2)
|
| 332 |
-
|
| 333 |
-
args.sentence_class_num = getattr(args, "sentence_class_num", 2)
|
| 334 |
-
args.sent_loss = getattr(args, "sent_loss", False)
|
| 335 |
-
|
| 336 |
-
args.apply_bert_init = getattr(args, "apply_bert_init", False)
|
| 337 |
-
|
| 338 |
-
args.activation_fn = getattr(args, "activation_fn", "relu")
|
| 339 |
-
args.pooler_activation_fn = getattr(args, "pooler_activation_fn", "tanh")
|
| 340 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
@register_model_architecture("masked_lm", "bert_base")
|
| 344 |
-
def bert_base_architecture(args):
|
| 345 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 768)
|
| 346 |
-
args.share_encoder_input_output_embed = getattr(
|
| 347 |
-
args, "share_encoder_input_output_embed", True
|
| 348 |
-
)
|
| 349 |
-
args.no_token_positional_embeddings = getattr(
|
| 350 |
-
args, "no_token_positional_embeddings", False
|
| 351 |
-
)
|
| 352 |
-
args.encoder_learned_pos = getattr(args, "encoder_learned_pos", True)
|
| 353 |
-
args.num_segment = getattr(args, "num_segment", 2)
|
| 354 |
-
|
| 355 |
-
args.encoder_layers = getattr(args, "encoder_layers", 12)
|
| 356 |
-
|
| 357 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 12)
|
| 358 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 3072)
|
| 359 |
-
|
| 360 |
-
args.sentence_class_num = getattr(args, "sentence_class_num", 2)
|
| 361 |
-
args.sent_loss = getattr(args, "sent_loss", True)
|
| 362 |
-
|
| 363 |
-
args.apply_bert_init = getattr(args, "apply_bert_init", True)
|
| 364 |
-
|
| 365 |
-
args.activation_fn = getattr(args, "activation_fn", "gelu")
|
| 366 |
-
args.pooler_activation_fn = getattr(args, "pooler_activation_fn", "tanh")
|
| 367 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", True)
|
| 368 |
-
base_architecture(args)
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
@register_model_architecture("masked_lm", "bert_large")
|
| 372 |
-
def bert_large_architecture(args):
|
| 373 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 1024)
|
| 374 |
-
args.encoder_layers = getattr(args, "encoder_layers", 24)
|
| 375 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 16)
|
| 376 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4096)
|
| 377 |
-
bert_base_architecture(args)
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
@register_model_architecture("masked_lm", "xlm_base")
|
| 381 |
-
def xlm_architecture(args):
|
| 382 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 1024)
|
| 383 |
-
args.share_encoder_input_output_embed = getattr(
|
| 384 |
-
args, "share_encoder_input_output_embed", True
|
| 385 |
-
)
|
| 386 |
-
args.no_token_positional_embeddings = getattr(
|
| 387 |
-
args, "no_token_positional_embeddings", False
|
| 388 |
-
)
|
| 389 |
-
args.encoder_learned_pos = getattr(args, "encoder_learned_pos", True)
|
| 390 |
-
args.num_segment = getattr(args, "num_segment", 1)
|
| 391 |
-
|
| 392 |
-
args.encoder_layers = getattr(args, "encoder_layers", 6)
|
| 393 |
-
|
| 394 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8)
|
| 395 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4096)
|
| 396 |
-
|
| 397 |
-
args.sent_loss = getattr(args, "sent_loss", False)
|
| 398 |
-
|
| 399 |
-
args.activation_fn = getattr(args, "activation_fn", "gelu")
|
| 400 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
|
| 401 |
-
args.pooler_activation_fn = getattr(args, "pooler_activation_fn", "tanh")
|
| 402 |
-
args.apply_bert_init = getattr(args, "apply_bert_init", True)
|
| 403 |
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/model_utils.py
DELETED
|
@@ -1,92 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
from typing import List, Optional
|
| 7 |
-
|
| 8 |
-
import torch
|
| 9 |
-
from torch import Tensor
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
@torch.jit.script
|
| 13 |
-
def script_skip_tensor_list(x: List[Tensor], mask):
|
| 14 |
-
res = [xi[mask] if xi.size(0) == mask.size(0) else xi[:, mask] for xi in x]
|
| 15 |
-
outputs = []
|
| 16 |
-
for i, t in enumerate(res):
|
| 17 |
-
if t.numel() != 0:
|
| 18 |
-
outputs.append(t)
|
| 19 |
-
else:
|
| 20 |
-
outputs.append(x[i])
|
| 21 |
-
return outputs
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
@torch.jit.script
|
| 25 |
-
def script_skip_tensor(x: Tensor, mask):
|
| 26 |
-
# None case
|
| 27 |
-
if x.size(0) == 0:
|
| 28 |
-
return x
|
| 29 |
-
res = x[mask] if x.size(0) == mask.size(0) else x[:, mask]
|
| 30 |
-
if res.numel() == 0:
|
| 31 |
-
return x
|
| 32 |
-
else:
|
| 33 |
-
return res
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
@torch.jit.script
|
| 37 |
-
def expand_2d_or_3d_tensor(x, trg_dim: int, padding_idx: int):
|
| 38 |
-
"""
|
| 39 |
-
Expand 2D/3D tensor on dim=1
|
| 40 |
-
"""
|
| 41 |
-
if x is None:
|
| 42 |
-
return None
|
| 43 |
-
|
| 44 |
-
assert x.dim() == 2 or x.dim() == 3
|
| 45 |
-
assert trg_dim >= x.size(1), (trg_dim, x.size())
|
| 46 |
-
if trg_dim == x.size(1):
|
| 47 |
-
return x
|
| 48 |
-
|
| 49 |
-
dims = [x.size(0), trg_dim - x.size(1)]
|
| 50 |
-
if x.dim() == 3:
|
| 51 |
-
dims.append(x.size(2))
|
| 52 |
-
x = torch.cat([x, torch.zeros(dims).to(x).fill_(padding_idx)], 1)
|
| 53 |
-
|
| 54 |
-
return x
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
@torch.jit.script
|
| 58 |
-
def coalesce(x: Optional[Tensor], y: Tensor) -> Tensor:
|
| 59 |
-
return x if x is not None else y
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
@torch.jit.script
|
| 63 |
-
def fill_tensors(
|
| 64 |
-
x: Optional[Tensor], mask, y: Optional[Tensor], padding_idx: int
|
| 65 |
-
) -> Optional[Tensor]:
|
| 66 |
-
"""
|
| 67 |
-
Filling tensor x with y at masked positions (dim=0).
|
| 68 |
-
"""
|
| 69 |
-
if x is None or x.size()[0] == 0 or y is None:
|
| 70 |
-
return x
|
| 71 |
-
assert x.dim() == y.dim() and mask.size(0) == x.size(0)
|
| 72 |
-
assert x.dim() == 2 or (x.dim() == 3 and x.size(2) == y.size(2))
|
| 73 |
-
|
| 74 |
-
n_selected = mask.sum()
|
| 75 |
-
if n_selected == 0:
|
| 76 |
-
return x
|
| 77 |
-
assert n_selected == y.size(0)
|
| 78 |
-
if n_selected == x.size(0):
|
| 79 |
-
return y
|
| 80 |
-
|
| 81 |
-
if x.size(1) < y.size(1):
|
| 82 |
-
x = expand_2d_or_3d_tensor(x, y.size(1), padding_idx)
|
| 83 |
-
x[mask] = y
|
| 84 |
-
elif x.size(1) > y.size(1):
|
| 85 |
-
x[mask] = torch.tensor(padding_idx).type_as(x)
|
| 86 |
-
if x.dim() == 2:
|
| 87 |
-
x[mask, : y.size(1)] = y
|
| 88 |
-
else:
|
| 89 |
-
x[mask, : y.size(1), :] = y
|
| 90 |
-
else:
|
| 91 |
-
x[mask] = y
|
| 92 |
-
return x
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/multilingual_transformer.py
DELETED
|
@@ -1,229 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
from collections import OrderedDict
|
| 7 |
-
|
| 8 |
-
from fairseq import utils
|
| 9 |
-
from fairseq.models import (
|
| 10 |
-
FairseqMultiModel,
|
| 11 |
-
register_model,
|
| 12 |
-
register_model_architecture,
|
| 13 |
-
)
|
| 14 |
-
from fairseq.models.transformer import (
|
| 15 |
-
Embedding,
|
| 16 |
-
TransformerDecoder,
|
| 17 |
-
TransformerEncoder,
|
| 18 |
-
TransformerModel,
|
| 19 |
-
base_architecture,
|
| 20 |
-
)
|
| 21 |
-
from fairseq.utils import safe_hasattr
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
@register_model("multilingual_transformer")
|
| 25 |
-
class MultilingualTransformerModel(FairseqMultiModel):
|
| 26 |
-
"""Train Transformer models for multiple language pairs simultaneously.
|
| 27 |
-
|
| 28 |
-
Requires `--task multilingual_translation`.
|
| 29 |
-
|
| 30 |
-
We inherit all arguments from TransformerModel and assume that all language
|
| 31 |
-
pairs use a single Transformer architecture. In addition, we provide several
|
| 32 |
-
options that are specific to the multilingual setting.
|
| 33 |
-
|
| 34 |
-
Args:
|
| 35 |
-
--share-encoder-embeddings: share encoder embeddings across all source languages
|
| 36 |
-
--share-decoder-embeddings: share decoder embeddings across all target languages
|
| 37 |
-
--share-encoders: share all encoder params (incl. embeddings) across all source languages
|
| 38 |
-
--share-decoders: share all decoder params (incl. embeddings) across all target languages
|
| 39 |
-
"""
|
| 40 |
-
|
| 41 |
-
def __init__(self, encoders, decoders):
|
| 42 |
-
super().__init__(encoders, decoders)
|
| 43 |
-
|
| 44 |
-
@staticmethod
|
| 45 |
-
def add_args(parser):
|
| 46 |
-
"""Add model-specific arguments to the parser."""
|
| 47 |
-
TransformerModel.add_args(parser)
|
| 48 |
-
parser.add_argument(
|
| 49 |
-
"--share-encoder-embeddings",
|
| 50 |
-
action="store_true",
|
| 51 |
-
help="share encoder embeddings across languages",
|
| 52 |
-
)
|
| 53 |
-
parser.add_argument(
|
| 54 |
-
"--share-decoder-embeddings",
|
| 55 |
-
action="store_true",
|
| 56 |
-
help="share decoder embeddings across languages",
|
| 57 |
-
)
|
| 58 |
-
parser.add_argument(
|
| 59 |
-
"--share-encoders",
|
| 60 |
-
action="store_true",
|
| 61 |
-
help="share encoders across languages",
|
| 62 |
-
)
|
| 63 |
-
parser.add_argument(
|
| 64 |
-
"--share-decoders",
|
| 65 |
-
action="store_true",
|
| 66 |
-
help="share decoders across languages",
|
| 67 |
-
)
|
| 68 |
-
|
| 69 |
-
@classmethod
|
| 70 |
-
def build_model(cls, args, task):
|
| 71 |
-
"""Build a new model instance."""
|
| 72 |
-
from fairseq.tasks.multilingual_translation import MultilingualTranslationTask
|
| 73 |
-
|
| 74 |
-
assert isinstance(task, MultilingualTranslationTask)
|
| 75 |
-
|
| 76 |
-
# make sure all arguments are present in older models
|
| 77 |
-
base_multilingual_architecture(args)
|
| 78 |
-
|
| 79 |
-
if not safe_hasattr(args, "max_source_positions"):
|
| 80 |
-
args.max_source_positions = 1024
|
| 81 |
-
if not safe_hasattr(args, "max_target_positions"):
|
| 82 |
-
args.max_target_positions = 1024
|
| 83 |
-
|
| 84 |
-
src_langs = [lang_pair.split("-")[0] for lang_pair in task.model_lang_pairs]
|
| 85 |
-
tgt_langs = [lang_pair.split("-")[1] for lang_pair in task.model_lang_pairs]
|
| 86 |
-
|
| 87 |
-
if args.share_encoders:
|
| 88 |
-
args.share_encoder_embeddings = True
|
| 89 |
-
if args.share_decoders:
|
| 90 |
-
args.share_decoder_embeddings = True
|
| 91 |
-
|
| 92 |
-
def build_embedding(dictionary, embed_dim, path=None):
|
| 93 |
-
num_embeddings = len(dictionary)
|
| 94 |
-
padding_idx = dictionary.pad()
|
| 95 |
-
emb = Embedding(num_embeddings, embed_dim, padding_idx)
|
| 96 |
-
# if provided, load from preloaded dictionaries
|
| 97 |
-
if path:
|
| 98 |
-
embed_dict = utils.parse_embedding(path)
|
| 99 |
-
utils.load_embedding(embed_dict, dictionary, emb)
|
| 100 |
-
return emb
|
| 101 |
-
|
| 102 |
-
# build shared embeddings (if applicable)
|
| 103 |
-
shared_encoder_embed_tokens, shared_decoder_embed_tokens = None, None
|
| 104 |
-
if args.share_all_embeddings:
|
| 105 |
-
if args.encoder_embed_dim != args.decoder_embed_dim:
|
| 106 |
-
raise ValueError(
|
| 107 |
-
"--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim"
|
| 108 |
-
)
|
| 109 |
-
if args.decoder_embed_path and (
|
| 110 |
-
args.decoder_embed_path != args.encoder_embed_path
|
| 111 |
-
):
|
| 112 |
-
raise ValueError(
|
| 113 |
-
"--share-all-embeddings not compatible with --decoder-embed-path"
|
| 114 |
-
)
|
| 115 |
-
shared_encoder_embed_tokens = FairseqMultiModel.build_shared_embeddings(
|
| 116 |
-
dicts=task.dicts,
|
| 117 |
-
langs=task.langs,
|
| 118 |
-
embed_dim=args.encoder_embed_dim,
|
| 119 |
-
build_embedding=build_embedding,
|
| 120 |
-
pretrained_embed_path=args.encoder_embed_path,
|
| 121 |
-
)
|
| 122 |
-
shared_decoder_embed_tokens = shared_encoder_embed_tokens
|
| 123 |
-
args.share_decoder_input_output_embed = True
|
| 124 |
-
else:
|
| 125 |
-
if args.share_encoder_embeddings:
|
| 126 |
-
shared_encoder_embed_tokens = FairseqMultiModel.build_shared_embeddings(
|
| 127 |
-
dicts=task.dicts,
|
| 128 |
-
langs=src_langs,
|
| 129 |
-
embed_dim=args.encoder_embed_dim,
|
| 130 |
-
build_embedding=build_embedding,
|
| 131 |
-
pretrained_embed_path=args.encoder_embed_path,
|
| 132 |
-
)
|
| 133 |
-
if args.share_decoder_embeddings:
|
| 134 |
-
shared_decoder_embed_tokens = FairseqMultiModel.build_shared_embeddings(
|
| 135 |
-
dicts=task.dicts,
|
| 136 |
-
langs=tgt_langs,
|
| 137 |
-
embed_dim=args.decoder_embed_dim,
|
| 138 |
-
build_embedding=build_embedding,
|
| 139 |
-
pretrained_embed_path=args.decoder_embed_path,
|
| 140 |
-
)
|
| 141 |
-
|
| 142 |
-
# encoders/decoders for each language
|
| 143 |
-
lang_encoders, lang_decoders = {}, {}
|
| 144 |
-
|
| 145 |
-
def get_encoder(lang):
|
| 146 |
-
if lang not in lang_encoders:
|
| 147 |
-
if shared_encoder_embed_tokens is not None:
|
| 148 |
-
encoder_embed_tokens = shared_encoder_embed_tokens
|
| 149 |
-
else:
|
| 150 |
-
encoder_embed_tokens = build_embedding(
|
| 151 |
-
task.dicts[lang],
|
| 152 |
-
args.encoder_embed_dim,
|
| 153 |
-
args.encoder_embed_path,
|
| 154 |
-
)
|
| 155 |
-
lang_encoders[lang] = cls._get_module_class(
|
| 156 |
-
True, args, task.dicts[lang], encoder_embed_tokens, src_langs
|
| 157 |
-
)
|
| 158 |
-
return lang_encoders[lang]
|
| 159 |
-
|
| 160 |
-
def get_decoder(lang):
|
| 161 |
-
if lang not in lang_decoders:
|
| 162 |
-
if shared_decoder_embed_tokens is not None:
|
| 163 |
-
decoder_embed_tokens = shared_decoder_embed_tokens
|
| 164 |
-
else:
|
| 165 |
-
decoder_embed_tokens = build_embedding(
|
| 166 |
-
task.dicts[lang],
|
| 167 |
-
args.decoder_embed_dim,
|
| 168 |
-
args.decoder_embed_path,
|
| 169 |
-
)
|
| 170 |
-
lang_decoders[lang] = cls._get_module_class(
|
| 171 |
-
False, args, task.dicts[lang], decoder_embed_tokens, tgt_langs
|
| 172 |
-
)
|
| 173 |
-
return lang_decoders[lang]
|
| 174 |
-
|
| 175 |
-
# shared encoders/decoders (if applicable)
|
| 176 |
-
shared_encoder, shared_decoder = None, None
|
| 177 |
-
if args.share_encoders:
|
| 178 |
-
shared_encoder = get_encoder(src_langs[0])
|
| 179 |
-
if args.share_decoders:
|
| 180 |
-
shared_decoder = get_decoder(tgt_langs[0])
|
| 181 |
-
|
| 182 |
-
encoders, decoders = OrderedDict(), OrderedDict()
|
| 183 |
-
for lang_pair, src, tgt in zip(task.model_lang_pairs, src_langs, tgt_langs):
|
| 184 |
-
encoders[lang_pair] = (
|
| 185 |
-
shared_encoder if shared_encoder is not None else get_encoder(src)
|
| 186 |
-
)
|
| 187 |
-
decoders[lang_pair] = (
|
| 188 |
-
shared_decoder if shared_decoder is not None else get_decoder(tgt)
|
| 189 |
-
)
|
| 190 |
-
|
| 191 |
-
return MultilingualTransformerModel(encoders, decoders)
|
| 192 |
-
|
| 193 |
-
@classmethod
|
| 194 |
-
def _get_module_class(cls, is_encoder, args, lang_dict, embed_tokens, langs):
|
| 195 |
-
module_class = TransformerEncoder if is_encoder else TransformerDecoder
|
| 196 |
-
return module_class(args, lang_dict, embed_tokens)
|
| 197 |
-
|
| 198 |
-
def load_state_dict(self, state_dict, strict=True, model_cfg=None):
|
| 199 |
-
state_dict_subset = state_dict.copy()
|
| 200 |
-
for k, _ in state_dict.items():
|
| 201 |
-
assert k.startswith("models.")
|
| 202 |
-
lang_pair = k.split(".")[1]
|
| 203 |
-
if lang_pair not in self.models:
|
| 204 |
-
del state_dict_subset[k]
|
| 205 |
-
super().load_state_dict(state_dict_subset, strict=strict, model_cfg=model_cfg)
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
@register_model_architecture("multilingual_transformer", "multilingual_transformer")
|
| 209 |
-
def base_multilingual_architecture(args):
|
| 210 |
-
base_architecture(args)
|
| 211 |
-
args.share_encoder_embeddings = getattr(args, "share_encoder_embeddings", False)
|
| 212 |
-
args.share_decoder_embeddings = getattr(args, "share_decoder_embeddings", False)
|
| 213 |
-
args.share_encoders = getattr(args, "share_encoders", False)
|
| 214 |
-
args.share_decoders = getattr(args, "share_decoders", False)
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
@register_model_architecture(
|
| 218 |
-
"multilingual_transformer", "multilingual_transformer_iwslt_de_en"
|
| 219 |
-
)
|
| 220 |
-
def multilingual_transformer_iwslt_de_en(args):
|
| 221 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
|
| 222 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 1024)
|
| 223 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 4)
|
| 224 |
-
args.encoder_layers = getattr(args, "encoder_layers", 6)
|
| 225 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 512)
|
| 226 |
-
args.decoder_ffn_embed_dim = getattr(args, "decoder_ffn_embed_dim", 1024)
|
| 227 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 4)
|
| 228 |
-
args.decoder_layers = getattr(args, "decoder_layers", 6)
|
| 229 |
-
base_multilingual_architecture(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/__init__.py
DELETED
|
@@ -1,13 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
"""isort:skip_file"""
|
| 6 |
-
|
| 7 |
-
from .fairseq_nat_model import *
|
| 8 |
-
from .nonautoregressive_transformer import *
|
| 9 |
-
from .nat_crf_transformer import *
|
| 10 |
-
from .iterative_nonautoregressive_transformer import *
|
| 11 |
-
from .cmlm_transformer import *
|
| 12 |
-
from .levenshtein_transformer import *
|
| 13 |
-
from .insertion_transformer import *
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/cmlm_transformer.py
DELETED
|
@@ -1,162 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
"""
|
| 7 |
-
This file implements:
|
| 8 |
-
Ghazvininejad, Marjan, et al.
|
| 9 |
-
"Constant-time machine translation with conditional masked language models."
|
| 10 |
-
arXiv preprint arXiv:1904.09324 (2019).
|
| 11 |
-
"""
|
| 12 |
-
|
| 13 |
-
from fairseq.models import register_model, register_model_architecture
|
| 14 |
-
from fairseq.models.nat import NATransformerModel
|
| 15 |
-
from fairseq.utils import new_arange
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
def _skeptical_unmasking(output_scores, output_masks, p):
|
| 19 |
-
sorted_index = output_scores.sort(-1)[1]
|
| 20 |
-
boundary_len = (
|
| 21 |
-
(output_masks.sum(1, keepdim=True).type_as(output_scores) - 2) * p
|
| 22 |
-
).long()
|
| 23 |
-
skeptical_mask = new_arange(output_masks) < boundary_len
|
| 24 |
-
return skeptical_mask.scatter(1, sorted_index, skeptical_mask)
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
@register_model("cmlm_transformer")
|
| 28 |
-
class CMLMNATransformerModel(NATransformerModel):
|
| 29 |
-
@staticmethod
|
| 30 |
-
def add_args(parser):
|
| 31 |
-
NATransformerModel.add_args(parser)
|
| 32 |
-
|
| 33 |
-
def forward(
|
| 34 |
-
self, src_tokens, src_lengths, prev_output_tokens, tgt_tokens, **kwargs
|
| 35 |
-
):
|
| 36 |
-
assert not self.decoder.src_embedding_copy, "do not support embedding copy."
|
| 37 |
-
|
| 38 |
-
# encoding
|
| 39 |
-
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
|
| 40 |
-
# length prediction
|
| 41 |
-
length_out = self.decoder.forward_length(
|
| 42 |
-
normalize=False, encoder_out=encoder_out
|
| 43 |
-
)
|
| 44 |
-
length_tgt = self.decoder.forward_length_prediction(
|
| 45 |
-
length_out, encoder_out, tgt_tokens
|
| 46 |
-
)
|
| 47 |
-
|
| 48 |
-
# decoding
|
| 49 |
-
word_ins_out = self.decoder(
|
| 50 |
-
normalize=False,
|
| 51 |
-
prev_output_tokens=prev_output_tokens,
|
| 52 |
-
encoder_out=encoder_out,
|
| 53 |
-
)
|
| 54 |
-
word_ins_mask = prev_output_tokens.eq(self.unk)
|
| 55 |
-
|
| 56 |
-
return {
|
| 57 |
-
"word_ins": {
|
| 58 |
-
"out": word_ins_out,
|
| 59 |
-
"tgt": tgt_tokens,
|
| 60 |
-
"mask": word_ins_mask,
|
| 61 |
-
"ls": self.args.label_smoothing,
|
| 62 |
-
"nll_loss": True,
|
| 63 |
-
},
|
| 64 |
-
"length": {
|
| 65 |
-
"out": length_out,
|
| 66 |
-
"tgt": length_tgt,
|
| 67 |
-
"factor": self.decoder.length_loss_factor,
|
| 68 |
-
},
|
| 69 |
-
}
|
| 70 |
-
|
| 71 |
-
def forward_decoder(self, decoder_out, encoder_out, decoding_format=None, **kwargs):
|
| 72 |
-
|
| 73 |
-
step = decoder_out.step
|
| 74 |
-
max_step = decoder_out.max_step
|
| 75 |
-
|
| 76 |
-
output_tokens = decoder_out.output_tokens
|
| 77 |
-
output_scores = decoder_out.output_scores
|
| 78 |
-
history = decoder_out.history
|
| 79 |
-
|
| 80 |
-
# execute the decoder
|
| 81 |
-
output_masks = output_tokens.eq(self.unk)
|
| 82 |
-
_scores, _tokens = self.decoder(
|
| 83 |
-
normalize=True,
|
| 84 |
-
prev_output_tokens=output_tokens,
|
| 85 |
-
encoder_out=encoder_out,
|
| 86 |
-
).max(-1)
|
| 87 |
-
output_tokens.masked_scatter_(output_masks, _tokens[output_masks])
|
| 88 |
-
output_scores.masked_scatter_(output_masks, _scores[output_masks])
|
| 89 |
-
|
| 90 |
-
if history is not None:
|
| 91 |
-
history.append(output_tokens.clone())
|
| 92 |
-
|
| 93 |
-
# skeptical decoding (depend on the maximum decoding steps.)
|
| 94 |
-
if (step + 1) < max_step:
|
| 95 |
-
skeptical_mask = _skeptical_unmasking(
|
| 96 |
-
output_scores, output_tokens.ne(self.pad), 1 - (step + 1) / max_step
|
| 97 |
-
)
|
| 98 |
-
|
| 99 |
-
output_tokens.masked_fill_(skeptical_mask, self.unk)
|
| 100 |
-
output_scores.masked_fill_(skeptical_mask, 0.0)
|
| 101 |
-
|
| 102 |
-
if history is not None:
|
| 103 |
-
history.append(output_tokens.clone())
|
| 104 |
-
|
| 105 |
-
return decoder_out._replace(
|
| 106 |
-
output_tokens=output_tokens,
|
| 107 |
-
output_scores=output_scores,
|
| 108 |
-
attn=None,
|
| 109 |
-
history=history,
|
| 110 |
-
)
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
@register_model_architecture("cmlm_transformer", "cmlm_transformer")
|
| 114 |
-
def cmlm_base_architecture(args):
|
| 115 |
-
args.encoder_embed_path = getattr(args, "encoder_embed_path", None)
|
| 116 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
|
| 117 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 2048)
|
| 118 |
-
args.encoder_layers = getattr(args, "encoder_layers", 6)
|
| 119 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8)
|
| 120 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
|
| 121 |
-
args.encoder_learned_pos = getattr(args, "encoder_learned_pos", False)
|
| 122 |
-
args.decoder_embed_path = getattr(args, "decoder_embed_path", None)
|
| 123 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", args.encoder_embed_dim)
|
| 124 |
-
args.decoder_ffn_embed_dim = getattr(
|
| 125 |
-
args, "decoder_ffn_embed_dim", args.encoder_ffn_embed_dim
|
| 126 |
-
)
|
| 127 |
-
args.decoder_layers = getattr(args, "decoder_layers", 6)
|
| 128 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 8)
|
| 129 |
-
args.decoder_normalize_before = getattr(args, "decoder_normalize_before", False)
|
| 130 |
-
args.decoder_learned_pos = getattr(args, "decoder_learned_pos", False)
|
| 131 |
-
args.attention_dropout = getattr(args, "attention_dropout", 0.0)
|
| 132 |
-
args.activation_dropout = getattr(args, "activation_dropout", 0.0)
|
| 133 |
-
args.activation_fn = getattr(args, "activation_fn", "relu")
|
| 134 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 135 |
-
args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
|
| 136 |
-
args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
|
| 137 |
-
args.share_decoder_input_output_embed = getattr(
|
| 138 |
-
args, "share_decoder_input_output_embed", False
|
| 139 |
-
)
|
| 140 |
-
args.share_all_embeddings = getattr(args, "share_all_embeddings", True)
|
| 141 |
-
args.no_token_positional_embeddings = getattr(
|
| 142 |
-
args, "no_token_positional_embeddings", False
|
| 143 |
-
)
|
| 144 |
-
args.adaptive_input = getattr(args, "adaptive_input", False)
|
| 145 |
-
args.apply_bert_init = getattr(args, "apply_bert_init", False)
|
| 146 |
-
|
| 147 |
-
args.decoder_output_dim = getattr(
|
| 148 |
-
args, "decoder_output_dim", args.decoder_embed_dim
|
| 149 |
-
)
|
| 150 |
-
args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim)
|
| 151 |
-
|
| 152 |
-
# --- special arguments ---
|
| 153 |
-
args.sg_length_pred = getattr(args, "sg_length_pred", False)
|
| 154 |
-
args.pred_length_offset = getattr(args, "pred_length_offset", False)
|
| 155 |
-
args.length_loss_factor = getattr(args, "length_loss_factor", 0.1)
|
| 156 |
-
args.ngram_predictor = getattr(args, "ngram_predictor", 1)
|
| 157 |
-
args.src_embedding_copy = getattr(args, "src_embedding_copy", False)
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
@register_model_architecture("cmlm_transformer", "cmlm_transformer_wmt_en_de")
|
| 161 |
-
def cmlm_wmt_en_de(args):
|
| 162 |
-
cmlm_base_architecture(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/fairseq_nat_model.py
DELETED
|
@@ -1,172 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import math
|
| 7 |
-
|
| 8 |
-
import torch
|
| 9 |
-
from fairseq.models.transformer import (
|
| 10 |
-
TransformerDecoder,
|
| 11 |
-
TransformerEncoder,
|
| 12 |
-
TransformerModel,
|
| 13 |
-
)
|
| 14 |
-
from fairseq.modules.transformer_sentence_encoder import init_bert_params
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
def ensemble_encoder(func):
|
| 18 |
-
def wrapper(self, *args, **kwargs):
|
| 19 |
-
if self.ensemble_models is None or len(self.ensemble_models) == 1:
|
| 20 |
-
return func(self, *args, **kwargs)
|
| 21 |
-
encoder_outs = [
|
| 22 |
-
func(model, *args, **kwargs, return_all_hiddens=True)
|
| 23 |
-
for model in self.ensemble_models
|
| 24 |
-
]
|
| 25 |
-
_encoder_out = encoder_outs[0].copy()
|
| 26 |
-
|
| 27 |
-
def stack(key):
|
| 28 |
-
outs = [e[key][0] for e in encoder_outs]
|
| 29 |
-
return [torch.stack(outs, -1) if outs[0] is not None else None]
|
| 30 |
-
|
| 31 |
-
_encoder_out["encoder_out"] = stack("encoder_out")
|
| 32 |
-
_encoder_out["encoder_embedding"] = stack("encoder_embedding")
|
| 33 |
-
|
| 34 |
-
num_layers = len(_encoder_out["encoder_states"])
|
| 35 |
-
if num_layers > 0:
|
| 36 |
-
_encoder_out["encoder_states"] = [
|
| 37 |
-
torch.stack([e["encoder_states"][i] for e in encoder_outs], -1)
|
| 38 |
-
for i in range(num_layers)
|
| 39 |
-
]
|
| 40 |
-
return _encoder_out
|
| 41 |
-
|
| 42 |
-
return wrapper
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
def ensemble_decoder(func):
|
| 46 |
-
def wrapper(self, normalize=False, encoder_out=None, *args, **kwargs):
|
| 47 |
-
if self.ensemble_models is None or len(self.ensemble_models) == 1:
|
| 48 |
-
return func(
|
| 49 |
-
self, normalize=normalize, encoder_out=encoder_out, *args, **kwargs
|
| 50 |
-
)
|
| 51 |
-
|
| 52 |
-
def _replace(encoder_out, new_val):
|
| 53 |
-
new_encoder_out = encoder_out.copy()
|
| 54 |
-
new_encoder_out["encoder_out"] = [new_val]
|
| 55 |
-
return new_encoder_out
|
| 56 |
-
|
| 57 |
-
action_outs = [
|
| 58 |
-
func(
|
| 59 |
-
model,
|
| 60 |
-
normalize=normalize,
|
| 61 |
-
encoder_out=_replace(
|
| 62 |
-
encoder_out, encoder_out["encoder_out"][0][:, :, :, i]
|
| 63 |
-
),
|
| 64 |
-
*args,
|
| 65 |
-
**kwargs
|
| 66 |
-
)
|
| 67 |
-
for i, model in enumerate(self.ensemble_models)
|
| 68 |
-
]
|
| 69 |
-
|
| 70 |
-
if not isinstance(action_outs[0], tuple): # return multiple values
|
| 71 |
-
action_outs = [[a] for a in action_outs]
|
| 72 |
-
else:
|
| 73 |
-
action_outs = [list(a) for a in action_outs]
|
| 74 |
-
|
| 75 |
-
ensembled_outs = []
|
| 76 |
-
for i in range(len(action_outs[0])):
|
| 77 |
-
if i == 0 and normalize:
|
| 78 |
-
ensembled_outs += [
|
| 79 |
-
torch.logsumexp(
|
| 80 |
-
torch.stack([a[i] for a in action_outs], -1), dim=-1
|
| 81 |
-
)
|
| 82 |
-
- math.log(len(self.ensemble_models))
|
| 83 |
-
]
|
| 84 |
-
elif action_outs[0][i] is not None:
|
| 85 |
-
ensembled_outs += [torch.stack([a[i] for a in action_outs], -1)]
|
| 86 |
-
else:
|
| 87 |
-
ensembled_outs += [None]
|
| 88 |
-
|
| 89 |
-
if len(ensembled_outs) == 1:
|
| 90 |
-
return ensembled_outs[0]
|
| 91 |
-
return tuple(ensembled_outs)
|
| 92 |
-
|
| 93 |
-
return wrapper
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
class FairseqNATModel(TransformerModel):
|
| 97 |
-
"""
|
| 98 |
-
Abstract class for all nonautoregressive-based models
|
| 99 |
-
"""
|
| 100 |
-
|
| 101 |
-
def __init__(self, args, encoder, decoder):
|
| 102 |
-
super().__init__(args, encoder, decoder)
|
| 103 |
-
self.tgt_dict = decoder.dictionary
|
| 104 |
-
self.bos = decoder.dictionary.bos()
|
| 105 |
-
self.eos = decoder.dictionary.eos()
|
| 106 |
-
self.pad = decoder.dictionary.pad()
|
| 107 |
-
self.unk = decoder.dictionary.unk()
|
| 108 |
-
|
| 109 |
-
self.ensemble_models = None
|
| 110 |
-
|
| 111 |
-
@property
|
| 112 |
-
def allow_length_beam(self):
|
| 113 |
-
return False
|
| 114 |
-
|
| 115 |
-
@property
|
| 116 |
-
def allow_ensemble(self):
|
| 117 |
-
return True
|
| 118 |
-
|
| 119 |
-
def enable_ensemble(self, models):
|
| 120 |
-
self.encoder.ensemble_models = [m.encoder for m in models]
|
| 121 |
-
self.decoder.ensemble_models = [m.decoder for m in models]
|
| 122 |
-
|
| 123 |
-
@staticmethod
|
| 124 |
-
def add_args(parser):
|
| 125 |
-
TransformerModel.add_args(parser)
|
| 126 |
-
parser.add_argument(
|
| 127 |
-
"--apply-bert-init",
|
| 128 |
-
action="store_true",
|
| 129 |
-
help="use custom param initialization for BERT",
|
| 130 |
-
)
|
| 131 |
-
|
| 132 |
-
@classmethod
|
| 133 |
-
def build_decoder(cls, args, tgt_dict, embed_tokens):
|
| 134 |
-
decoder = FairseqNATDecoder(args, tgt_dict, embed_tokens)
|
| 135 |
-
if getattr(args, "apply_bert_init", False):
|
| 136 |
-
decoder.apply(init_bert_params)
|
| 137 |
-
return decoder
|
| 138 |
-
|
| 139 |
-
@classmethod
|
| 140 |
-
def build_encoder(cls, args, src_dict, embed_tokens):
|
| 141 |
-
encoder = FairseqNATEncoder(args, src_dict, embed_tokens)
|
| 142 |
-
if getattr(args, "apply_bert_init", False):
|
| 143 |
-
encoder.apply(init_bert_params)
|
| 144 |
-
return encoder
|
| 145 |
-
|
| 146 |
-
def forward_encoder(self, encoder_inputs):
|
| 147 |
-
return self.encoder(*encoder_inputs)
|
| 148 |
-
|
| 149 |
-
def forward_decoder(self, *args, **kwargs):
|
| 150 |
-
return NotImplementedError
|
| 151 |
-
|
| 152 |
-
def initialize_output_tokens(self, *args, **kwargs):
|
| 153 |
-
return NotImplementedError
|
| 154 |
-
|
| 155 |
-
def forward(self, *args, **kwargs):
|
| 156 |
-
return NotImplementedError
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
class FairseqNATEncoder(TransformerEncoder):
|
| 160 |
-
def __init__(self, args, dictionary, embed_tokens):
|
| 161 |
-
super().__init__(args, dictionary, embed_tokens)
|
| 162 |
-
self.ensemble_models = None
|
| 163 |
-
|
| 164 |
-
@ensemble_encoder
|
| 165 |
-
def forward(self, *args, **kwargs):
|
| 166 |
-
return super().forward(*args, **kwargs)
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
class FairseqNATDecoder(TransformerDecoder):
|
| 170 |
-
def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False):
|
| 171 |
-
super().__init__(args, dictionary, embed_tokens, no_encoder_attn)
|
| 172 |
-
self.ensemble_models = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/insertion_transformer.py
DELETED
|
@@ -1,280 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import numpy as np
|
| 7 |
-
import torch
|
| 8 |
-
import torch.nn.functional as F
|
| 9 |
-
from fairseq.models import register_model, register_model_architecture
|
| 10 |
-
from fairseq.models.nat import (
|
| 11 |
-
FairseqNATModel,
|
| 12 |
-
LevenshteinTransformerDecoder,
|
| 13 |
-
LevenshteinTransformerModel,
|
| 14 |
-
ensemble_decoder,
|
| 15 |
-
)
|
| 16 |
-
from fairseq.models.transformer import Linear
|
| 17 |
-
from fairseq.modules.transformer_sentence_encoder import init_bert_params
|
| 18 |
-
from fairseq.utils import new_arange
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
class NegativeDistanceScore(object):
|
| 22 |
-
def __init__(self):
|
| 23 |
-
|
| 24 |
-
# pre-compute some values
|
| 25 |
-
self.scores = {}
|
| 26 |
-
|
| 27 |
-
self.scores[0.5] = self.compute_score_full(50, 0.5)
|
| 28 |
-
self.scores[1.0] = self.compute_score_full(50, 1.0)
|
| 29 |
-
self.scores[2.0] = self.compute_score_full(50, 2.0)
|
| 30 |
-
|
| 31 |
-
def __call__(self, i, L, tau):
|
| 32 |
-
if (tau is None) or (tau > 1000):
|
| 33 |
-
return 1 / L
|
| 34 |
-
|
| 35 |
-
if tau in self.scores:
|
| 36 |
-
if L < self.scores[tau].shape[0]:
|
| 37 |
-
return self.scores[tau][L - 1, i]
|
| 38 |
-
return self.compute_score(L, tau)[i]
|
| 39 |
-
|
| 40 |
-
def compute_score(self, L, tau):
|
| 41 |
-
s = np.array([-abs(L / 2 - i) / tau for i in range(L)])
|
| 42 |
-
s = np.exp(s - s.max())
|
| 43 |
-
return s / s.sum()
|
| 44 |
-
|
| 45 |
-
def compute_score_full(self, L, tau):
|
| 46 |
-
s = -abs(np.arange(0, L - 1)[:, None] / 2 - np.arange(L)[None, :]) / tau
|
| 47 |
-
s = np.tril(s, 0) + np.triu(s - float("inf"), 1)
|
| 48 |
-
s = np.exp(s - s.max(1, keepdims=True))
|
| 49 |
-
return s / s.sum(1, keepdims=True)
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
neg_scorer = NegativeDistanceScore()
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
def _get_ins_targets(in_tokens, out_tokens, padding_idx, unk_idx, vocab_size, tau=None):
|
| 56 |
-
try:
|
| 57 |
-
from fairseq import libnat
|
| 58 |
-
except ImportError as e:
|
| 59 |
-
import sys
|
| 60 |
-
|
| 61 |
-
sys.stderr.write("ERROR: missing libnat. run `pip install --editable .`\n")
|
| 62 |
-
raise e
|
| 63 |
-
|
| 64 |
-
B = in_tokens.size(0)
|
| 65 |
-
T = in_tokens.size(1)
|
| 66 |
-
V = vocab_size
|
| 67 |
-
|
| 68 |
-
with torch.cuda.device_of(in_tokens):
|
| 69 |
-
in_tokens_list = [
|
| 70 |
-
[t for t in s if t != padding_idx] for i, s in enumerate(in_tokens.tolist())
|
| 71 |
-
]
|
| 72 |
-
out_tokens_list = [
|
| 73 |
-
[t for t in s if t != padding_idx]
|
| 74 |
-
for i, s in enumerate(out_tokens.tolist())
|
| 75 |
-
]
|
| 76 |
-
|
| 77 |
-
full_labels = libnat.suggested_ed2_path(
|
| 78 |
-
in_tokens_list, out_tokens_list, padding_idx
|
| 79 |
-
)
|
| 80 |
-
insert_labels = [a[:-1] for a in full_labels]
|
| 81 |
-
|
| 82 |
-
# numericalize1
|
| 83 |
-
insert_label_tensors = in_tokens.new_zeros(B * (T - 1) * V).float()
|
| 84 |
-
insert_index, insert_labels = zip(
|
| 85 |
-
*[
|
| 86 |
-
(w + (j + i * (T - 1)) * V, neg_scorer(k, len(label), tau))
|
| 87 |
-
for i, labels in enumerate(insert_labels)
|
| 88 |
-
for j, label in enumerate(labels[1:-1])
|
| 89 |
-
for k, w in enumerate(label)
|
| 90 |
-
]
|
| 91 |
-
) # HACK 1:-1
|
| 92 |
-
insert_index, insert_labels = [
|
| 93 |
-
torch.tensor(list(a), device=in_tokens.device)
|
| 94 |
-
for a in [insert_index, insert_labels]
|
| 95 |
-
]
|
| 96 |
-
insert_label_tensors.scatter_(0, insert_index.long(), insert_labels)
|
| 97 |
-
insert_label_tensors = insert_label_tensors.view(B, T - 1, V)
|
| 98 |
-
|
| 99 |
-
return insert_label_tensors
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
def _apply_ins_words(in_tokens, in_scores, word_ins_pred, word_ins_scores, padding_idx):
|
| 103 |
-
|
| 104 |
-
padding_masks = in_tokens[:, 1:].eq(padding_idx)
|
| 105 |
-
word_ins_scores.masked_fill_(padding_masks, 0.0)
|
| 106 |
-
word_ins_pred.masked_fill_(padding_masks, padding_idx)
|
| 107 |
-
|
| 108 |
-
in_coords = new_arange(in_tokens).type_as(in_scores)
|
| 109 |
-
|
| 110 |
-
# shift all padding predictions to infinite
|
| 111 |
-
out_coords = (in_coords[:, 1:] - 0.5).masked_fill(
|
| 112 |
-
word_ins_pred.eq(padding_idx), float("inf")
|
| 113 |
-
)
|
| 114 |
-
out_coords = torch.cat([in_coords, out_coords], 1).sort(-1)[1]
|
| 115 |
-
out_tokens = torch.cat([in_tokens, word_ins_pred], 1).gather(1, out_coords)
|
| 116 |
-
out_scores = torch.cat([in_scores, word_ins_scores], 1).gather(1, out_coords)
|
| 117 |
-
return out_tokens, out_scores
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
@register_model("insertion_transformer")
|
| 121 |
-
class InsertionTransformerModel(LevenshteinTransformerModel):
|
| 122 |
-
def __init__(self, args, encoder, decoder):
|
| 123 |
-
super().__init__(args, encoder, decoder)
|
| 124 |
-
|
| 125 |
-
@staticmethod
|
| 126 |
-
def add_args(parser):
|
| 127 |
-
FairseqNATModel.add_args(parser)
|
| 128 |
-
parser.add_argument("--label-tau", default=None, type=float)
|
| 129 |
-
|
| 130 |
-
@classmethod
|
| 131 |
-
def build_decoder(cls, args, tgt_dict, embed_tokens):
|
| 132 |
-
decoder = InsertionTransformerDecoder(args, tgt_dict, embed_tokens)
|
| 133 |
-
if getattr(args, "apply_bert_init", False):
|
| 134 |
-
decoder.apply(init_bert_params)
|
| 135 |
-
return decoder
|
| 136 |
-
|
| 137 |
-
def forward(
|
| 138 |
-
self, src_tokens, src_lengths, prev_output_tokens, tgt_tokens, **kwargs
|
| 139 |
-
):
|
| 140 |
-
|
| 141 |
-
assert tgt_tokens is not None, "forward function only supports training."
|
| 142 |
-
|
| 143 |
-
# encoding
|
| 144 |
-
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
|
| 145 |
-
|
| 146 |
-
# generate training labels for insertion
|
| 147 |
-
word_ins_out = self.decoder.forward_word_ins(
|
| 148 |
-
normalize=False,
|
| 149 |
-
prev_output_tokens=prev_output_tokens,
|
| 150 |
-
encoder_out=encoder_out,
|
| 151 |
-
)
|
| 152 |
-
|
| 153 |
-
word_ins_tgt = _get_ins_targets(
|
| 154 |
-
prev_output_tokens,
|
| 155 |
-
tgt_tokens,
|
| 156 |
-
self.pad,
|
| 157 |
-
self.unk,
|
| 158 |
-
len(self.tgt_dict),
|
| 159 |
-
tau=self.decoder.label_tau,
|
| 160 |
-
).type_as(word_ins_out)
|
| 161 |
-
word_ins_masks = prev_output_tokens[:, 1:].ne(self.pad)
|
| 162 |
-
|
| 163 |
-
return {
|
| 164 |
-
"word_ins": {
|
| 165 |
-
"out": word_ins_out,
|
| 166 |
-
"tgt": word_ins_tgt,
|
| 167 |
-
"mask": word_ins_masks,
|
| 168 |
-
"ls": self.args.label_smoothing,
|
| 169 |
-
"nll_loss": True,
|
| 170 |
-
}
|
| 171 |
-
}
|
| 172 |
-
|
| 173 |
-
def forward_decoder(
|
| 174 |
-
self, decoder_out, encoder_out, eos_penalty=0.0, max_ratio=None, **kwargs
|
| 175 |
-
):
|
| 176 |
-
|
| 177 |
-
output_tokens = decoder_out.output_tokens
|
| 178 |
-
output_scores = decoder_out.output_scores
|
| 179 |
-
history = decoder_out.history
|
| 180 |
-
|
| 181 |
-
# TODO: decoding for InsertionTransformer
|
| 182 |
-
word_ins_score = self.decoder.forward_word_ins(
|
| 183 |
-
normalize=True, prev_output_tokens=output_tokens, encoder_out=encoder_out
|
| 184 |
-
)
|
| 185 |
-
|
| 186 |
-
if eos_penalty > 0.0:
|
| 187 |
-
word_ins_score[:, :, self.pad] -= eos_penalty
|
| 188 |
-
word_ins_score, word_ins_pred = word_ins_score.max(-1)
|
| 189 |
-
output_tokens, output_scores = _apply_ins_words(
|
| 190 |
-
output_tokens, output_scores, word_ins_pred, word_ins_score, self.pad
|
| 191 |
-
)
|
| 192 |
-
|
| 193 |
-
# delete some unnecessary paddings
|
| 194 |
-
cut_off = output_tokens.ne(self.pad).sum(1).max()
|
| 195 |
-
output_tokens = output_tokens[:, :cut_off]
|
| 196 |
-
output_scores = output_scores[:, :cut_off]
|
| 197 |
-
|
| 198 |
-
if history is not None:
|
| 199 |
-
history.append(output_tokens.clone())
|
| 200 |
-
|
| 201 |
-
return decoder_out._replace(
|
| 202 |
-
output_tokens=output_tokens,
|
| 203 |
-
output_scores=output_scores,
|
| 204 |
-
attn=None,
|
| 205 |
-
history=history,
|
| 206 |
-
)
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
class InsertionTransformerDecoder(LevenshteinTransformerDecoder):
|
| 210 |
-
def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False):
|
| 211 |
-
# use the TransformerDecoder's __init__
|
| 212 |
-
super(LevenshteinTransformerDecoder, self).__init__(
|
| 213 |
-
args, dictionary, embed_tokens, no_encoder_attn=no_encoder_attn
|
| 214 |
-
)
|
| 215 |
-
|
| 216 |
-
self.dictionary = dictionary
|
| 217 |
-
self.bos = dictionary.bos()
|
| 218 |
-
self.unk = dictionary.unk()
|
| 219 |
-
self.eos = dictionary.eos()
|
| 220 |
-
self.pool_out = Linear(self.output_embed_dim * 2, self.output_embed_dim)
|
| 221 |
-
|
| 222 |
-
self.label_tau = getattr(args, "label_tau", None)
|
| 223 |
-
|
| 224 |
-
@ensemble_decoder
|
| 225 |
-
def forward_word_ins(self, normalize, encoder_out, prev_output_tokens):
|
| 226 |
-
features = self.extract_features(prev_output_tokens, encoder_out=encoder_out)[0]
|
| 227 |
-
features = self.pool_out(
|
| 228 |
-
torch.cat([features[:, :-1, :], features[:, 1:, :]], 2)
|
| 229 |
-
)
|
| 230 |
-
decoder_out = self.output_layer(features)
|
| 231 |
-
return F.log_softmax(decoder_out, -1) if normalize else decoder_out
|
| 232 |
-
|
| 233 |
-
def forward_mask_ins(self, *args, **kwargs):
|
| 234 |
-
raise NotImplementedError
|
| 235 |
-
|
| 236 |
-
def forward_word_del(self, *args, **kwargs):
|
| 237 |
-
raise NotImplementedError
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
@register_model_architecture("insertion_transformer", "insertion_transformer")
|
| 241 |
-
def insertion_base_architecture(args):
|
| 242 |
-
args.encoder_embed_path = getattr(args, "encoder_embed_path", None)
|
| 243 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
|
| 244 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 2048)
|
| 245 |
-
args.encoder_layers = getattr(args, "encoder_layers", 6)
|
| 246 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8)
|
| 247 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
|
| 248 |
-
args.encoder_learned_pos = getattr(args, "encoder_learned_pos", False)
|
| 249 |
-
args.decoder_embed_path = getattr(args, "decoder_embed_path", None)
|
| 250 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", args.encoder_embed_dim)
|
| 251 |
-
args.decoder_ffn_embed_dim = getattr(
|
| 252 |
-
args, "decoder_ffn_embed_dim", args.encoder_ffn_embed_dim
|
| 253 |
-
)
|
| 254 |
-
args.decoder_layers = getattr(args, "decoder_layers", 6)
|
| 255 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 8)
|
| 256 |
-
args.decoder_normalize_before = getattr(args, "decoder_normalize_before", False)
|
| 257 |
-
args.decoder_learned_pos = getattr(args, "decoder_learned_pos", False)
|
| 258 |
-
args.attention_dropout = getattr(args, "attention_dropout", 0.0)
|
| 259 |
-
args.activation_dropout = getattr(args, "activation_dropout", 0.0)
|
| 260 |
-
args.activation_fn = getattr(args, "activation_fn", "relu")
|
| 261 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 262 |
-
args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
|
| 263 |
-
args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
|
| 264 |
-
args.share_decoder_input_output_embed = getattr(
|
| 265 |
-
args, "share_decoder_input_output_embed", False
|
| 266 |
-
)
|
| 267 |
-
args.share_all_embeddings = getattr(args, "share_all_embeddings", False)
|
| 268 |
-
args.no_token_positional_embeddings = getattr(
|
| 269 |
-
args, "no_token_positional_embeddings", False
|
| 270 |
-
)
|
| 271 |
-
args.adaptive_input = getattr(args, "adaptive_input", False)
|
| 272 |
-
args.apply_bert_init = getattr(args, "apply_bert_init", False)
|
| 273 |
-
|
| 274 |
-
args.decoder_output_dim = getattr(
|
| 275 |
-
args, "decoder_output_dim", args.decoder_embed_dim
|
| 276 |
-
)
|
| 277 |
-
args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim)
|
| 278 |
-
|
| 279 |
-
# special for insertion transformer
|
| 280 |
-
args.label_tau = getattr(args, "label_tau", None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/iterative_nonautoregressive_transformer.py
DELETED
|
@@ -1,228 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import torch
|
| 7 |
-
from fairseq.models import register_model, register_model_architecture
|
| 8 |
-
from fairseq.models.nat import NATransformerModel
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
def _sequential_poisoning(s, V, beta=0.33, bos=2, eos=3, pad=1):
|
| 12 |
-
# s: input batch
|
| 13 |
-
# V: vocabulary size
|
| 14 |
-
rand_words = torch.randint(low=4, high=V, size=s.size(), device=s.device)
|
| 15 |
-
choices = torch.rand(size=s.size(), device=s.device)
|
| 16 |
-
choices.masked_fill_((s == pad) | (s == bos) | (s == eos), 1)
|
| 17 |
-
|
| 18 |
-
replace = choices < beta / 3
|
| 19 |
-
repeat = (choices >= beta / 3) & (choices < beta * 2 / 3)
|
| 20 |
-
swap = (choices >= beta * 2 / 3) & (choices < beta)
|
| 21 |
-
safe = choices >= beta
|
| 22 |
-
|
| 23 |
-
for i in range(s.size(1) - 1):
|
| 24 |
-
rand_word = rand_words[:, i]
|
| 25 |
-
next_word = s[:, i + 1]
|
| 26 |
-
self_word = s[:, i]
|
| 27 |
-
|
| 28 |
-
replace_i = replace[:, i]
|
| 29 |
-
swap_i = swap[:, i] & (next_word != 3)
|
| 30 |
-
repeat_i = repeat[:, i] & (next_word != 3)
|
| 31 |
-
safe_i = safe[:, i] | ((next_word == 3) & (~replace_i))
|
| 32 |
-
|
| 33 |
-
s[:, i] = (
|
| 34 |
-
self_word * (safe_i | repeat_i).long()
|
| 35 |
-
+ next_word * swap_i.long()
|
| 36 |
-
+ rand_word * replace_i.long()
|
| 37 |
-
)
|
| 38 |
-
s[:, i + 1] = (
|
| 39 |
-
next_word * (safe_i | replace_i).long()
|
| 40 |
-
+ self_word * (swap_i | repeat_i).long()
|
| 41 |
-
)
|
| 42 |
-
return s
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
def gumbel_noise(input, TINY=1e-8):
|
| 46 |
-
return (
|
| 47 |
-
input.new_zeros(*input.size())
|
| 48 |
-
.uniform_()
|
| 49 |
-
.add_(TINY)
|
| 50 |
-
.log_()
|
| 51 |
-
.neg_()
|
| 52 |
-
.add_(TINY)
|
| 53 |
-
.log_()
|
| 54 |
-
.neg_()
|
| 55 |
-
)
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
@register_model("iterative_nonautoregressive_transformer")
|
| 59 |
-
class IterNATransformerModel(NATransformerModel):
|
| 60 |
-
@staticmethod
|
| 61 |
-
def add_args(parser):
|
| 62 |
-
NATransformerModel.add_args(parser)
|
| 63 |
-
parser.add_argument(
|
| 64 |
-
"--train-step",
|
| 65 |
-
type=int,
|
| 66 |
-
help="number of refinement iterations during training",
|
| 67 |
-
)
|
| 68 |
-
parser.add_argument(
|
| 69 |
-
"--dae-ratio",
|
| 70 |
-
type=float,
|
| 71 |
-
help="the probability of switching to the denoising auto-encoder loss",
|
| 72 |
-
)
|
| 73 |
-
parser.add_argument(
|
| 74 |
-
"--stochastic-approx",
|
| 75 |
-
action="store_true",
|
| 76 |
-
help="sampling from the decoder as the inputs for next iteration",
|
| 77 |
-
)
|
| 78 |
-
|
| 79 |
-
@classmethod
|
| 80 |
-
def build_model(cls, args, task):
|
| 81 |
-
model = super().build_model(args, task)
|
| 82 |
-
model.train_step = getattr(args, "train_step", 4)
|
| 83 |
-
model.dae_ratio = getattr(args, "dae_ratio", 0.5)
|
| 84 |
-
model.stochastic_approx = getattr(args, "stochastic_approx", False)
|
| 85 |
-
return model
|
| 86 |
-
|
| 87 |
-
def forward(
|
| 88 |
-
self, src_tokens, src_lengths, prev_output_tokens, tgt_tokens, **kwargs
|
| 89 |
-
):
|
| 90 |
-
|
| 91 |
-
B, T = prev_output_tokens.size()
|
| 92 |
-
|
| 93 |
-
# encoding
|
| 94 |
-
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
|
| 95 |
-
|
| 96 |
-
# length prediction
|
| 97 |
-
length_out = self.decoder.forward_length(
|
| 98 |
-
normalize=False, encoder_out=encoder_out
|
| 99 |
-
)
|
| 100 |
-
length_tgt = self.decoder.forward_length_prediction(
|
| 101 |
-
length_out, encoder_out, tgt_tokens
|
| 102 |
-
)
|
| 103 |
-
|
| 104 |
-
# decoding
|
| 105 |
-
word_ins_outs, word_ins_tgts, word_ins_masks = [], [], []
|
| 106 |
-
for t in range(self.train_step):
|
| 107 |
-
word_ins_out = self.decoder(
|
| 108 |
-
normalize=False,
|
| 109 |
-
prev_output_tokens=prev_output_tokens,
|
| 110 |
-
encoder_out=encoder_out,
|
| 111 |
-
step=t,
|
| 112 |
-
)
|
| 113 |
-
word_ins_tgt = tgt_tokens
|
| 114 |
-
word_ins_mask = word_ins_tgt.ne(self.pad)
|
| 115 |
-
|
| 116 |
-
word_ins_outs.append(word_ins_out)
|
| 117 |
-
word_ins_tgts.append(word_ins_tgt)
|
| 118 |
-
word_ins_masks.append(word_ins_mask)
|
| 119 |
-
|
| 120 |
-
if t < (self.train_step - 1):
|
| 121 |
-
# prediction for next iteration
|
| 122 |
-
if self.stochastic_approx:
|
| 123 |
-
word_ins_prediction = (
|
| 124 |
-
word_ins_out + gumbel_noise(word_ins_out)
|
| 125 |
-
).max(-1)[1]
|
| 126 |
-
else:
|
| 127 |
-
word_ins_prediction = word_ins_out.max(-1)[1]
|
| 128 |
-
|
| 129 |
-
prev_output_tokens = prev_output_tokens.masked_scatter(
|
| 130 |
-
word_ins_mask, word_ins_prediction[word_ins_mask]
|
| 131 |
-
)
|
| 132 |
-
|
| 133 |
-
if self.dae_ratio > 0:
|
| 134 |
-
# we do not perform denoising for the first iteration
|
| 135 |
-
corrputed = (
|
| 136 |
-
torch.rand(size=(B,), device=prev_output_tokens.device)
|
| 137 |
-
< self.dae_ratio
|
| 138 |
-
)
|
| 139 |
-
corrputed_tokens = _sequential_poisoning(
|
| 140 |
-
tgt_tokens[corrputed],
|
| 141 |
-
len(self.tgt_dict),
|
| 142 |
-
0.33,
|
| 143 |
-
self.bos,
|
| 144 |
-
self.eos,
|
| 145 |
-
self.pad,
|
| 146 |
-
)
|
| 147 |
-
prev_output_tokens[corrputed] = corrputed_tokens
|
| 148 |
-
|
| 149 |
-
# concat everything
|
| 150 |
-
word_ins_out = torch.cat(word_ins_outs, 0)
|
| 151 |
-
word_ins_tgt = torch.cat(word_ins_tgts, 0)
|
| 152 |
-
word_ins_mask = torch.cat(word_ins_masks, 0)
|
| 153 |
-
|
| 154 |
-
return {
|
| 155 |
-
"word_ins": {
|
| 156 |
-
"out": word_ins_out,
|
| 157 |
-
"tgt": word_ins_tgt,
|
| 158 |
-
"mask": word_ins_mask,
|
| 159 |
-
"ls": self.args.label_smoothing,
|
| 160 |
-
"nll_loss": True,
|
| 161 |
-
},
|
| 162 |
-
"length": {
|
| 163 |
-
"out": length_out,
|
| 164 |
-
"tgt": length_tgt,
|
| 165 |
-
"factor": self.decoder.length_loss_factor,
|
| 166 |
-
},
|
| 167 |
-
}
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
@register_model_architecture(
|
| 171 |
-
"iterative_nonautoregressive_transformer", "iterative_nonautoregressive_transformer"
|
| 172 |
-
)
|
| 173 |
-
def inat_base_architecture(args):
|
| 174 |
-
args.encoder_embed_path = getattr(args, "encoder_embed_path", None)
|
| 175 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
|
| 176 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 2048)
|
| 177 |
-
args.encoder_layers = getattr(args, "encoder_layers", 6)
|
| 178 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8)
|
| 179 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
|
| 180 |
-
args.encoder_learned_pos = getattr(args, "encoder_learned_pos", False)
|
| 181 |
-
args.decoder_embed_path = getattr(args, "decoder_embed_path", None)
|
| 182 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", args.encoder_embed_dim)
|
| 183 |
-
args.decoder_ffn_embed_dim = getattr(
|
| 184 |
-
args, "decoder_ffn_embed_dim", args.encoder_ffn_embed_dim
|
| 185 |
-
)
|
| 186 |
-
args.decoder_layers = getattr(args, "decoder_layers", 6)
|
| 187 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 8)
|
| 188 |
-
args.decoder_normalize_before = getattr(args, "decoder_normalize_before", False)
|
| 189 |
-
args.decoder_learned_pos = getattr(args, "decoder_learned_pos", False)
|
| 190 |
-
args.attention_dropout = getattr(args, "attention_dropout", 0.0)
|
| 191 |
-
args.activation_dropout = getattr(args, "activation_dropout", 0.0)
|
| 192 |
-
args.activation_fn = getattr(args, "activation_fn", "relu")
|
| 193 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 194 |
-
args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
|
| 195 |
-
args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
|
| 196 |
-
args.share_decoder_input_output_embed = getattr(
|
| 197 |
-
args, "share_decoder_input_output_embed", False
|
| 198 |
-
)
|
| 199 |
-
args.share_all_embeddings = getattr(args, "share_all_embeddings", False)
|
| 200 |
-
args.no_token_positional_embeddings = getattr(
|
| 201 |
-
args, "no_token_positional_embeddings", False
|
| 202 |
-
)
|
| 203 |
-
args.adaptive_input = getattr(args, "adaptive_input", False)
|
| 204 |
-
args.apply_bert_init = getattr(args, "apply_bert_init", False)
|
| 205 |
-
|
| 206 |
-
args.decoder_output_dim = getattr(
|
| 207 |
-
args, "decoder_output_dim", args.decoder_embed_dim
|
| 208 |
-
)
|
| 209 |
-
args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim)
|
| 210 |
-
|
| 211 |
-
# --- special arguments ---
|
| 212 |
-
args.sg_length_pred = getattr(args, "sg_length_pred", False)
|
| 213 |
-
args.pred_length_offset = getattr(args, "pred_length_offset", False)
|
| 214 |
-
args.length_loss_factor = getattr(args, "length_loss_factor", 0.1)
|
| 215 |
-
args.ngram_predictor = getattr(args, "ngram_predictor", 1)
|
| 216 |
-
args.src_embedding_copy = getattr(args, "src_embedding_copy", False)
|
| 217 |
-
|
| 218 |
-
args.train_step = getattr(args, "train_step", 4)
|
| 219 |
-
args.dae_ratio = getattr(args, "dae_ratio", 0.5)
|
| 220 |
-
args.stochastic_approx = getattr(args, "stochastic_approx", False)
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
@register_model_architecture(
|
| 224 |
-
"iterative_nonautoregressive_transformer",
|
| 225 |
-
"iterative_nonautoregressive_transformer_wmt_en_de",
|
| 226 |
-
)
|
| 227 |
-
def iter_nat_wmt_en_de(args):
|
| 228 |
-
inat_base_architecture(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/levenshtein_transformer.py
DELETED
|
@@ -1,510 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import torch
|
| 7 |
-
import torch.nn as nn
|
| 8 |
-
import torch.nn.functional as F
|
| 9 |
-
from fairseq.iterative_refinement_generator import DecoderOut
|
| 10 |
-
from fairseq.models import register_model, register_model_architecture
|
| 11 |
-
from fairseq.models.nat import FairseqNATDecoder, FairseqNATModel, ensemble_decoder
|
| 12 |
-
from fairseq.models.transformer import Embedding
|
| 13 |
-
from fairseq.modules import TransformerDecoderLayer
|
| 14 |
-
from fairseq.modules.transformer_sentence_encoder import init_bert_params
|
| 15 |
-
|
| 16 |
-
from .levenshtein_utils import (
|
| 17 |
-
_apply_del_words,
|
| 18 |
-
_apply_ins_masks,
|
| 19 |
-
_apply_ins_words,
|
| 20 |
-
_fill,
|
| 21 |
-
_get_del_targets,
|
| 22 |
-
_get_ins_targets,
|
| 23 |
-
_skip,
|
| 24 |
-
_skip_encoder_out,
|
| 25 |
-
)
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
@register_model("levenshtein_transformer")
|
| 29 |
-
class LevenshteinTransformerModel(FairseqNATModel):
|
| 30 |
-
@property
|
| 31 |
-
def allow_length_beam(self):
|
| 32 |
-
return False
|
| 33 |
-
|
| 34 |
-
@staticmethod
|
| 35 |
-
def add_args(parser):
|
| 36 |
-
FairseqNATModel.add_args(parser)
|
| 37 |
-
parser.add_argument(
|
| 38 |
-
"--early-exit",
|
| 39 |
-
default="6,6,6",
|
| 40 |
-
type=str,
|
| 41 |
-
help="number of decoder layers before word_del, mask_ins, word_ins",
|
| 42 |
-
)
|
| 43 |
-
parser.add_argument(
|
| 44 |
-
"--no-share-discriminator",
|
| 45 |
-
action="store_true",
|
| 46 |
-
help="separate parameters for discriminator",
|
| 47 |
-
)
|
| 48 |
-
parser.add_argument(
|
| 49 |
-
"--no-share-maskpredictor",
|
| 50 |
-
action="store_true",
|
| 51 |
-
help="separate parameters for mask-predictor",
|
| 52 |
-
)
|
| 53 |
-
parser.add_argument(
|
| 54 |
-
"--share-discriminator-maskpredictor",
|
| 55 |
-
action="store_true",
|
| 56 |
-
help="share the parameters for both mask-predictor and discriminator",
|
| 57 |
-
)
|
| 58 |
-
parser.add_argument(
|
| 59 |
-
"--sampling-for-deletion",
|
| 60 |
-
action="store_true",
|
| 61 |
-
help="instead of argmax, use sampling to predict the tokens",
|
| 62 |
-
)
|
| 63 |
-
|
| 64 |
-
@classmethod
|
| 65 |
-
def build_decoder(cls, args, tgt_dict, embed_tokens):
|
| 66 |
-
decoder = LevenshteinTransformerDecoder(args, tgt_dict, embed_tokens)
|
| 67 |
-
if getattr(args, "apply_bert_init", False):
|
| 68 |
-
decoder.apply(init_bert_params)
|
| 69 |
-
return decoder
|
| 70 |
-
|
| 71 |
-
def forward(
|
| 72 |
-
self, src_tokens, src_lengths, prev_output_tokens, tgt_tokens, **kwargs
|
| 73 |
-
):
|
| 74 |
-
|
| 75 |
-
assert tgt_tokens is not None, "forward function only supports training."
|
| 76 |
-
|
| 77 |
-
# encoding
|
| 78 |
-
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
|
| 79 |
-
|
| 80 |
-
# generate training labels for insertion
|
| 81 |
-
masked_tgt_masks, masked_tgt_tokens, mask_ins_targets = _get_ins_targets(
|
| 82 |
-
prev_output_tokens, tgt_tokens, self.pad, self.unk
|
| 83 |
-
)
|
| 84 |
-
mask_ins_targets = mask_ins_targets.clamp(min=0, max=255) # for safe prediction
|
| 85 |
-
mask_ins_masks = prev_output_tokens[:, 1:].ne(self.pad)
|
| 86 |
-
|
| 87 |
-
mask_ins_out, _ = self.decoder.forward_mask_ins(
|
| 88 |
-
normalize=False,
|
| 89 |
-
prev_output_tokens=prev_output_tokens,
|
| 90 |
-
encoder_out=encoder_out,
|
| 91 |
-
)
|
| 92 |
-
word_ins_out, _ = self.decoder.forward_word_ins(
|
| 93 |
-
normalize=False,
|
| 94 |
-
prev_output_tokens=masked_tgt_tokens,
|
| 95 |
-
encoder_out=encoder_out,
|
| 96 |
-
)
|
| 97 |
-
|
| 98 |
-
# make online prediction
|
| 99 |
-
if self.decoder.sampling_for_deletion:
|
| 100 |
-
word_predictions = torch.multinomial(
|
| 101 |
-
F.softmax(word_ins_out, -1).view(-1, word_ins_out.size(-1)), 1
|
| 102 |
-
).view(word_ins_out.size(0), -1)
|
| 103 |
-
else:
|
| 104 |
-
word_predictions = F.log_softmax(word_ins_out, dim=-1).max(2)[1]
|
| 105 |
-
|
| 106 |
-
word_predictions.masked_scatter_(
|
| 107 |
-
~masked_tgt_masks, tgt_tokens[~masked_tgt_masks]
|
| 108 |
-
)
|
| 109 |
-
|
| 110 |
-
# generate training labels for deletion
|
| 111 |
-
word_del_targets = _get_del_targets(word_predictions, tgt_tokens, self.pad)
|
| 112 |
-
word_del_out, _ = self.decoder.forward_word_del(
|
| 113 |
-
normalize=False,
|
| 114 |
-
prev_output_tokens=word_predictions,
|
| 115 |
-
encoder_out=encoder_out,
|
| 116 |
-
)
|
| 117 |
-
word_del_masks = word_predictions.ne(self.pad)
|
| 118 |
-
|
| 119 |
-
return {
|
| 120 |
-
"mask_ins": {
|
| 121 |
-
"out": mask_ins_out,
|
| 122 |
-
"tgt": mask_ins_targets,
|
| 123 |
-
"mask": mask_ins_masks,
|
| 124 |
-
"ls": 0.01,
|
| 125 |
-
},
|
| 126 |
-
"word_ins": {
|
| 127 |
-
"out": word_ins_out,
|
| 128 |
-
"tgt": tgt_tokens,
|
| 129 |
-
"mask": masked_tgt_masks,
|
| 130 |
-
"ls": self.args.label_smoothing,
|
| 131 |
-
"nll_loss": True,
|
| 132 |
-
},
|
| 133 |
-
"word_del": {
|
| 134 |
-
"out": word_del_out,
|
| 135 |
-
"tgt": word_del_targets,
|
| 136 |
-
"mask": word_del_masks,
|
| 137 |
-
},
|
| 138 |
-
}
|
| 139 |
-
|
| 140 |
-
def forward_decoder(
|
| 141 |
-
self, decoder_out, encoder_out, eos_penalty=0.0, max_ratio=None, **kwargs
|
| 142 |
-
):
|
| 143 |
-
|
| 144 |
-
output_tokens = decoder_out.output_tokens
|
| 145 |
-
output_scores = decoder_out.output_scores
|
| 146 |
-
attn = decoder_out.attn
|
| 147 |
-
history = decoder_out.history
|
| 148 |
-
|
| 149 |
-
bsz = output_tokens.size(0)
|
| 150 |
-
if max_ratio is None:
|
| 151 |
-
max_lens = torch.zeros_like(output_tokens).fill_(255)
|
| 152 |
-
else:
|
| 153 |
-
if not encoder_out["encoder_padding_mask"]:
|
| 154 |
-
max_src_len = encoder_out["encoder_out"].size(0)
|
| 155 |
-
src_lens = encoder_out["encoder_out"].new(bsz).fill_(max_src_len)
|
| 156 |
-
else:
|
| 157 |
-
src_lens = (~encoder_out["encoder_padding_mask"][0]).sum(1)
|
| 158 |
-
max_lens = (src_lens * max_ratio).clamp(min=10).long()
|
| 159 |
-
|
| 160 |
-
# delete words
|
| 161 |
-
# do not delete tokens if it is <s> </s>
|
| 162 |
-
can_del_word = output_tokens.ne(self.pad).sum(1) > 2
|
| 163 |
-
if can_del_word.sum() != 0: # we cannot delete, skip
|
| 164 |
-
word_del_score, word_del_attn = self.decoder.forward_word_del(
|
| 165 |
-
normalize=True,
|
| 166 |
-
prev_output_tokens=_skip(output_tokens, can_del_word),
|
| 167 |
-
encoder_out=_skip_encoder_out(self.encoder, encoder_out, can_del_word),
|
| 168 |
-
)
|
| 169 |
-
word_del_pred = word_del_score.max(-1)[1].bool()
|
| 170 |
-
|
| 171 |
-
_tokens, _scores, _attn = _apply_del_words(
|
| 172 |
-
output_tokens[can_del_word],
|
| 173 |
-
output_scores[can_del_word],
|
| 174 |
-
word_del_attn,
|
| 175 |
-
word_del_pred,
|
| 176 |
-
self.pad,
|
| 177 |
-
self.bos,
|
| 178 |
-
self.eos,
|
| 179 |
-
)
|
| 180 |
-
output_tokens = _fill(output_tokens, can_del_word, _tokens, self.pad)
|
| 181 |
-
output_scores = _fill(output_scores, can_del_word, _scores, 0)
|
| 182 |
-
attn = _fill(attn, can_del_word, _attn, 0.0)
|
| 183 |
-
|
| 184 |
-
if history is not None:
|
| 185 |
-
history.append(output_tokens.clone())
|
| 186 |
-
|
| 187 |
-
# insert placeholders
|
| 188 |
-
can_ins_mask = output_tokens.ne(self.pad).sum(1) < max_lens
|
| 189 |
-
if can_ins_mask.sum() != 0:
|
| 190 |
-
mask_ins_score, _ = self.decoder.forward_mask_ins(
|
| 191 |
-
normalize=True,
|
| 192 |
-
prev_output_tokens=_skip(output_tokens, can_ins_mask),
|
| 193 |
-
encoder_out=_skip_encoder_out(self.encoder, encoder_out, can_ins_mask),
|
| 194 |
-
)
|
| 195 |
-
if eos_penalty > 0.0:
|
| 196 |
-
mask_ins_score[:, :, 0] = mask_ins_score[:, :, 0] - eos_penalty
|
| 197 |
-
mask_ins_pred = mask_ins_score.max(-1)[1]
|
| 198 |
-
mask_ins_pred = torch.min(
|
| 199 |
-
mask_ins_pred, max_lens[can_ins_mask, None].expand_as(mask_ins_pred)
|
| 200 |
-
)
|
| 201 |
-
|
| 202 |
-
_tokens, _scores = _apply_ins_masks(
|
| 203 |
-
output_tokens[can_ins_mask],
|
| 204 |
-
output_scores[can_ins_mask],
|
| 205 |
-
mask_ins_pred,
|
| 206 |
-
self.pad,
|
| 207 |
-
self.unk,
|
| 208 |
-
self.eos,
|
| 209 |
-
)
|
| 210 |
-
output_tokens = _fill(output_tokens, can_ins_mask, _tokens, self.pad)
|
| 211 |
-
output_scores = _fill(output_scores, can_ins_mask, _scores, 0)
|
| 212 |
-
|
| 213 |
-
if history is not None:
|
| 214 |
-
history.append(output_tokens.clone())
|
| 215 |
-
|
| 216 |
-
# insert words
|
| 217 |
-
can_ins_word = output_tokens.eq(self.unk).sum(1) > 0
|
| 218 |
-
if can_ins_word.sum() != 0:
|
| 219 |
-
word_ins_score, word_ins_attn = self.decoder.forward_word_ins(
|
| 220 |
-
normalize=True,
|
| 221 |
-
prev_output_tokens=_skip(output_tokens, can_ins_word),
|
| 222 |
-
encoder_out=_skip_encoder_out(self.encoder, encoder_out, can_ins_word),
|
| 223 |
-
)
|
| 224 |
-
word_ins_score, word_ins_pred = word_ins_score.max(-1)
|
| 225 |
-
_tokens, _scores = _apply_ins_words(
|
| 226 |
-
output_tokens[can_ins_word],
|
| 227 |
-
output_scores[can_ins_word],
|
| 228 |
-
word_ins_pred,
|
| 229 |
-
word_ins_score,
|
| 230 |
-
self.unk,
|
| 231 |
-
)
|
| 232 |
-
|
| 233 |
-
output_tokens = _fill(output_tokens, can_ins_word, _tokens, self.pad)
|
| 234 |
-
output_scores = _fill(output_scores, can_ins_word, _scores, 0)
|
| 235 |
-
attn = _fill(attn, can_ins_word, word_ins_attn, 0.0)
|
| 236 |
-
|
| 237 |
-
if history is not None:
|
| 238 |
-
history.append(output_tokens.clone())
|
| 239 |
-
|
| 240 |
-
# delete some unnecessary paddings
|
| 241 |
-
cut_off = output_tokens.ne(self.pad).sum(1).max()
|
| 242 |
-
output_tokens = output_tokens[:, :cut_off]
|
| 243 |
-
output_scores = output_scores[:, :cut_off]
|
| 244 |
-
attn = None if attn is None else attn[:, :cut_off, :]
|
| 245 |
-
|
| 246 |
-
return decoder_out._replace(
|
| 247 |
-
output_tokens=output_tokens,
|
| 248 |
-
output_scores=output_scores,
|
| 249 |
-
attn=attn,
|
| 250 |
-
history=history,
|
| 251 |
-
)
|
| 252 |
-
|
| 253 |
-
def initialize_output_tokens(self, encoder_out, src_tokens):
|
| 254 |
-
initial_output_tokens = src_tokens.new_zeros(src_tokens.size(0), 2)
|
| 255 |
-
initial_output_tokens[:, 0] = self.bos
|
| 256 |
-
initial_output_tokens[:, 1] = self.eos
|
| 257 |
-
|
| 258 |
-
initial_output_scores = initial_output_tokens.new_zeros(
|
| 259 |
-
*initial_output_tokens.size()
|
| 260 |
-
).type_as(encoder_out["encoder_out"][0])
|
| 261 |
-
|
| 262 |
-
return DecoderOut(
|
| 263 |
-
output_tokens=initial_output_tokens,
|
| 264 |
-
output_scores=initial_output_scores,
|
| 265 |
-
attn=None,
|
| 266 |
-
step=0,
|
| 267 |
-
max_step=0,
|
| 268 |
-
history=None,
|
| 269 |
-
)
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
class LevenshteinTransformerDecoder(FairseqNATDecoder):
|
| 273 |
-
def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False):
|
| 274 |
-
super().__init__(
|
| 275 |
-
args, dictionary, embed_tokens, no_encoder_attn=no_encoder_attn
|
| 276 |
-
)
|
| 277 |
-
self.dictionary = dictionary
|
| 278 |
-
self.bos = dictionary.bos()
|
| 279 |
-
self.unk = dictionary.unk()
|
| 280 |
-
self.eos = dictionary.eos()
|
| 281 |
-
self.sampling_for_deletion = getattr(args, "sampling_for_deletion", False)
|
| 282 |
-
self.embed_mask_ins = Embedding(256, self.output_embed_dim * 2, None)
|
| 283 |
-
self.embed_word_del = Embedding(2, self.output_embed_dim, None)
|
| 284 |
-
|
| 285 |
-
# del_word, ins_mask, ins_word
|
| 286 |
-
self.early_exit = [int(i) for i in args.early_exit.split(",")]
|
| 287 |
-
assert len(self.early_exit) == 3
|
| 288 |
-
|
| 289 |
-
# copy layers for mask-predict/deletion
|
| 290 |
-
self.layers_msk = None
|
| 291 |
-
if getattr(args, "no_share_maskpredictor", False):
|
| 292 |
-
self.layers_msk = nn.ModuleList(
|
| 293 |
-
[
|
| 294 |
-
TransformerDecoderLayer(args, no_encoder_attn)
|
| 295 |
-
for _ in range(self.early_exit[1])
|
| 296 |
-
]
|
| 297 |
-
)
|
| 298 |
-
self.layers_del = None
|
| 299 |
-
if getattr(args, "no_share_discriminator", False):
|
| 300 |
-
self.layers_del = nn.ModuleList(
|
| 301 |
-
[
|
| 302 |
-
TransformerDecoderLayer(args, no_encoder_attn)
|
| 303 |
-
for _ in range(self.early_exit[0])
|
| 304 |
-
]
|
| 305 |
-
)
|
| 306 |
-
|
| 307 |
-
if getattr(args, "share_discriminator_maskpredictor", False):
|
| 308 |
-
assert getattr(
|
| 309 |
-
args, "no_share_discriminator", False
|
| 310 |
-
), "must set saperate discriminator"
|
| 311 |
-
self.layers_msk = self.layers_del
|
| 312 |
-
|
| 313 |
-
def extract_features(
|
| 314 |
-
self,
|
| 315 |
-
prev_output_tokens,
|
| 316 |
-
encoder_out=None,
|
| 317 |
-
early_exit=None,
|
| 318 |
-
layers=None,
|
| 319 |
-
**unused
|
| 320 |
-
):
|
| 321 |
-
"""
|
| 322 |
-
Similar to *forward* but only return features.
|
| 323 |
-
Inputs:
|
| 324 |
-
prev_output_tokens: Tensor(B, T)
|
| 325 |
-
encoder_out: a dictionary of hidden states and masks
|
| 326 |
-
|
| 327 |
-
Returns:
|
| 328 |
-
tuple:
|
| 329 |
-
- the decoder's features of shape `(batch, tgt_len, embed_dim)`
|
| 330 |
-
- a dictionary with any model-specific outputs
|
| 331 |
-
the LevenshteinTransformer decoder has full-attention to all generated tokens
|
| 332 |
-
"""
|
| 333 |
-
# embed positions
|
| 334 |
-
positions = (
|
| 335 |
-
self.embed_positions(prev_output_tokens)
|
| 336 |
-
if self.embed_positions is not None
|
| 337 |
-
else None
|
| 338 |
-
)
|
| 339 |
-
|
| 340 |
-
# embed tokens and positions
|
| 341 |
-
x = self.embed_scale * self.embed_tokens(prev_output_tokens)
|
| 342 |
-
if self.project_in_dim is not None:
|
| 343 |
-
x = self.project_in_dim(x)
|
| 344 |
-
|
| 345 |
-
if positions is not None:
|
| 346 |
-
x += positions
|
| 347 |
-
x = self.dropout_module(x)
|
| 348 |
-
|
| 349 |
-
# B x T x C -> T x B x C
|
| 350 |
-
x = x.transpose(0, 1)
|
| 351 |
-
attn = None
|
| 352 |
-
inner_states = [x]
|
| 353 |
-
|
| 354 |
-
# decoder layers
|
| 355 |
-
decoder_padding_mask = prev_output_tokens.eq(self.padding_idx)
|
| 356 |
-
layers = self.layers if layers is None else layers
|
| 357 |
-
early_exit = len(layers) if early_exit is None else early_exit
|
| 358 |
-
for _, layer in enumerate(layers[:early_exit]):
|
| 359 |
-
x, attn, _ = layer(
|
| 360 |
-
x,
|
| 361 |
-
encoder_out["encoder_out"][0]
|
| 362 |
-
if (encoder_out is not None and len(encoder_out["encoder_out"]) > 0)
|
| 363 |
-
else None,
|
| 364 |
-
encoder_out["encoder_padding_mask"][0]
|
| 365 |
-
if (
|
| 366 |
-
encoder_out is not None
|
| 367 |
-
and len(encoder_out["encoder_padding_mask"]) > 0
|
| 368 |
-
)
|
| 369 |
-
else None,
|
| 370 |
-
self_attn_mask=None,
|
| 371 |
-
self_attn_padding_mask=decoder_padding_mask,
|
| 372 |
-
)
|
| 373 |
-
inner_states.append(x)
|
| 374 |
-
|
| 375 |
-
if self.layer_norm:
|
| 376 |
-
x = self.layer_norm(x)
|
| 377 |
-
|
| 378 |
-
# T x B x C -> B x T x C
|
| 379 |
-
x = x.transpose(0, 1)
|
| 380 |
-
|
| 381 |
-
if self.project_out_dim is not None:
|
| 382 |
-
x = self.project_out_dim(x)
|
| 383 |
-
|
| 384 |
-
return x, {"attn": attn, "inner_states": inner_states}
|
| 385 |
-
|
| 386 |
-
@ensemble_decoder
|
| 387 |
-
def forward_mask_ins(self, normalize, encoder_out, prev_output_tokens, **unused):
|
| 388 |
-
features, extra = self.extract_features(
|
| 389 |
-
prev_output_tokens,
|
| 390 |
-
encoder_out=encoder_out,
|
| 391 |
-
early_exit=self.early_exit[1],
|
| 392 |
-
layers=self.layers_msk,
|
| 393 |
-
**unused
|
| 394 |
-
)
|
| 395 |
-
features_cat = torch.cat([features[:, :-1, :], features[:, 1:, :]], 2)
|
| 396 |
-
decoder_out = F.linear(features_cat, self.embed_mask_ins.weight)
|
| 397 |
-
if normalize:
|
| 398 |
-
return F.log_softmax(decoder_out, -1), extra["attn"]
|
| 399 |
-
return decoder_out, extra["attn"]
|
| 400 |
-
|
| 401 |
-
@ensemble_decoder
|
| 402 |
-
def forward_word_ins(self, normalize, encoder_out, prev_output_tokens, **unused):
|
| 403 |
-
features, extra = self.extract_features(
|
| 404 |
-
prev_output_tokens,
|
| 405 |
-
encoder_out=encoder_out,
|
| 406 |
-
early_exit=self.early_exit[2],
|
| 407 |
-
layers=self.layers,
|
| 408 |
-
**unused
|
| 409 |
-
)
|
| 410 |
-
decoder_out = self.output_layer(features)
|
| 411 |
-
if normalize:
|
| 412 |
-
return F.log_softmax(decoder_out, -1), extra["attn"]
|
| 413 |
-
return decoder_out, extra["attn"]
|
| 414 |
-
|
| 415 |
-
@ensemble_decoder
|
| 416 |
-
def forward_word_del(self, normalize, encoder_out, prev_output_tokens, **unused):
|
| 417 |
-
features, extra = self.extract_features(
|
| 418 |
-
prev_output_tokens,
|
| 419 |
-
encoder_out=encoder_out,
|
| 420 |
-
early_exit=self.early_exit[0],
|
| 421 |
-
layers=self.layers_del,
|
| 422 |
-
**unused
|
| 423 |
-
)
|
| 424 |
-
decoder_out = F.linear(features, self.embed_word_del.weight)
|
| 425 |
-
if normalize:
|
| 426 |
-
return F.log_softmax(decoder_out, -1), extra["attn"]
|
| 427 |
-
return decoder_out, extra["attn"]
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
@register_model_architecture("levenshtein_transformer", "levenshtein_transformer")
|
| 431 |
-
def levenshtein_base_architecture(args):
|
| 432 |
-
args.encoder_embed_path = getattr(args, "encoder_embed_path", None)
|
| 433 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
|
| 434 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 2048)
|
| 435 |
-
args.encoder_layers = getattr(args, "encoder_layers", 6)
|
| 436 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8)
|
| 437 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
|
| 438 |
-
args.encoder_learned_pos = getattr(args, "encoder_learned_pos", False)
|
| 439 |
-
args.decoder_embed_path = getattr(args, "decoder_embed_path", None)
|
| 440 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", args.encoder_embed_dim)
|
| 441 |
-
args.decoder_ffn_embed_dim = getattr(
|
| 442 |
-
args, "decoder_ffn_embed_dim", args.encoder_ffn_embed_dim
|
| 443 |
-
)
|
| 444 |
-
args.decoder_layers = getattr(args, "decoder_layers", 6)
|
| 445 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 8)
|
| 446 |
-
args.decoder_normalize_before = getattr(args, "decoder_normalize_before", False)
|
| 447 |
-
args.decoder_learned_pos = getattr(args, "decoder_learned_pos", False)
|
| 448 |
-
args.attention_dropout = getattr(args, "attention_dropout", 0.0)
|
| 449 |
-
args.activation_dropout = getattr(args, "activation_dropout", 0.0)
|
| 450 |
-
args.activation_fn = getattr(args, "activation_fn", "relu")
|
| 451 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 452 |
-
args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
|
| 453 |
-
args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
|
| 454 |
-
args.share_decoder_input_output_embed = getattr(
|
| 455 |
-
args, "share_decoder_input_output_embed", False
|
| 456 |
-
)
|
| 457 |
-
args.share_all_embeddings = getattr(args, "share_all_embeddings", False)
|
| 458 |
-
args.no_token_positional_embeddings = getattr(
|
| 459 |
-
args, "no_token_positional_embeddings", False
|
| 460 |
-
)
|
| 461 |
-
args.adaptive_input = getattr(args, "adaptive_input", False)
|
| 462 |
-
args.apply_bert_init = getattr(args, "apply_bert_init", False)
|
| 463 |
-
|
| 464 |
-
args.decoder_output_dim = getattr(
|
| 465 |
-
args, "decoder_output_dim", args.decoder_embed_dim
|
| 466 |
-
)
|
| 467 |
-
args.sampling_for_deletion = getattr(args, "sampling_for_deletion", False)
|
| 468 |
-
args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim)
|
| 469 |
-
args.early_exit = getattr(args, "early_exit", "6,6,6")
|
| 470 |
-
args.no_share_discriminator = getattr(args, "no_share_discriminator", False)
|
| 471 |
-
args.no_share_maskpredictor = getattr(args, "no_share_maskpredictor", False)
|
| 472 |
-
args.share_discriminator_maskpredictor = getattr(
|
| 473 |
-
args, "share_discriminator_maskpredictor", False
|
| 474 |
-
)
|
| 475 |
-
args.no_share_last_layer = getattr(args, "no_share_last_layer", False)
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
@register_model_architecture(
|
| 479 |
-
"levenshtein_transformer", "levenshtein_transformer_wmt_en_de"
|
| 480 |
-
)
|
| 481 |
-
def levenshtein_transformer_wmt_en_de(args):
|
| 482 |
-
levenshtein_base_architecture(args)
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
# similar parameters used in the "Attention Is All You Need" paper (Vaswani et al., 2017)
|
| 486 |
-
@register_model_architecture(
|
| 487 |
-
"levenshtein_transformer", "levenshtein_transformer_vaswani_wmt_en_de_big"
|
| 488 |
-
)
|
| 489 |
-
def levenshtein_transformer_vaswani_wmt_en_de_big(args):
|
| 490 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 1024)
|
| 491 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4096)
|
| 492 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 16)
|
| 493 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
|
| 494 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 1024)
|
| 495 |
-
args.decoder_ffn_embed_dim = getattr(args, "decoder_ffn_embed_dim", 4096)
|
| 496 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 16)
|
| 497 |
-
args.dropout = getattr(args, "dropout", 0.3)
|
| 498 |
-
levenshtein_base_architecture(args)
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
# default parameters used in tensor2tensor implementation
|
| 502 |
-
@register_model_architecture(
|
| 503 |
-
"levenshtein_transformer", "levenshtein_transformer_wmt_en_de_big"
|
| 504 |
-
)
|
| 505 |
-
def levenshtein_transformer_wmt_en_de_big_t2t(args):
|
| 506 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", True)
|
| 507 |
-
args.decoder_normalize_before = getattr(args, "decoder_normalize_before", True)
|
| 508 |
-
args.attention_dropout = getattr(args, "attention_dropout", 0.1)
|
| 509 |
-
args.activation_dropout = getattr(args, "activation_dropout", 0.1)
|
| 510 |
-
levenshtein_transformer_vaswani_wmt_en_de_big(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/levenshtein_utils.py
DELETED
|
@@ -1,292 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import torch
|
| 7 |
-
from fairseq.utils import new_arange
|
| 8 |
-
|
| 9 |
-
# -------------- Helper Functions --------------------------------------------------- #
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
def load_libnat():
|
| 13 |
-
try:
|
| 14 |
-
from fairseq import libnat_cuda
|
| 15 |
-
|
| 16 |
-
return libnat_cuda, True
|
| 17 |
-
|
| 18 |
-
except ImportError as e:
|
| 19 |
-
print(str(e) + "... fall back to CPU version")
|
| 20 |
-
|
| 21 |
-
try:
|
| 22 |
-
from fairseq import libnat
|
| 23 |
-
|
| 24 |
-
return libnat, False
|
| 25 |
-
|
| 26 |
-
except ImportError as e:
|
| 27 |
-
import sys
|
| 28 |
-
|
| 29 |
-
sys.stderr.write(
|
| 30 |
-
"ERROR: missing libnat_cuda. run `python setup.py build_ext --inplace`\n"
|
| 31 |
-
)
|
| 32 |
-
raise e
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
def _get_ins_targets(in_tokens, out_tokens, padding_idx, unk_idx):
|
| 36 |
-
libnat, use_cuda = load_libnat()
|
| 37 |
-
|
| 38 |
-
def _get_ins_targets_cuda(in_tokens, out_tokens, padding_idx, unk_idx):
|
| 39 |
-
in_masks = in_tokens.ne(padding_idx)
|
| 40 |
-
out_masks = out_tokens.ne(padding_idx)
|
| 41 |
-
mask_ins_targets, masked_tgt_masks = libnat.generate_insertion_labels(
|
| 42 |
-
out_tokens.int(),
|
| 43 |
-
libnat.levenshtein_distance(
|
| 44 |
-
in_tokens.int(),
|
| 45 |
-
out_tokens.int(),
|
| 46 |
-
in_masks.sum(1).int(),
|
| 47 |
-
out_masks.sum(1).int(),
|
| 48 |
-
),
|
| 49 |
-
)
|
| 50 |
-
masked_tgt_masks = masked_tgt_masks.bool() & out_masks
|
| 51 |
-
mask_ins_targets = mask_ins_targets.type_as(in_tokens)[
|
| 52 |
-
:, 1 : in_masks.size(1)
|
| 53 |
-
].masked_fill_(~in_masks[:, 1:], 0)
|
| 54 |
-
masked_tgt_tokens = out_tokens.masked_fill(masked_tgt_masks, unk_idx)
|
| 55 |
-
return masked_tgt_masks, masked_tgt_tokens, mask_ins_targets
|
| 56 |
-
|
| 57 |
-
def _get_ins_targets_cpu(in_tokens, out_tokens, padding_idx, unk_idx):
|
| 58 |
-
in_seq_len, out_seq_len = in_tokens.size(1), out_tokens.size(1)
|
| 59 |
-
|
| 60 |
-
in_tokens_list = [
|
| 61 |
-
[t for t in s if t != padding_idx] for i, s in enumerate(in_tokens.tolist())
|
| 62 |
-
]
|
| 63 |
-
out_tokens_list = [
|
| 64 |
-
[t for t in s if t != padding_idx]
|
| 65 |
-
for i, s in enumerate(out_tokens.tolist())
|
| 66 |
-
]
|
| 67 |
-
|
| 68 |
-
full_labels = libnat.suggested_ed2_path(
|
| 69 |
-
in_tokens_list, out_tokens_list, padding_idx
|
| 70 |
-
)
|
| 71 |
-
mask_inputs = [
|
| 72 |
-
[len(c) if c[0] != padding_idx else 0 for c in a[:-1]] for a in full_labels
|
| 73 |
-
]
|
| 74 |
-
|
| 75 |
-
# generate labels
|
| 76 |
-
masked_tgt_masks = []
|
| 77 |
-
for mask_input in mask_inputs:
|
| 78 |
-
mask_label = []
|
| 79 |
-
for beam_size in mask_input[1:-1]: # HACK 1:-1
|
| 80 |
-
mask_label += [0] + [1 for _ in range(beam_size)]
|
| 81 |
-
masked_tgt_masks.append(
|
| 82 |
-
mask_label + [0 for _ in range(out_seq_len - len(mask_label))]
|
| 83 |
-
)
|
| 84 |
-
mask_ins_targets = [
|
| 85 |
-
mask_input[1:-1]
|
| 86 |
-
+ [0 for _ in range(in_seq_len - 1 - len(mask_input[1:-1]))]
|
| 87 |
-
for mask_input in mask_inputs
|
| 88 |
-
]
|
| 89 |
-
|
| 90 |
-
# transform to tensor
|
| 91 |
-
masked_tgt_masks = torch.tensor(
|
| 92 |
-
masked_tgt_masks, device=out_tokens.device
|
| 93 |
-
).bool()
|
| 94 |
-
mask_ins_targets = torch.tensor(mask_ins_targets, device=in_tokens.device)
|
| 95 |
-
masked_tgt_tokens = out_tokens.masked_fill(masked_tgt_masks, unk_idx)
|
| 96 |
-
return masked_tgt_masks, masked_tgt_tokens, mask_ins_targets
|
| 97 |
-
|
| 98 |
-
if use_cuda:
|
| 99 |
-
return _get_ins_targets_cuda(in_tokens, out_tokens, padding_idx, unk_idx)
|
| 100 |
-
return _get_ins_targets_cpu(in_tokens, out_tokens, padding_idx, unk_idx)
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
def _get_del_targets(in_tokens, out_tokens, padding_idx):
|
| 104 |
-
libnat, use_cuda = load_libnat()
|
| 105 |
-
|
| 106 |
-
def _get_del_targets_cuda(in_tokens, out_tokens, padding_idx):
|
| 107 |
-
in_masks = in_tokens.ne(padding_idx)
|
| 108 |
-
out_masks = out_tokens.ne(padding_idx)
|
| 109 |
-
|
| 110 |
-
word_del_targets = libnat.generate_deletion_labels(
|
| 111 |
-
in_tokens.int(),
|
| 112 |
-
libnat.levenshtein_distance(
|
| 113 |
-
in_tokens.int(),
|
| 114 |
-
out_tokens.int(),
|
| 115 |
-
in_masks.sum(1).int(),
|
| 116 |
-
out_masks.sum(1).int(),
|
| 117 |
-
),
|
| 118 |
-
)
|
| 119 |
-
word_del_targets = word_del_targets.type_as(in_tokens).masked_fill_(
|
| 120 |
-
~in_masks, 0
|
| 121 |
-
)
|
| 122 |
-
return word_del_targets
|
| 123 |
-
|
| 124 |
-
def _get_del_targets_cpu(in_tokens, out_tokens, padding_idx):
|
| 125 |
-
out_seq_len = out_tokens.size(1)
|
| 126 |
-
with torch.cuda.device_of(in_tokens):
|
| 127 |
-
in_tokens_list = [
|
| 128 |
-
[t for t in s if t != padding_idx]
|
| 129 |
-
for i, s in enumerate(in_tokens.tolist())
|
| 130 |
-
]
|
| 131 |
-
out_tokens_list = [
|
| 132 |
-
[t for t in s if t != padding_idx]
|
| 133 |
-
for i, s in enumerate(out_tokens.tolist())
|
| 134 |
-
]
|
| 135 |
-
|
| 136 |
-
full_labels = libnat.suggested_ed2_path(
|
| 137 |
-
in_tokens_list, out_tokens_list, padding_idx
|
| 138 |
-
)
|
| 139 |
-
word_del_targets = [b[-1] for b in full_labels]
|
| 140 |
-
word_del_targets = [
|
| 141 |
-
labels + [0 for _ in range(out_seq_len - len(labels))]
|
| 142 |
-
for labels in word_del_targets
|
| 143 |
-
]
|
| 144 |
-
|
| 145 |
-
# transform to tensor
|
| 146 |
-
word_del_targets = torch.tensor(word_del_targets, device=out_tokens.device)
|
| 147 |
-
return word_del_targets
|
| 148 |
-
|
| 149 |
-
if use_cuda:
|
| 150 |
-
return _get_del_targets_cuda(in_tokens, out_tokens, padding_idx)
|
| 151 |
-
return _get_del_targets_cpu(in_tokens, out_tokens, padding_idx)
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
def _apply_ins_masks(
|
| 155 |
-
in_tokens, in_scores, mask_ins_pred, padding_idx, unk_idx, eos_idx
|
| 156 |
-
):
|
| 157 |
-
|
| 158 |
-
in_masks = in_tokens.ne(padding_idx)
|
| 159 |
-
in_lengths = in_masks.sum(1)
|
| 160 |
-
|
| 161 |
-
# HACK: hacky way to shift all the paddings to eos first.
|
| 162 |
-
in_tokens.masked_fill_(~in_masks, eos_idx)
|
| 163 |
-
mask_ins_pred.masked_fill_(~in_masks[:, 1:], 0)
|
| 164 |
-
|
| 165 |
-
out_lengths = in_lengths + mask_ins_pred.sum(1)
|
| 166 |
-
out_max_len = out_lengths.max()
|
| 167 |
-
out_masks = new_arange(out_lengths, out_max_len)[None, :] < out_lengths[:, None]
|
| 168 |
-
|
| 169 |
-
reordering = (mask_ins_pred + in_masks[:, 1:].long()).cumsum(1)
|
| 170 |
-
out_tokens = (
|
| 171 |
-
in_tokens.new_zeros(in_tokens.size(0), out_max_len)
|
| 172 |
-
.fill_(padding_idx)
|
| 173 |
-
.masked_fill_(out_masks, unk_idx)
|
| 174 |
-
)
|
| 175 |
-
out_tokens[:, 0] = in_tokens[:, 0]
|
| 176 |
-
out_tokens.scatter_(1, reordering, in_tokens[:, 1:])
|
| 177 |
-
|
| 178 |
-
out_scores = None
|
| 179 |
-
if in_scores is not None:
|
| 180 |
-
in_scores.masked_fill_(~in_masks, 0)
|
| 181 |
-
out_scores = in_scores.new_zeros(*out_tokens.size())
|
| 182 |
-
out_scores[:, 0] = in_scores[:, 0]
|
| 183 |
-
out_scores.scatter_(1, reordering, in_scores[:, 1:])
|
| 184 |
-
|
| 185 |
-
return out_tokens, out_scores
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
def _apply_ins_words(in_tokens, in_scores, word_ins_pred, word_ins_scores, unk_idx):
|
| 189 |
-
word_ins_masks = in_tokens.eq(unk_idx)
|
| 190 |
-
out_tokens = in_tokens.masked_scatter(word_ins_masks, word_ins_pred[word_ins_masks])
|
| 191 |
-
|
| 192 |
-
if in_scores is not None:
|
| 193 |
-
out_scores = in_scores.masked_scatter(
|
| 194 |
-
word_ins_masks, word_ins_scores[word_ins_masks]
|
| 195 |
-
)
|
| 196 |
-
else:
|
| 197 |
-
out_scores = None
|
| 198 |
-
|
| 199 |
-
return out_tokens, out_scores
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
def _apply_del_words(
|
| 203 |
-
in_tokens, in_scores, in_attn, word_del_pred, padding_idx, bos_idx, eos_idx
|
| 204 |
-
):
|
| 205 |
-
# apply deletion to a tensor
|
| 206 |
-
in_masks = in_tokens.ne(padding_idx)
|
| 207 |
-
bos_eos_masks = in_tokens.eq(bos_idx) | in_tokens.eq(eos_idx)
|
| 208 |
-
|
| 209 |
-
max_len = in_tokens.size(1)
|
| 210 |
-
word_del_pred.masked_fill_(~in_masks, 1)
|
| 211 |
-
word_del_pred.masked_fill_(bos_eos_masks, 0)
|
| 212 |
-
|
| 213 |
-
reordering = new_arange(in_tokens).masked_fill_(word_del_pred, max_len).sort(1)[1]
|
| 214 |
-
|
| 215 |
-
out_tokens = in_tokens.masked_fill(word_del_pred, padding_idx).gather(1, reordering)
|
| 216 |
-
|
| 217 |
-
out_scores = None
|
| 218 |
-
if in_scores is not None:
|
| 219 |
-
out_scores = in_scores.masked_fill(word_del_pred, 0).gather(1, reordering)
|
| 220 |
-
|
| 221 |
-
out_attn = None
|
| 222 |
-
if in_attn is not None:
|
| 223 |
-
_mask = word_del_pred[:, :, None].expand_as(in_attn)
|
| 224 |
-
_reordering = reordering[:, :, None].expand_as(in_attn)
|
| 225 |
-
out_attn = in_attn.masked_fill(_mask, 0.0).gather(1, _reordering)
|
| 226 |
-
|
| 227 |
-
return out_tokens, out_scores, out_attn
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
def _skip(x, mask):
|
| 231 |
-
"""
|
| 232 |
-
Getting sliced (dim=0) tensor by mask. Supporting tensor and list/dict of tensors.
|
| 233 |
-
"""
|
| 234 |
-
if isinstance(x, int):
|
| 235 |
-
return x
|
| 236 |
-
|
| 237 |
-
if x is None:
|
| 238 |
-
return None
|
| 239 |
-
|
| 240 |
-
if isinstance(x, torch.Tensor):
|
| 241 |
-
if x.size(0) == mask.size(0):
|
| 242 |
-
return x[mask]
|
| 243 |
-
elif x.size(1) == mask.size(0):
|
| 244 |
-
return x[:, mask]
|
| 245 |
-
|
| 246 |
-
if isinstance(x, list):
|
| 247 |
-
return [_skip(x_i, mask) for x_i in x]
|
| 248 |
-
|
| 249 |
-
if isinstance(x, dict):
|
| 250 |
-
return {k: _skip(v, mask) for k, v in x.items()}
|
| 251 |
-
|
| 252 |
-
raise NotImplementedError
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
def _skip_encoder_out(encoder, encoder_out, mask):
|
| 256 |
-
if not mask.any():
|
| 257 |
-
return encoder_out
|
| 258 |
-
else:
|
| 259 |
-
return encoder.reorder_encoder_out(
|
| 260 |
-
encoder_out, mask.nonzero(as_tuple=False).squeeze()
|
| 261 |
-
)
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
def _fill(x, mask, y, padding_idx):
|
| 265 |
-
"""
|
| 266 |
-
Filling tensor x with y at masked positions (dim=0).
|
| 267 |
-
"""
|
| 268 |
-
if x is None:
|
| 269 |
-
return y
|
| 270 |
-
assert x.dim() == y.dim() and mask.size(0) == x.size(0)
|
| 271 |
-
assert x.dim() == 2 or (x.dim() == 3 and x.size(2) == y.size(2))
|
| 272 |
-
n_selected = mask.sum()
|
| 273 |
-
assert n_selected == y.size(0)
|
| 274 |
-
|
| 275 |
-
if n_selected == x.size(0):
|
| 276 |
-
return y
|
| 277 |
-
|
| 278 |
-
if x.size(1) < y.size(1):
|
| 279 |
-
dims = [x.size(0), y.size(1) - x.size(1)]
|
| 280 |
-
if x.dim() == 3:
|
| 281 |
-
dims.append(x.size(2))
|
| 282 |
-
x = torch.cat([x, x.new_zeros(*dims).fill_(padding_idx)], 1)
|
| 283 |
-
x[mask] = y
|
| 284 |
-
elif x.size(1) > y.size(1):
|
| 285 |
-
x[mask] = padding_idx
|
| 286 |
-
if x.dim() == 2:
|
| 287 |
-
x[mask, : y.size(1)] = y
|
| 288 |
-
else:
|
| 289 |
-
x[mask, : y.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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/nat_crf_transformer.py
DELETED
|
@@ -1,121 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
from fairseq.models import register_model, register_model_architecture
|
| 8 |
-
from fairseq.models.nat import NATransformerModel, base_architecture
|
| 9 |
-
from fairseq.modules import DynamicCRF
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
@register_model("nacrf_transformer")
|
| 13 |
-
class NACRFTransformerModel(NATransformerModel):
|
| 14 |
-
def __init__(self, args, encoder, decoder):
|
| 15 |
-
super().__init__(args, encoder, decoder)
|
| 16 |
-
self.crf_layer = DynamicCRF(
|
| 17 |
-
num_embedding=len(self.tgt_dict),
|
| 18 |
-
low_rank=args.crf_lowrank_approx,
|
| 19 |
-
beam_size=args.crf_beam_approx,
|
| 20 |
-
)
|
| 21 |
-
|
| 22 |
-
@property
|
| 23 |
-
def allow_ensemble(self):
|
| 24 |
-
return False
|
| 25 |
-
|
| 26 |
-
@staticmethod
|
| 27 |
-
def add_args(parser):
|
| 28 |
-
NATransformerModel.add_args(parser)
|
| 29 |
-
parser.add_argument(
|
| 30 |
-
"--crf-lowrank-approx",
|
| 31 |
-
type=int,
|
| 32 |
-
help="the dimension of low-rank approximation of transition",
|
| 33 |
-
)
|
| 34 |
-
parser.add_argument(
|
| 35 |
-
"--crf-beam-approx",
|
| 36 |
-
type=int,
|
| 37 |
-
help="the beam size for apporixmating the normalizing factor",
|
| 38 |
-
)
|
| 39 |
-
parser.add_argument(
|
| 40 |
-
"--word-ins-loss-factor",
|
| 41 |
-
type=float,
|
| 42 |
-
help="weights on NAT loss used to co-training with CRF loss.",
|
| 43 |
-
)
|
| 44 |
-
|
| 45 |
-
def forward(
|
| 46 |
-
self, src_tokens, src_lengths, prev_output_tokens, tgt_tokens, **kwargs
|
| 47 |
-
):
|
| 48 |
-
# encoding
|
| 49 |
-
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
|
| 50 |
-
|
| 51 |
-
# length prediction
|
| 52 |
-
length_out = self.decoder.forward_length(
|
| 53 |
-
normalize=False, encoder_out=encoder_out
|
| 54 |
-
)
|
| 55 |
-
length_tgt = self.decoder.forward_length_prediction(
|
| 56 |
-
length_out, encoder_out, tgt_tokens
|
| 57 |
-
)
|
| 58 |
-
|
| 59 |
-
# decoding
|
| 60 |
-
word_ins_out = self.decoder(
|
| 61 |
-
normalize=False,
|
| 62 |
-
prev_output_tokens=prev_output_tokens,
|
| 63 |
-
encoder_out=encoder_out,
|
| 64 |
-
)
|
| 65 |
-
word_ins_tgt, word_ins_mask = tgt_tokens, tgt_tokens.ne(self.pad)
|
| 66 |
-
|
| 67 |
-
# compute the log-likelihood of CRF
|
| 68 |
-
crf_nll = -self.crf_layer(word_ins_out, word_ins_tgt, word_ins_mask)
|
| 69 |
-
crf_nll = (crf_nll / word_ins_mask.type_as(crf_nll).sum(-1)).mean()
|
| 70 |
-
|
| 71 |
-
return {
|
| 72 |
-
"word_ins": {
|
| 73 |
-
"out": word_ins_out,
|
| 74 |
-
"tgt": word_ins_tgt,
|
| 75 |
-
"mask": word_ins_mask,
|
| 76 |
-
"ls": self.args.label_smoothing,
|
| 77 |
-
"nll_loss": True,
|
| 78 |
-
"factor": self.args.word_ins_loss_factor,
|
| 79 |
-
},
|
| 80 |
-
"word_crf": {"loss": crf_nll},
|
| 81 |
-
"length": {
|
| 82 |
-
"out": length_out,
|
| 83 |
-
"tgt": length_tgt,
|
| 84 |
-
"factor": self.decoder.length_loss_factor,
|
| 85 |
-
},
|
| 86 |
-
}
|
| 87 |
-
|
| 88 |
-
def forward_decoder(self, decoder_out, encoder_out, decoding_format=None, **kwargs):
|
| 89 |
-
output_tokens = decoder_out.output_tokens
|
| 90 |
-
output_scores = decoder_out.output_scores
|
| 91 |
-
history = decoder_out.history
|
| 92 |
-
|
| 93 |
-
# execute the decoder and get emission scores
|
| 94 |
-
output_masks = output_tokens.ne(self.pad)
|
| 95 |
-
word_ins_out = self.decoder(
|
| 96 |
-
normalize=False, prev_output_tokens=output_tokens, encoder_out=encoder_out
|
| 97 |
-
)
|
| 98 |
-
|
| 99 |
-
# run viterbi decoding through CRF
|
| 100 |
-
_scores, _tokens = self.crf_layer.forward_decoder(word_ins_out, output_masks)
|
| 101 |
-
output_tokens.masked_scatter_(output_masks, _tokens[output_masks])
|
| 102 |
-
output_scores.masked_scatter_(output_masks, _scores[output_masks])
|
| 103 |
-
if history is not None:
|
| 104 |
-
history.append(output_tokens.clone())
|
| 105 |
-
|
| 106 |
-
return decoder_out._replace(
|
| 107 |
-
output_tokens=output_tokens,
|
| 108 |
-
output_scores=output_scores,
|
| 109 |
-
attn=None,
|
| 110 |
-
history=history,
|
| 111 |
-
)
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
@register_model_architecture("nacrf_transformer", "nacrf_transformer")
|
| 115 |
-
def nacrf_base_architecture(args):
|
| 116 |
-
args.crf_lowrank_approx = getattr(args, "crf_lowrank_approx", 32)
|
| 117 |
-
args.crf_beam_approx = getattr(args, "crf_beam_approx", 64)
|
| 118 |
-
args.word_ins_loss_factor = getattr(args, "word_ins_loss_factor", 0.5)
|
| 119 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", True)
|
| 120 |
-
args.decoder_normalize_before = getattr(args, "decoder_normalize_before", True)
|
| 121 |
-
base_architecture(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/nonautoregressive_ensembles.py
DELETED
|
@@ -1,254 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import math
|
| 7 |
-
|
| 8 |
-
import torch
|
| 9 |
-
import torch.nn.functional as F
|
| 10 |
-
from fairseq.models.nat import (
|
| 11 |
-
_apply_del_words,
|
| 12 |
-
_apply_ins_masks,
|
| 13 |
-
_apply_ins_words,
|
| 14 |
-
_fill,
|
| 15 |
-
_skip,
|
| 16 |
-
_skip_encoder_out,
|
| 17 |
-
)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
class _EnsembleModelEncoder(object):
|
| 21 |
-
def __init__(self, models):
|
| 22 |
-
self.models = models
|
| 23 |
-
|
| 24 |
-
def reorder_encoder_out(self, encoder_outs, new_order):
|
| 25 |
-
encoder_outs = [
|
| 26 |
-
model.encoder.reorder_encoder_out(encoder_out, new_order)
|
| 27 |
-
for model, encoder_out in zip(self.models, encoder_outs)
|
| 28 |
-
]
|
| 29 |
-
return encoder_outs
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
class BasicEnsembleModel(torch.nn.Module):
|
| 33 |
-
"""A wrapper around an ensemble of models."""
|
| 34 |
-
|
| 35 |
-
def __init__(self, models):
|
| 36 |
-
super().__init__()
|
| 37 |
-
self.models = torch.nn.ModuleList(models)
|
| 38 |
-
self.bos = self.models[0].decoder.dictionary.bos()
|
| 39 |
-
self.eos = self.models[0].decoder.dictionary.eos()
|
| 40 |
-
self.pad = self.models[0].decoder.dictionary.pad()
|
| 41 |
-
self.unk = self.models[0].decoder.dictionary.unk()
|
| 42 |
-
self.encoder = _EnsembleModelEncoder(self.models)
|
| 43 |
-
|
| 44 |
-
def has_encoder(self):
|
| 45 |
-
return hasattr(self.models[0], "encoder")
|
| 46 |
-
|
| 47 |
-
def max_decoder_positions(self):
|
| 48 |
-
return min(m.max_decoder_positions() for m in self.models)
|
| 49 |
-
|
| 50 |
-
@torch.no_grad()
|
| 51 |
-
def forward_encoder(self, encoder_input):
|
| 52 |
-
if not self.has_encoder():
|
| 53 |
-
return None
|
| 54 |
-
return [model.forward_encoder(encoder_input) for model in self.models]
|
| 55 |
-
|
| 56 |
-
@torch.no_grad()
|
| 57 |
-
def forward_decoder(self, *inputs):
|
| 58 |
-
raise NotImplementedError
|
| 59 |
-
|
| 60 |
-
def initialize_output_tokens(self, *inputs):
|
| 61 |
-
raise NotImplementedError
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
class EnsembleLevT(BasicEnsembleModel):
|
| 65 |
-
"""A wrapper around an ensemble of models."""
|
| 66 |
-
|
| 67 |
-
def __init__(self, models):
|
| 68 |
-
super().__init__(models)
|
| 69 |
-
|
| 70 |
-
@torch.no_grad()
|
| 71 |
-
def forward_decoder(
|
| 72 |
-
self, decoder_out, encoder_outs, eos_penalty=0.0, max_ratio=None, **kwargs
|
| 73 |
-
):
|
| 74 |
-
# LevT ensembling
|
| 75 |
-
# A pipeline of three steps: deletion, placeholder, and word insertion.
|
| 76 |
-
# We need to average scores in each step in a pipeline way because of dependence.
|
| 77 |
-
# deletion
|
| 78 |
-
output_tokens = decoder_out.output_tokens
|
| 79 |
-
output_scores = decoder_out.output_scores
|
| 80 |
-
attn = decoder_out.attn
|
| 81 |
-
|
| 82 |
-
bsz = output_tokens.size(0)
|
| 83 |
-
if max_ratio is None:
|
| 84 |
-
max_lens = output_tokens.new().fill_(255)
|
| 85 |
-
else:
|
| 86 |
-
if not encoder_outs[0]["encoder_padding_mask"]:
|
| 87 |
-
src_lens = (
|
| 88 |
-
encoder_outs[0]["encoder_out"][0]
|
| 89 |
-
.new(bsz)
|
| 90 |
-
.fill_(encoder_outs[0]["encoder_out"][0].size(1))
|
| 91 |
-
)
|
| 92 |
-
else:
|
| 93 |
-
src_lens = (~encoder_outs[0]["encoder_padding_mask"][0]).sum(1)
|
| 94 |
-
max_lens = (src_lens * max_ratio).clamp(min=10).long()
|
| 95 |
-
|
| 96 |
-
# delete words
|
| 97 |
-
# do not delete tokens if it is <s> </s>
|
| 98 |
-
can_del_word = output_tokens.ne(self.pad).sum(1) > 2
|
| 99 |
-
if can_del_word.sum() != 0: # we cannot delete, skip
|
| 100 |
-
output_tokens, output_scores, attn = self.forward_word_del(
|
| 101 |
-
encoder_outs,
|
| 102 |
-
output_tokens,
|
| 103 |
-
output_scores,
|
| 104 |
-
attn,
|
| 105 |
-
can_del_word,
|
| 106 |
-
)
|
| 107 |
-
|
| 108 |
-
# insert placeholders
|
| 109 |
-
can_ins_mask = output_tokens.ne(self.pad).sum(1) < max_lens
|
| 110 |
-
if can_ins_mask.sum() != 0:
|
| 111 |
-
output_tokens, output_scores = self.forward_mask_ins(
|
| 112 |
-
encoder_outs,
|
| 113 |
-
output_tokens,
|
| 114 |
-
output_scores,
|
| 115 |
-
can_ins_mask,
|
| 116 |
-
eos_penalty,
|
| 117 |
-
max_lens,
|
| 118 |
-
)
|
| 119 |
-
|
| 120 |
-
# insert words
|
| 121 |
-
can_ins_word = output_tokens.eq(self.unk).sum(1) > 0
|
| 122 |
-
if can_ins_word.sum() != 0:
|
| 123 |
-
output_tokens, output_scores, attn = self.forward_word_ins(
|
| 124 |
-
encoder_outs,
|
| 125 |
-
output_tokens,
|
| 126 |
-
output_scores,
|
| 127 |
-
attn,
|
| 128 |
-
can_ins_word,
|
| 129 |
-
)
|
| 130 |
-
|
| 131 |
-
# delete some unnecessary paddings
|
| 132 |
-
cut_off = output_tokens.ne(self.pad).sum(1).max()
|
| 133 |
-
output_tokens = output_tokens[:, :cut_off]
|
| 134 |
-
output_scores = output_scores[:, :cut_off]
|
| 135 |
-
attn = None if attn is None else attn[:, :cut_off, :]
|
| 136 |
-
return decoder_out._replace(
|
| 137 |
-
output_tokens=output_tokens,
|
| 138 |
-
output_scores=output_scores,
|
| 139 |
-
attn=attn,
|
| 140 |
-
history=None,
|
| 141 |
-
)
|
| 142 |
-
|
| 143 |
-
def forward_word_del(
|
| 144 |
-
self, encoder_outs, output_tokens, output_scores, attn, can_del_word
|
| 145 |
-
):
|
| 146 |
-
word_del_score_avg = []
|
| 147 |
-
word_del_attn_avg = []
|
| 148 |
-
for model, encoder_out in zip(self.models, encoder_outs):
|
| 149 |
-
word_del_out, word_del_attn = model.decoder.forward_word_del(
|
| 150 |
-
_skip(output_tokens, can_del_word),
|
| 151 |
-
_skip_encoder_out(model.encoder, encoder_out, can_del_word),
|
| 152 |
-
)
|
| 153 |
-
word_del_score = F.log_softmax(word_del_out, 2)
|
| 154 |
-
word_del_score_avg.append(word_del_score)
|
| 155 |
-
word_del_attn_avg.append(word_del_attn)
|
| 156 |
-
word_del_score_avg = torch.logsumexp(
|
| 157 |
-
torch.stack(word_del_score_avg, dim=0), dim=0
|
| 158 |
-
) - math.log(len(self.models))
|
| 159 |
-
word_del_pred = word_del_score_avg.max(-1)[1].bool()
|
| 160 |
-
if word_del_attn_avg[0] is not None:
|
| 161 |
-
word_del_attn_avg = torch.stack(word_del_attn_avg, dim=0) / len(self.models)
|
| 162 |
-
else:
|
| 163 |
-
word_del_attn_avg = None
|
| 164 |
-
|
| 165 |
-
_tokens, _scores, _attn = _apply_del_words(
|
| 166 |
-
output_tokens[can_del_word],
|
| 167 |
-
output_scores[can_del_word],
|
| 168 |
-
word_del_attn_avg,
|
| 169 |
-
word_del_pred,
|
| 170 |
-
self.pad,
|
| 171 |
-
self.bos,
|
| 172 |
-
self.eos,
|
| 173 |
-
)
|
| 174 |
-
output_tokens = _fill(output_tokens, can_del_word, _tokens, self.pad)
|
| 175 |
-
output_scores = _fill(output_scores, can_del_word, _scores, 0)
|
| 176 |
-
attn = _fill(attn, can_del_word, _attn, 0.0)
|
| 177 |
-
return output_tokens, output_scores, attn
|
| 178 |
-
|
| 179 |
-
def forward_mask_ins(
|
| 180 |
-
self,
|
| 181 |
-
encoder_outs,
|
| 182 |
-
output_tokens,
|
| 183 |
-
output_scores,
|
| 184 |
-
can_ins_mask,
|
| 185 |
-
eos_penalty,
|
| 186 |
-
max_lens,
|
| 187 |
-
):
|
| 188 |
-
mask_ins_score_avg = []
|
| 189 |
-
for model, encoder_out in zip(self.models, encoder_outs):
|
| 190 |
-
mask_ins_out, _ = model.decoder.forward_mask_ins(
|
| 191 |
-
_skip(output_tokens, can_ins_mask),
|
| 192 |
-
_skip_encoder_out(model.encoder, encoder_out, can_ins_mask),
|
| 193 |
-
)
|
| 194 |
-
mask_ins_score = F.log_softmax(mask_ins_out, 2)
|
| 195 |
-
if eos_penalty > 0.0:
|
| 196 |
-
mask_ins_score[:, :, 0] -= eos_penalty
|
| 197 |
-
mask_ins_score_avg.append(mask_ins_score)
|
| 198 |
-
mask_ins_score_avg = torch.logsumexp(
|
| 199 |
-
torch.stack(mask_ins_score_avg, dim=0), dim=0
|
| 200 |
-
) - math.log(len(self.models))
|
| 201 |
-
mask_ins_pred = mask_ins_score_avg.max(-1)[1]
|
| 202 |
-
mask_ins_pred = torch.min(
|
| 203 |
-
mask_ins_pred, max_lens[can_ins_mask, None].expand_as(mask_ins_pred)
|
| 204 |
-
)
|
| 205 |
-
_tokens, _scores = _apply_ins_masks(
|
| 206 |
-
output_tokens[can_ins_mask],
|
| 207 |
-
output_scores[can_ins_mask],
|
| 208 |
-
mask_ins_pred,
|
| 209 |
-
self.pad,
|
| 210 |
-
self.unk,
|
| 211 |
-
self.eos,
|
| 212 |
-
)
|
| 213 |
-
output_tokens = _fill(output_tokens, can_ins_mask, _tokens, self.pad)
|
| 214 |
-
output_scores = _fill(output_scores, can_ins_mask, _scores, 0)
|
| 215 |
-
return output_tokens, output_scores
|
| 216 |
-
|
| 217 |
-
def forward_word_ins(
|
| 218 |
-
self, encoder_outs, output_tokens, output_scores, attn, can_ins_word
|
| 219 |
-
):
|
| 220 |
-
word_ins_score_avg = []
|
| 221 |
-
word_ins_attn_avg = []
|
| 222 |
-
for model, encoder_out in zip(self.models, encoder_outs):
|
| 223 |
-
word_ins_out, word_ins_attn = model.decoder.forward_word_ins(
|
| 224 |
-
_skip(output_tokens, can_ins_word),
|
| 225 |
-
_skip_encoder_out(model.encoder, encoder_out, can_ins_word),
|
| 226 |
-
)
|
| 227 |
-
word_ins_score = F.log_softmax(word_ins_out, 2)
|
| 228 |
-
word_ins_score_avg.append(word_ins_score)
|
| 229 |
-
word_ins_attn_avg.append(word_ins_attn)
|
| 230 |
-
word_ins_score_avg = torch.logsumexp(
|
| 231 |
-
torch.stack(word_ins_score_avg, dim=0), dim=0
|
| 232 |
-
) - math.log(len(self.models))
|
| 233 |
-
if word_ins_attn_avg[0] is not None:
|
| 234 |
-
word_ins_attn_avg = torch.stack(word_ins_attn_avg, dim=0) / len(self.models)
|
| 235 |
-
else:
|
| 236 |
-
word_ins_attn_avg = None
|
| 237 |
-
word_ins_score_max, word_ins_pred = word_ins_score_avg.max(-1)
|
| 238 |
-
|
| 239 |
-
_tokens, _scores = _apply_ins_words(
|
| 240 |
-
output_tokens[can_ins_word],
|
| 241 |
-
output_scores[can_ins_word],
|
| 242 |
-
word_ins_pred,
|
| 243 |
-
word_ins_score_max,
|
| 244 |
-
self.unk,
|
| 245 |
-
)
|
| 246 |
-
|
| 247 |
-
output_tokens = _fill(output_tokens, can_ins_word, _tokens, self.pad)
|
| 248 |
-
output_scores = _fill(output_scores, can_ins_word, _scores, 0)
|
| 249 |
-
attn = _fill(attn, can_ins_word, word_ins_attn, 0.0)
|
| 250 |
-
return output_tokens, output_scores, attn
|
| 251 |
-
|
| 252 |
-
def initialize_output_tokens(self, encoder_outs, src_tokens):
|
| 253 |
-
# LevT doesn't do length prediction.
|
| 254 |
-
return self.models[0].initialize_output_tokens(encoder_outs[0], src_tokens)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/nat/nonautoregressive_transformer.py
DELETED
|
@@ -1,456 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import torch
|
| 7 |
-
import torch.nn.functional as F
|
| 8 |
-
from fairseq import utils
|
| 9 |
-
from fairseq.iterative_refinement_generator import DecoderOut
|
| 10 |
-
from fairseq.models import register_model, register_model_architecture
|
| 11 |
-
from fairseq.models.nat import FairseqNATDecoder, FairseqNATModel, ensemble_decoder
|
| 12 |
-
from fairseq.models.transformer import Embedding
|
| 13 |
-
from fairseq.modules.transformer_sentence_encoder import init_bert_params
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
def _mean_pooling(enc_feats, src_masks):
|
| 17 |
-
# enc_feats: T x B x C
|
| 18 |
-
# src_masks: B x T or None
|
| 19 |
-
if src_masks is None:
|
| 20 |
-
enc_feats = enc_feats.mean(0)
|
| 21 |
-
else:
|
| 22 |
-
src_masks = (~src_masks).transpose(0, 1).type_as(enc_feats)
|
| 23 |
-
enc_feats = (
|
| 24 |
-
(enc_feats / src_masks.sum(0)[None, :, None]) * src_masks[:, :, None]
|
| 25 |
-
).sum(0)
|
| 26 |
-
return enc_feats
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def _argmax(x, dim):
|
| 30 |
-
return (x == x.max(dim, keepdim=True)[0]).type_as(x)
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def _uniform_assignment(src_lens, trg_lens):
|
| 34 |
-
max_trg_len = trg_lens.max()
|
| 35 |
-
steps = (src_lens.float() - 1) / (trg_lens.float() - 1) # step-size
|
| 36 |
-
# max_trg_len
|
| 37 |
-
index_t = utils.new_arange(trg_lens, max_trg_len).float()
|
| 38 |
-
index_t = steps[:, None] * index_t[None, :] # batch_size X max_trg_len
|
| 39 |
-
index_t = torch.round(index_t).long().detach()
|
| 40 |
-
return index_t
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
@register_model("nonautoregressive_transformer")
|
| 44 |
-
class NATransformerModel(FairseqNATModel):
|
| 45 |
-
@property
|
| 46 |
-
def allow_length_beam(self):
|
| 47 |
-
return True
|
| 48 |
-
|
| 49 |
-
@staticmethod
|
| 50 |
-
def add_args(parser):
|
| 51 |
-
FairseqNATModel.add_args(parser)
|
| 52 |
-
|
| 53 |
-
# length prediction
|
| 54 |
-
parser.add_argument(
|
| 55 |
-
"--src-embedding-copy",
|
| 56 |
-
action="store_true",
|
| 57 |
-
help="copy encoder word embeddings as the initial input of the decoder",
|
| 58 |
-
)
|
| 59 |
-
parser.add_argument(
|
| 60 |
-
"--pred-length-offset",
|
| 61 |
-
action="store_true",
|
| 62 |
-
help="predicting the length difference between the target and source sentences",
|
| 63 |
-
)
|
| 64 |
-
parser.add_argument(
|
| 65 |
-
"--sg-length-pred",
|
| 66 |
-
action="store_true",
|
| 67 |
-
help="stop the gradients back-propagated from the length predictor",
|
| 68 |
-
)
|
| 69 |
-
parser.add_argument(
|
| 70 |
-
"--length-loss-factor",
|
| 71 |
-
type=float,
|
| 72 |
-
help="weights on the length prediction loss",
|
| 73 |
-
)
|
| 74 |
-
|
| 75 |
-
@classmethod
|
| 76 |
-
def build_decoder(cls, args, tgt_dict, embed_tokens):
|
| 77 |
-
decoder = NATransformerDecoder(args, tgt_dict, embed_tokens)
|
| 78 |
-
if getattr(args, "apply_bert_init", False):
|
| 79 |
-
decoder.apply(init_bert_params)
|
| 80 |
-
return decoder
|
| 81 |
-
|
| 82 |
-
def forward(
|
| 83 |
-
self, src_tokens, src_lengths, prev_output_tokens, tgt_tokens, **kwargs
|
| 84 |
-
):
|
| 85 |
-
# encoding
|
| 86 |
-
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
|
| 87 |
-
|
| 88 |
-
# length prediction
|
| 89 |
-
length_out = self.decoder.forward_length(
|
| 90 |
-
normalize=False, encoder_out=encoder_out
|
| 91 |
-
)
|
| 92 |
-
length_tgt = self.decoder.forward_length_prediction(
|
| 93 |
-
length_out, encoder_out, tgt_tokens
|
| 94 |
-
)
|
| 95 |
-
|
| 96 |
-
# decoding
|
| 97 |
-
word_ins_out = self.decoder(
|
| 98 |
-
normalize=False,
|
| 99 |
-
prev_output_tokens=prev_output_tokens,
|
| 100 |
-
encoder_out=encoder_out,
|
| 101 |
-
)
|
| 102 |
-
|
| 103 |
-
return {
|
| 104 |
-
"word_ins": {
|
| 105 |
-
"out": word_ins_out,
|
| 106 |
-
"tgt": tgt_tokens,
|
| 107 |
-
"mask": tgt_tokens.ne(self.pad),
|
| 108 |
-
"ls": self.args.label_smoothing,
|
| 109 |
-
"nll_loss": True,
|
| 110 |
-
},
|
| 111 |
-
"length": {
|
| 112 |
-
"out": length_out,
|
| 113 |
-
"tgt": length_tgt,
|
| 114 |
-
"factor": self.decoder.length_loss_factor,
|
| 115 |
-
},
|
| 116 |
-
}
|
| 117 |
-
|
| 118 |
-
def forward_decoder(self, decoder_out, encoder_out, decoding_format=None, **kwargs):
|
| 119 |
-
step = decoder_out.step
|
| 120 |
-
output_tokens = decoder_out.output_tokens
|
| 121 |
-
output_scores = decoder_out.output_scores
|
| 122 |
-
history = decoder_out.history
|
| 123 |
-
|
| 124 |
-
# execute the decoder
|
| 125 |
-
output_masks = output_tokens.ne(self.pad)
|
| 126 |
-
_scores, _tokens = self.decoder(
|
| 127 |
-
normalize=True,
|
| 128 |
-
prev_output_tokens=output_tokens,
|
| 129 |
-
encoder_out=encoder_out,
|
| 130 |
-
step=step,
|
| 131 |
-
).max(-1)
|
| 132 |
-
|
| 133 |
-
output_tokens.masked_scatter_(output_masks, _tokens[output_masks])
|
| 134 |
-
output_scores.masked_scatter_(output_masks, _scores[output_masks])
|
| 135 |
-
if history is not None:
|
| 136 |
-
history.append(output_tokens.clone())
|
| 137 |
-
|
| 138 |
-
return decoder_out._replace(
|
| 139 |
-
output_tokens=output_tokens,
|
| 140 |
-
output_scores=output_scores,
|
| 141 |
-
attn=None,
|
| 142 |
-
history=history,
|
| 143 |
-
)
|
| 144 |
-
|
| 145 |
-
def initialize_output_tokens(self, encoder_out, src_tokens):
|
| 146 |
-
# length prediction
|
| 147 |
-
length_tgt = self.decoder.forward_length_prediction(
|
| 148 |
-
self.decoder.forward_length(normalize=True, encoder_out=encoder_out),
|
| 149 |
-
encoder_out=encoder_out,
|
| 150 |
-
)
|
| 151 |
-
|
| 152 |
-
max_length = length_tgt.clamp_(min=2).max()
|
| 153 |
-
idx_length = utils.new_arange(src_tokens, max_length)
|
| 154 |
-
|
| 155 |
-
initial_output_tokens = src_tokens.new_zeros(
|
| 156 |
-
src_tokens.size(0), max_length
|
| 157 |
-
).fill_(self.pad)
|
| 158 |
-
initial_output_tokens.masked_fill_(
|
| 159 |
-
idx_length[None, :] < length_tgt[:, None], self.unk
|
| 160 |
-
)
|
| 161 |
-
initial_output_tokens[:, 0] = self.bos
|
| 162 |
-
initial_output_tokens.scatter_(1, length_tgt[:, None] - 1, self.eos)
|
| 163 |
-
|
| 164 |
-
initial_output_scores = initial_output_tokens.new_zeros(
|
| 165 |
-
*initial_output_tokens.size()
|
| 166 |
-
).type_as(encoder_out["encoder_out"][0])
|
| 167 |
-
|
| 168 |
-
return DecoderOut(
|
| 169 |
-
output_tokens=initial_output_tokens,
|
| 170 |
-
output_scores=initial_output_scores,
|
| 171 |
-
attn=None,
|
| 172 |
-
step=0,
|
| 173 |
-
max_step=0,
|
| 174 |
-
history=None,
|
| 175 |
-
)
|
| 176 |
-
|
| 177 |
-
def regenerate_length_beam(self, decoder_out, beam_size):
|
| 178 |
-
output_tokens = decoder_out.output_tokens
|
| 179 |
-
length_tgt = output_tokens.ne(self.pad).sum(1)
|
| 180 |
-
length_tgt = (
|
| 181 |
-
length_tgt[:, None]
|
| 182 |
-
+ utils.new_arange(length_tgt, 1, beam_size)
|
| 183 |
-
- beam_size // 2
|
| 184 |
-
)
|
| 185 |
-
length_tgt = length_tgt.view(-1).clamp_(min=2)
|
| 186 |
-
max_length = length_tgt.max()
|
| 187 |
-
idx_length = utils.new_arange(length_tgt, max_length)
|
| 188 |
-
|
| 189 |
-
initial_output_tokens = output_tokens.new_zeros(
|
| 190 |
-
length_tgt.size(0), max_length
|
| 191 |
-
).fill_(self.pad)
|
| 192 |
-
initial_output_tokens.masked_fill_(
|
| 193 |
-
idx_length[None, :] < length_tgt[:, None], self.unk
|
| 194 |
-
)
|
| 195 |
-
initial_output_tokens[:, 0] = self.bos
|
| 196 |
-
initial_output_tokens.scatter_(1, length_tgt[:, None] - 1, self.eos)
|
| 197 |
-
|
| 198 |
-
initial_output_scores = initial_output_tokens.new_zeros(
|
| 199 |
-
*initial_output_tokens.size()
|
| 200 |
-
).type_as(decoder_out.output_scores)
|
| 201 |
-
|
| 202 |
-
return decoder_out._replace(
|
| 203 |
-
output_tokens=initial_output_tokens, output_scores=initial_output_scores
|
| 204 |
-
)
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
class NATransformerDecoder(FairseqNATDecoder):
|
| 208 |
-
def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False):
|
| 209 |
-
super().__init__(
|
| 210 |
-
args, dictionary, embed_tokens, no_encoder_attn=no_encoder_attn
|
| 211 |
-
)
|
| 212 |
-
self.dictionary = dictionary
|
| 213 |
-
self.bos = dictionary.bos()
|
| 214 |
-
self.unk = dictionary.unk()
|
| 215 |
-
self.eos = dictionary.eos()
|
| 216 |
-
|
| 217 |
-
self.encoder_embed_dim = args.encoder_embed_dim
|
| 218 |
-
self.sg_length_pred = getattr(args, "sg_length_pred", False)
|
| 219 |
-
self.pred_length_offset = getattr(args, "pred_length_offset", False)
|
| 220 |
-
self.length_loss_factor = getattr(args, "length_loss_factor", 0.1)
|
| 221 |
-
self.src_embedding_copy = getattr(args, "src_embedding_copy", False)
|
| 222 |
-
self.embed_length = Embedding(256, self.encoder_embed_dim, None)
|
| 223 |
-
|
| 224 |
-
@ensemble_decoder
|
| 225 |
-
def forward(self, normalize, encoder_out, prev_output_tokens, step=0, **unused):
|
| 226 |
-
features, _ = self.extract_features(
|
| 227 |
-
prev_output_tokens,
|
| 228 |
-
encoder_out=encoder_out,
|
| 229 |
-
embedding_copy=(step == 0) & self.src_embedding_copy,
|
| 230 |
-
)
|
| 231 |
-
decoder_out = self.output_layer(features)
|
| 232 |
-
return F.log_softmax(decoder_out, -1) if normalize else decoder_out
|
| 233 |
-
|
| 234 |
-
@ensemble_decoder
|
| 235 |
-
def forward_length(self, normalize, encoder_out):
|
| 236 |
-
enc_feats = encoder_out["encoder_out"][0] # T x B x C
|
| 237 |
-
if len(encoder_out["encoder_padding_mask"]) > 0:
|
| 238 |
-
src_masks = encoder_out["encoder_padding_mask"][0] # B x T
|
| 239 |
-
else:
|
| 240 |
-
src_masks = None
|
| 241 |
-
enc_feats = _mean_pooling(enc_feats, src_masks)
|
| 242 |
-
if self.sg_length_pred:
|
| 243 |
-
enc_feats = enc_feats.detach()
|
| 244 |
-
length_out = F.linear(enc_feats, self.embed_length.weight)
|
| 245 |
-
return F.log_softmax(length_out, -1) if normalize else length_out
|
| 246 |
-
|
| 247 |
-
def extract_features(
|
| 248 |
-
self,
|
| 249 |
-
prev_output_tokens,
|
| 250 |
-
encoder_out=None,
|
| 251 |
-
early_exit=None,
|
| 252 |
-
embedding_copy=False,
|
| 253 |
-
**unused
|
| 254 |
-
):
|
| 255 |
-
"""
|
| 256 |
-
Similar to *forward* but only return features.
|
| 257 |
-
|
| 258 |
-
Inputs:
|
| 259 |
-
prev_output_tokens: Tensor(B, T)
|
| 260 |
-
encoder_out: a dictionary of hidden states and masks
|
| 261 |
-
|
| 262 |
-
Returns:
|
| 263 |
-
tuple:
|
| 264 |
-
- the decoder's features of shape `(batch, tgt_len, embed_dim)`
|
| 265 |
-
- a dictionary with any model-specific outputs
|
| 266 |
-
the LevenshteinTransformer decoder has full-attention to all generated tokens
|
| 267 |
-
"""
|
| 268 |
-
# embedding
|
| 269 |
-
if embedding_copy:
|
| 270 |
-
src_embd = encoder_out["encoder_embedding"][0]
|
| 271 |
-
if len(encoder_out["encoder_padding_mask"]) > 0:
|
| 272 |
-
src_mask = encoder_out["encoder_padding_mask"][0]
|
| 273 |
-
else:
|
| 274 |
-
src_mask = None
|
| 275 |
-
src_mask = (
|
| 276 |
-
~src_mask
|
| 277 |
-
if src_mask is not None
|
| 278 |
-
else prev_output_tokens.new_ones(*src_embd.size()[:2]).bool()
|
| 279 |
-
)
|
| 280 |
-
|
| 281 |
-
x, decoder_padding_mask = self.forward_embedding(
|
| 282 |
-
prev_output_tokens,
|
| 283 |
-
self.forward_copying_source(
|
| 284 |
-
src_embd, src_mask, prev_output_tokens.ne(self.padding_idx)
|
| 285 |
-
),
|
| 286 |
-
)
|
| 287 |
-
|
| 288 |
-
else:
|
| 289 |
-
|
| 290 |
-
x, decoder_padding_mask = self.forward_embedding(prev_output_tokens)
|
| 291 |
-
|
| 292 |
-
# B x T x C -> T x B x C
|
| 293 |
-
x = x.transpose(0, 1)
|
| 294 |
-
attn = None
|
| 295 |
-
inner_states = [x]
|
| 296 |
-
|
| 297 |
-
# decoder layers
|
| 298 |
-
for i, layer in enumerate(self.layers):
|
| 299 |
-
|
| 300 |
-
# early exit from the decoder.
|
| 301 |
-
if (early_exit is not None) and (i >= early_exit):
|
| 302 |
-
break
|
| 303 |
-
|
| 304 |
-
x, attn, _ = layer(
|
| 305 |
-
x,
|
| 306 |
-
encoder_out["encoder_out"][0]
|
| 307 |
-
if (encoder_out is not None and len(encoder_out["encoder_out"]) > 0)
|
| 308 |
-
else None,
|
| 309 |
-
encoder_out["encoder_padding_mask"][0]
|
| 310 |
-
if (
|
| 311 |
-
encoder_out is not None
|
| 312 |
-
and len(encoder_out["encoder_padding_mask"]) > 0
|
| 313 |
-
)
|
| 314 |
-
else None,
|
| 315 |
-
self_attn_mask=None,
|
| 316 |
-
self_attn_padding_mask=decoder_padding_mask,
|
| 317 |
-
)
|
| 318 |
-
inner_states.append(x)
|
| 319 |
-
|
| 320 |
-
if self.layer_norm:
|
| 321 |
-
x = self.layer_norm(x)
|
| 322 |
-
|
| 323 |
-
# T x B x C -> B x T x C
|
| 324 |
-
x = x.transpose(0, 1)
|
| 325 |
-
|
| 326 |
-
if self.project_out_dim is not None:
|
| 327 |
-
x = self.project_out_dim(x)
|
| 328 |
-
|
| 329 |
-
return x, {"attn": attn, "inner_states": inner_states}
|
| 330 |
-
|
| 331 |
-
def forward_embedding(self, prev_output_tokens, states=None):
|
| 332 |
-
# embed positions
|
| 333 |
-
positions = (
|
| 334 |
-
self.embed_positions(prev_output_tokens)
|
| 335 |
-
if self.embed_positions is not None
|
| 336 |
-
else None
|
| 337 |
-
)
|
| 338 |
-
|
| 339 |
-
# embed tokens and positions
|
| 340 |
-
if states is None:
|
| 341 |
-
x = self.embed_scale * self.embed_tokens(prev_output_tokens)
|
| 342 |
-
if self.project_in_dim is not None:
|
| 343 |
-
x = self.project_in_dim(x)
|
| 344 |
-
else:
|
| 345 |
-
x = states
|
| 346 |
-
|
| 347 |
-
if positions is not None:
|
| 348 |
-
x += positions
|
| 349 |
-
x = self.dropout_module(x)
|
| 350 |
-
decoder_padding_mask = prev_output_tokens.eq(self.padding_idx)
|
| 351 |
-
return x, decoder_padding_mask
|
| 352 |
-
|
| 353 |
-
def forward_copying_source(self, src_embeds, src_masks, tgt_masks):
|
| 354 |
-
length_sources = src_masks.sum(1)
|
| 355 |
-
length_targets = tgt_masks.sum(1)
|
| 356 |
-
mapped_inputs = _uniform_assignment(length_sources, length_targets).masked_fill(
|
| 357 |
-
~tgt_masks, 0
|
| 358 |
-
)
|
| 359 |
-
copied_embedding = torch.gather(
|
| 360 |
-
src_embeds,
|
| 361 |
-
1,
|
| 362 |
-
mapped_inputs.unsqueeze(-1).expand(
|
| 363 |
-
*mapped_inputs.size(), src_embeds.size(-1)
|
| 364 |
-
),
|
| 365 |
-
)
|
| 366 |
-
return copied_embedding
|
| 367 |
-
|
| 368 |
-
def forward_length_prediction(self, length_out, encoder_out, tgt_tokens=None):
|
| 369 |
-
enc_feats = encoder_out["encoder_out"][0] # T x B x C
|
| 370 |
-
if len(encoder_out["encoder_padding_mask"]) > 0:
|
| 371 |
-
src_masks = encoder_out["encoder_padding_mask"][0] # B x T
|
| 372 |
-
else:
|
| 373 |
-
src_masks = None
|
| 374 |
-
if self.pred_length_offset:
|
| 375 |
-
if src_masks is None:
|
| 376 |
-
src_lengs = enc_feats.new_ones(enc_feats.size(1)).fill_(
|
| 377 |
-
enc_feats.size(0)
|
| 378 |
-
)
|
| 379 |
-
else:
|
| 380 |
-
src_lengs = (~src_masks).transpose(0, 1).type_as(enc_feats).sum(0)
|
| 381 |
-
src_lengs = src_lengs.long()
|
| 382 |
-
|
| 383 |
-
if tgt_tokens is not None:
|
| 384 |
-
# obtain the length target
|
| 385 |
-
tgt_lengs = tgt_tokens.ne(self.padding_idx).sum(1).long()
|
| 386 |
-
if self.pred_length_offset:
|
| 387 |
-
length_tgt = tgt_lengs - src_lengs + 128
|
| 388 |
-
else:
|
| 389 |
-
length_tgt = tgt_lengs
|
| 390 |
-
length_tgt = length_tgt.clamp(min=0, max=255)
|
| 391 |
-
|
| 392 |
-
else:
|
| 393 |
-
# predict the length target (greedy for now)
|
| 394 |
-
# TODO: implementing length-beam
|
| 395 |
-
pred_lengs = length_out.max(-1)[1]
|
| 396 |
-
if self.pred_length_offset:
|
| 397 |
-
length_tgt = pred_lengs - 128 + src_lengs
|
| 398 |
-
else:
|
| 399 |
-
length_tgt = pred_lengs
|
| 400 |
-
|
| 401 |
-
return length_tgt
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
@register_model_architecture(
|
| 405 |
-
"nonautoregressive_transformer", "nonautoregressive_transformer"
|
| 406 |
-
)
|
| 407 |
-
def base_architecture(args):
|
| 408 |
-
args.encoder_embed_path = getattr(args, "encoder_embed_path", None)
|
| 409 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
|
| 410 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 2048)
|
| 411 |
-
args.encoder_layers = getattr(args, "encoder_layers", 6)
|
| 412 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8)
|
| 413 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
|
| 414 |
-
args.encoder_learned_pos = getattr(args, "encoder_learned_pos", False)
|
| 415 |
-
args.decoder_embed_path = getattr(args, "decoder_embed_path", None)
|
| 416 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", args.encoder_embed_dim)
|
| 417 |
-
args.decoder_ffn_embed_dim = getattr(
|
| 418 |
-
args, "decoder_ffn_embed_dim", args.encoder_ffn_embed_dim
|
| 419 |
-
)
|
| 420 |
-
args.decoder_layers = getattr(args, "decoder_layers", 6)
|
| 421 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 8)
|
| 422 |
-
args.decoder_normalize_before = getattr(args, "decoder_normalize_before", False)
|
| 423 |
-
args.decoder_learned_pos = getattr(args, "decoder_learned_pos", False)
|
| 424 |
-
args.attention_dropout = getattr(args, "attention_dropout", 0.0)
|
| 425 |
-
args.activation_dropout = getattr(args, "activation_dropout", 0.0)
|
| 426 |
-
args.activation_fn = getattr(args, "activation_fn", "relu")
|
| 427 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 428 |
-
args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
|
| 429 |
-
args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
|
| 430 |
-
args.share_decoder_input_output_embed = getattr(
|
| 431 |
-
args, "share_decoder_input_output_embed", False
|
| 432 |
-
)
|
| 433 |
-
args.share_all_embeddings = getattr(args, "share_all_embeddings", False)
|
| 434 |
-
args.no_token_positional_embeddings = getattr(
|
| 435 |
-
args, "no_token_positional_embeddings", False
|
| 436 |
-
)
|
| 437 |
-
args.adaptive_input = getattr(args, "adaptive_input", False)
|
| 438 |
-
args.apply_bert_init = getattr(args, "apply_bert_init", False)
|
| 439 |
-
|
| 440 |
-
args.decoder_output_dim = getattr(
|
| 441 |
-
args, "decoder_output_dim", args.decoder_embed_dim
|
| 442 |
-
)
|
| 443 |
-
args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim)
|
| 444 |
-
|
| 445 |
-
# --- special arguments ---
|
| 446 |
-
args.sg_length_pred = getattr(args, "sg_length_pred", False)
|
| 447 |
-
args.pred_length_offset = getattr(args, "pred_length_offset", False)
|
| 448 |
-
args.length_loss_factor = getattr(args, "length_loss_factor", 0.1)
|
| 449 |
-
args.src_embedding_copy = getattr(args, "src_embedding_copy", False)
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
@register_model_architecture(
|
| 453 |
-
"nonautoregressive_transformer", "nonautoregressive_transformer_wmt_en_de"
|
| 454 |
-
)
|
| 455 |
-
def nonautoregressive_transformer_wmt_en_de(args):
|
| 456 |
-
base_architecture(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/__init__.py
DELETED
|
@@ -1,11 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
from .enc_dec import * # noqa
|
| 7 |
-
from .hub_interface import * # noqa
|
| 8 |
-
from .model import * # noqa
|
| 9 |
-
from .model_camembert import * # noqa
|
| 10 |
-
from .model_gottbert import * # noqa
|
| 11 |
-
from .model_xlmr import * # noqa
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/alignment_utils.py
DELETED
|
@@ -1,118 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
from collections import Counter
|
| 7 |
-
from typing import List
|
| 8 |
-
|
| 9 |
-
import torch
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
def align_bpe_to_words(roberta, bpe_tokens: torch.LongTensor, other_tokens: List[str]):
|
| 13 |
-
"""
|
| 14 |
-
Helper to align GPT-2 BPE to other tokenization formats (e.g., spaCy).
|
| 15 |
-
|
| 16 |
-
Args:
|
| 17 |
-
roberta (RobertaHubInterface): RoBERTa instance
|
| 18 |
-
bpe_tokens (torch.LongTensor): GPT-2 BPE tokens of shape `(T_bpe)`
|
| 19 |
-
other_tokens (List[str]): other tokens of shape `(T_words)`
|
| 20 |
-
|
| 21 |
-
Returns:
|
| 22 |
-
List[str]: mapping from *other_tokens* to corresponding *bpe_tokens*.
|
| 23 |
-
"""
|
| 24 |
-
assert bpe_tokens.dim() == 1
|
| 25 |
-
assert bpe_tokens[0] == 0
|
| 26 |
-
|
| 27 |
-
def clean(text):
|
| 28 |
-
return text.strip()
|
| 29 |
-
|
| 30 |
-
# remove whitespaces to simplify alignment
|
| 31 |
-
bpe_tokens = [roberta.task.source_dictionary.string([x]) for x in bpe_tokens]
|
| 32 |
-
bpe_tokens = [
|
| 33 |
-
clean(roberta.bpe.decode(x) if x not in {"<s>", ""} else x) for x in bpe_tokens
|
| 34 |
-
]
|
| 35 |
-
other_tokens = [clean(str(o)) for o in other_tokens]
|
| 36 |
-
|
| 37 |
-
# strip leading <s>
|
| 38 |
-
bpe_tokens = bpe_tokens[1:]
|
| 39 |
-
assert "".join(bpe_tokens) == "".join(other_tokens)
|
| 40 |
-
|
| 41 |
-
# create alignment from every word to a list of BPE tokens
|
| 42 |
-
alignment = []
|
| 43 |
-
bpe_toks = filter(lambda item: item[1] != "", enumerate(bpe_tokens, start=1))
|
| 44 |
-
j, bpe_tok = next(bpe_toks)
|
| 45 |
-
for other_tok in other_tokens:
|
| 46 |
-
bpe_indices = []
|
| 47 |
-
while True:
|
| 48 |
-
if other_tok.startswith(bpe_tok):
|
| 49 |
-
bpe_indices.append(j)
|
| 50 |
-
other_tok = other_tok[len(bpe_tok) :]
|
| 51 |
-
try:
|
| 52 |
-
j, bpe_tok = next(bpe_toks)
|
| 53 |
-
except StopIteration:
|
| 54 |
-
j, bpe_tok = None, None
|
| 55 |
-
elif bpe_tok.startswith(other_tok):
|
| 56 |
-
# other_tok spans multiple BPE tokens
|
| 57 |
-
bpe_indices.append(j)
|
| 58 |
-
bpe_tok = bpe_tok[len(other_tok) :]
|
| 59 |
-
other_tok = ""
|
| 60 |
-
else:
|
| 61 |
-
raise Exception('Cannot align "{}" and "{}"'.format(other_tok, bpe_tok))
|
| 62 |
-
if other_tok == "":
|
| 63 |
-
break
|
| 64 |
-
assert len(bpe_indices) > 0
|
| 65 |
-
alignment.append(bpe_indices)
|
| 66 |
-
assert len(alignment) == len(other_tokens)
|
| 67 |
-
|
| 68 |
-
return alignment
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
def align_features_to_words(roberta, features, alignment):
|
| 72 |
-
"""
|
| 73 |
-
Align given features to words.
|
| 74 |
-
|
| 75 |
-
Args:
|
| 76 |
-
roberta (RobertaHubInterface): RoBERTa instance
|
| 77 |
-
features (torch.Tensor): features to align of shape `(T_bpe x C)`
|
| 78 |
-
alignment: alignment between BPE tokens and words returned by
|
| 79 |
-
func:`align_bpe_to_words`.
|
| 80 |
-
"""
|
| 81 |
-
assert features.dim() == 2
|
| 82 |
-
|
| 83 |
-
bpe_counts = Counter(j for bpe_indices in alignment for j in bpe_indices)
|
| 84 |
-
assert bpe_counts[0] == 0 # <s> shouldn't be aligned
|
| 85 |
-
denom = features.new([bpe_counts.get(j, 1) for j in range(len(features))])
|
| 86 |
-
weighted_features = features / denom.unsqueeze(-1)
|
| 87 |
-
|
| 88 |
-
output = [weighted_features[0]]
|
| 89 |
-
largest_j = -1
|
| 90 |
-
for bpe_indices in alignment:
|
| 91 |
-
output.append(weighted_features[bpe_indices].sum(dim=0))
|
| 92 |
-
largest_j = max(largest_j, *bpe_indices)
|
| 93 |
-
for j in range(largest_j + 1, len(features)):
|
| 94 |
-
output.append(weighted_features[j])
|
| 95 |
-
output = torch.stack(output)
|
| 96 |
-
assert torch.all(torch.abs(output.sum(dim=0) - features.sum(dim=0)) < 1e-4)
|
| 97 |
-
return output
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
def spacy_nlp():
|
| 101 |
-
if getattr(spacy_nlp, "_nlp", None) is None:
|
| 102 |
-
try:
|
| 103 |
-
from spacy.lang.en import English
|
| 104 |
-
|
| 105 |
-
spacy_nlp._nlp = English()
|
| 106 |
-
except ImportError:
|
| 107 |
-
raise ImportError("Please install spacy with: pip install spacy")
|
| 108 |
-
return spacy_nlp._nlp
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
def spacy_tokenizer():
|
| 112 |
-
if getattr(spacy_tokenizer, "_tokenizer", None) is None:
|
| 113 |
-
try:
|
| 114 |
-
nlp = spacy_nlp()
|
| 115 |
-
spacy_tokenizer._tokenizer = nlp.Defaults.create_tokenizer(nlp)
|
| 116 |
-
except ImportError:
|
| 117 |
-
raise ImportError("Please install spacy with: pip install spacy")
|
| 118 |
-
return spacy_tokenizer._tokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/enc_dec.py
DELETED
|
@@ -1,192 +0,0 @@
|
|
| 1 |
-
import argparse
|
| 2 |
-
import logging
|
| 3 |
-
|
| 4 |
-
import fairseq.checkpoint_utils
|
| 5 |
-
import torch.nn as nn
|
| 6 |
-
from fairseq.models import (
|
| 7 |
-
FairseqEncoderDecoderModel,
|
| 8 |
-
register_model,
|
| 9 |
-
register_model_architecture,
|
| 10 |
-
)
|
| 11 |
-
from fairseq.models.roberta import model as roberta
|
| 12 |
-
from fairseq.models.transformer import TransformerDecoder
|
| 13 |
-
|
| 14 |
-
logger = logging.getLogger(__name__)
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
@register_model("roberta_enc_dec")
|
| 18 |
-
class RobertaEncDecModel(FairseqEncoderDecoderModel):
|
| 19 |
-
@staticmethod
|
| 20 |
-
def add_args(parser):
|
| 21 |
-
parser.add_argument(
|
| 22 |
-
"--pretrained-mlm-checkpoint",
|
| 23 |
-
default=None,
|
| 24 |
-
type=str,
|
| 25 |
-
metavar="PRETRAINED",
|
| 26 |
-
help="path to pretrained mlm checkpoint",
|
| 27 |
-
)
|
| 28 |
-
parser.add_argument(
|
| 29 |
-
"--pretrained-decoder", action="store_true", help="reload decoder"
|
| 30 |
-
)
|
| 31 |
-
parser.add_argument(
|
| 32 |
-
"--hack-layernorm-embedding",
|
| 33 |
-
action="store_true",
|
| 34 |
-
help="hack to reload old models trained with encoder-normalize-before=False (no equivalent to encoder-normalize-before=False and layernorm_embedding=False",
|
| 35 |
-
)
|
| 36 |
-
parser.add_argument(
|
| 37 |
-
"--share-decoder-input-output-embed",
|
| 38 |
-
action="store_true",
|
| 39 |
-
help="share decoder input and output embeddings",
|
| 40 |
-
)
|
| 41 |
-
parser.add_argument(
|
| 42 |
-
"--share-all-embeddings",
|
| 43 |
-
action="store_true",
|
| 44 |
-
help="share encoder, decoder and output embeddings"
|
| 45 |
-
" (requires shared dictionary and embed dim)",
|
| 46 |
-
)
|
| 47 |
-
|
| 48 |
-
@classmethod
|
| 49 |
-
def build_model(cls, args, task):
|
| 50 |
-
"""Build a new model instance."""
|
| 51 |
-
|
| 52 |
-
# make sure all arguments are present
|
| 53 |
-
base_enc_dec_architecture(args)
|
| 54 |
-
if args.pretrained_mlm_checkpoint:
|
| 55 |
-
arg_overrides = None
|
| 56 |
-
if args.hack_layernorm_embedding:
|
| 57 |
-
arg_overrides = {"layernorm_embedding": False}
|
| 58 |
-
loaded = fairseq.checkpoint_utils.load_model_ensemble_and_task(
|
| 59 |
-
[args.pretrained_mlm_checkpoint], arg_overrides=arg_overrides
|
| 60 |
-
)
|
| 61 |
-
([roberta_enc], _cfg, _task) = loaded
|
| 62 |
-
else:
|
| 63 |
-
# Do we need to edit untie_weights here ?
|
| 64 |
-
share_in_out = (
|
| 65 |
-
args.share_decoder_input_output_embed or args.share_all_embeddings
|
| 66 |
-
)
|
| 67 |
-
args.untie_weights_roberta = not share_in_out
|
| 68 |
-
if args.hack_layernorm_embedding:
|
| 69 |
-
args.layernorm_embedding = False
|
| 70 |
-
args.encoder_normalize_before = False
|
| 71 |
-
roberta_enc = roberta.RobertaModel.build_model(args, task)
|
| 72 |
-
|
| 73 |
-
return cls.from_roberta(roberta_enc, args, task.source_dictionary)
|
| 74 |
-
|
| 75 |
-
@staticmethod
|
| 76 |
-
def from_roberta(roberta_enc: roberta.RobertaModel, args, dictionary):
|
| 77 |
-
encoder = roberta_enc.encoder.sentence_encoder
|
| 78 |
-
vocab_size, embed_dim = encoder.embed_tokens.weight.shape
|
| 79 |
-
|
| 80 |
-
if args.share_all_embeddings:
|
| 81 |
-
lm_head = roberta_enc.encoder.lm_head
|
| 82 |
-
assert encoder.embed_tokens.weight is lm_head.weight, (
|
| 83 |
-
"Can't use --share-all-embeddings with a model "
|
| 84 |
-
"that was pretraiend with --untie-weights-roberta_enc"
|
| 85 |
-
)
|
| 86 |
-
else:
|
| 87 |
-
lm_head = roberta.RobertaLMHead(
|
| 88 |
-
embed_dim, vocab_size, roberta_enc.args.activation_fn
|
| 89 |
-
)
|
| 90 |
-
|
| 91 |
-
dec_embs = nn.Embedding(vocab_size, embed_dim, dictionary.pad())
|
| 92 |
-
if args.share_all_embeddings or args.share_decoder_input_output_embed:
|
| 93 |
-
# Note: I wasn't able to use Embedding _weight parameter to achive this sharing.
|
| 94 |
-
dec_embs.weight = lm_head.weight
|
| 95 |
-
|
| 96 |
-
decoder = TransformerDecoder(
|
| 97 |
-
RobertaEncDecModel.read_args_from_roberta(roberta_enc.args),
|
| 98 |
-
dictionary,
|
| 99 |
-
dec_embs,
|
| 100 |
-
no_encoder_attn=False,
|
| 101 |
-
output_projection=lm_head,
|
| 102 |
-
)
|
| 103 |
-
if getattr(args, "pretrained_decoder", False):
|
| 104 |
-
decoder_dict = encoder.state_dict()
|
| 105 |
-
|
| 106 |
-
# TODO: hide setting "encoder_attn" layers behind a flag.
|
| 107 |
-
for k, w in list(decoder_dict.items()):
|
| 108 |
-
if ".self_attn" in k:
|
| 109 |
-
k_enc_attn = k.replace(".self_attn", ".encoder_attn")
|
| 110 |
-
decoder_dict[k_enc_attn] = w.detach().clone()
|
| 111 |
-
|
| 112 |
-
for k, w in lm_head.state_dict().items():
|
| 113 |
-
decoder_dict["output_projection." + k] = w
|
| 114 |
-
|
| 115 |
-
missing_keys, unexpected_keys = decoder.load_state_dict(
|
| 116 |
-
decoder_dict, strict=False
|
| 117 |
-
)
|
| 118 |
-
# missing_keys = [m for m in missing_keys if ".encoder_attn" not in m]
|
| 119 |
-
assert not missing_keys and not unexpected_keys, (
|
| 120 |
-
"Failed to load state dict. "
|
| 121 |
-
f"Missing keys: {missing_keys}. "
|
| 122 |
-
f"Unexpected keys: {unexpected_keys}."
|
| 123 |
-
)
|
| 124 |
-
|
| 125 |
-
if args.share_all_embeddings:
|
| 126 |
-
assert decoder.output_projection.weight is decoder.embed_tokens.weight
|
| 127 |
-
assert encoder.embed_tokens.weight is decoder.embed_tokens.weight
|
| 128 |
-
elif args.share_decoder_input_output_embed:
|
| 129 |
-
assert decoder.output_projection.weight is decoder.embed_tokens.weight
|
| 130 |
-
assert encoder.embed_tokens.weight is not decoder.embed_tokens.weight
|
| 131 |
-
else:
|
| 132 |
-
assert decoder.output_projection.weight is not decoder.embed_tokens.weight
|
| 133 |
-
assert encoder.embed_tokens.weight is not decoder.embed_tokens.weight
|
| 134 |
-
|
| 135 |
-
return RobertaEncDecModel(encoder, decoder)
|
| 136 |
-
|
| 137 |
-
@staticmethod
|
| 138 |
-
def read_args_from_roberta(roberta_args: argparse.Namespace):
|
| 139 |
-
# TODO: this would become easier if encoder/decoder where using a similar
|
| 140 |
-
# TransformerConfig object
|
| 141 |
-
args = argparse.Namespace(**vars(roberta_args))
|
| 142 |
-
attr_map = [
|
| 143 |
-
("encoder_attention_heads", "decoder_attention_heads"),
|
| 144 |
-
("encoder_embed_dim", "decoder_embed_dim"),
|
| 145 |
-
("encoder_embed_dim", "decoder_output_dim"),
|
| 146 |
-
("encoder_normalize_before", "decoder_normalize_before"),
|
| 147 |
-
("encoder_layers_to_keep", "decoder_layers_to_keep"),
|
| 148 |
-
("encoder_ffn_embed_dim", "decoder_ffn_embed_dim"),
|
| 149 |
-
("encoder_layerdrop", "decoder_layerdrop"),
|
| 150 |
-
("encoder_layers", "decoder_layers"),
|
| 151 |
-
("encoder_learned_pos", "decoder_learned_pos"),
|
| 152 |
-
# should this be set from here ?
|
| 153 |
-
("max_positions", "max_target_positions"),
|
| 154 |
-
]
|
| 155 |
-
for k1, k2 in attr_map:
|
| 156 |
-
setattr(args, k2, getattr(roberta_args, k1))
|
| 157 |
-
|
| 158 |
-
args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
|
| 159 |
-
args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
|
| 160 |
-
args.share_decoder_input_output_embed = not roberta_args.untie_weights_roberta
|
| 161 |
-
return args
|
| 162 |
-
|
| 163 |
-
def upgrade_state_dict_named(self, state_dict, name):
|
| 164 |
-
prefix = name + "." if name != "" else ""
|
| 165 |
-
super().upgrade_state_dict_named(state_dict, name)
|
| 166 |
-
old_keys = list(state_dict.keys())
|
| 167 |
-
|
| 168 |
-
# rename decoder -> encoder before upgrading children modules
|
| 169 |
-
for k in old_keys:
|
| 170 |
-
if k.startswith(prefix + "encoder.lm_head"):
|
| 171 |
-
state_dict.pop(k)
|
| 172 |
-
continue
|
| 173 |
-
new_k = k
|
| 174 |
-
new_k = new_k.replace(".sentence_encoder.", ".")
|
| 175 |
-
new_k = new_k.replace("decoder.lm_head.", "decoder.output_projection.")
|
| 176 |
-
if k == new_k:
|
| 177 |
-
continue
|
| 178 |
-
# print(k, "->", new_k)
|
| 179 |
-
state_dict[new_k] = state_dict.pop(k)
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
@register_model_architecture("roberta_enc_dec", "roberta_enc_dec")
|
| 183 |
-
def base_enc_dec_architecture(args):
|
| 184 |
-
args.hack_layernorm_embedding = getattr(args, "hack_layernorm_embedding", False)
|
| 185 |
-
args.pretrained_mlm_checkpoint = getattr(args, "pretrained_mlm_checkpoint", None)
|
| 186 |
-
args.pretrained_decoder = getattr(args, "pretrained_decoder", None)
|
| 187 |
-
args.share_all_embeddings = getattr(args, "share_all_embeddings", False)
|
| 188 |
-
args.share_decoder_input_output_embed = getattr(
|
| 189 |
-
args, "share_decoder_input_output_embed", False
|
| 190 |
-
)
|
| 191 |
-
|
| 192 |
-
roberta.base_architecture(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/hub_interface.py
DELETED
|
@@ -1,235 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import numpy as np
|
| 7 |
-
import torch
|
| 8 |
-
import torch.nn as nn
|
| 9 |
-
import torch.nn.functional as F
|
| 10 |
-
from fairseq import utils
|
| 11 |
-
from fairseq.data import encoders
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
class RobertaHubInterface(nn.Module):
|
| 15 |
-
"""A simple PyTorch Hub interface to RoBERTa.
|
| 16 |
-
|
| 17 |
-
Usage: https://github.com/pytorch/fairseq/tree/main/examples/roberta
|
| 18 |
-
"""
|
| 19 |
-
|
| 20 |
-
def __init__(self, cfg, task, model):
|
| 21 |
-
super().__init__()
|
| 22 |
-
self.cfg = cfg
|
| 23 |
-
self.task = task
|
| 24 |
-
self.model = model
|
| 25 |
-
|
| 26 |
-
self.bpe = encoders.build_bpe(cfg.bpe)
|
| 27 |
-
|
| 28 |
-
# this is useful for determining the device
|
| 29 |
-
self.register_buffer("_float_tensor", torch.tensor([0], dtype=torch.float))
|
| 30 |
-
|
| 31 |
-
@property
|
| 32 |
-
def device(self):
|
| 33 |
-
return self._float_tensor.device
|
| 34 |
-
|
| 35 |
-
def encode(
|
| 36 |
-
self, sentence: str, *addl_sentences, no_separator=False
|
| 37 |
-
) -> torch.LongTensor:
|
| 38 |
-
"""
|
| 39 |
-
BPE-encode a sentence (or multiple sentences).
|
| 40 |
-
|
| 41 |
-
Every sequence begins with a beginning-of-sentence (`<s>`) symbol.
|
| 42 |
-
Every sentence ends with an end-of-sentence (`</s>`) and we use an
|
| 43 |
-
extra end-of-sentence (`</s>`) as a separator.
|
| 44 |
-
|
| 45 |
-
Example (single sentence): `<s> a b c </s>`
|
| 46 |
-
Example (sentence pair): `<s> d e f </s> </s> 1 2 3 </s>`
|
| 47 |
-
|
| 48 |
-
The BPE encoding follows GPT-2. One subtle detail is that the GPT-2 BPE
|
| 49 |
-
requires leading spaces. For example::
|
| 50 |
-
|
| 51 |
-
>>> roberta.encode('Hello world').tolist()
|
| 52 |
-
[0, 31414, 232, 2]
|
| 53 |
-
>>> roberta.encode(' world').tolist()
|
| 54 |
-
[0, 232, 2]
|
| 55 |
-
>>> roberta.encode('world').tolist()
|
| 56 |
-
[0, 8331, 2]
|
| 57 |
-
"""
|
| 58 |
-
bpe_sentence = "<s> " + self.bpe.encode(sentence) + " </s>"
|
| 59 |
-
for s in addl_sentences:
|
| 60 |
-
bpe_sentence += " </s>" if not no_separator else ""
|
| 61 |
-
bpe_sentence += " " + self.bpe.encode(s) + " </s>"
|
| 62 |
-
tokens = self.task.source_dictionary.encode_line(
|
| 63 |
-
bpe_sentence, append_eos=False, add_if_not_exist=False
|
| 64 |
-
)
|
| 65 |
-
return tokens.long()
|
| 66 |
-
|
| 67 |
-
def decode(self, tokens: torch.LongTensor):
|
| 68 |
-
assert tokens.dim() == 1
|
| 69 |
-
tokens = tokens.numpy()
|
| 70 |
-
if tokens[0] == self.task.source_dictionary.bos():
|
| 71 |
-
tokens = tokens[1:] # remove <s>
|
| 72 |
-
eos_mask = tokens == self.task.source_dictionary.eos()
|
| 73 |
-
doc_mask = eos_mask[1:] & eos_mask[:-1]
|
| 74 |
-
sentences = np.split(tokens, doc_mask.nonzero()[0] + 1)
|
| 75 |
-
sentences = [
|
| 76 |
-
self.bpe.decode(self.task.source_dictionary.string(s)) for s in sentences
|
| 77 |
-
]
|
| 78 |
-
if len(sentences) == 1:
|
| 79 |
-
return sentences[0]
|
| 80 |
-
return sentences
|
| 81 |
-
|
| 82 |
-
def extract_features(
|
| 83 |
-
self, tokens: torch.LongTensor, return_all_hiddens: bool = False
|
| 84 |
-
) -> torch.Tensor:
|
| 85 |
-
if tokens.dim() == 1:
|
| 86 |
-
tokens = tokens.unsqueeze(0)
|
| 87 |
-
if tokens.size(-1) > self.model.max_positions():
|
| 88 |
-
raise ValueError(
|
| 89 |
-
"tokens exceeds maximum length: {} > {}".format(
|
| 90 |
-
tokens.size(-1), self.model.max_positions()
|
| 91 |
-
)
|
| 92 |
-
)
|
| 93 |
-
features, extra = self.model(
|
| 94 |
-
tokens.to(device=self.device),
|
| 95 |
-
features_only=True,
|
| 96 |
-
return_all_hiddens=return_all_hiddens,
|
| 97 |
-
)
|
| 98 |
-
if return_all_hiddens:
|
| 99 |
-
# convert from T x B x C -> B x T x C
|
| 100 |
-
inner_states = extra["inner_states"]
|
| 101 |
-
return [inner_state.transpose(0, 1) for inner_state in inner_states]
|
| 102 |
-
else:
|
| 103 |
-
return features # just the last layer's features
|
| 104 |
-
|
| 105 |
-
def register_classification_head(
|
| 106 |
-
self, name: str, num_classes: int = None, embedding_size: int = None, **kwargs
|
| 107 |
-
):
|
| 108 |
-
self.model.register_classification_head(
|
| 109 |
-
name, num_classes=num_classes, embedding_size=embedding_size, **kwargs
|
| 110 |
-
)
|
| 111 |
-
|
| 112 |
-
def predict(self, head: str, tokens: torch.LongTensor, return_logits: bool = False):
|
| 113 |
-
features = self.extract_features(tokens.to(device=self.device))
|
| 114 |
-
logits = self.model.classification_heads[head](features)
|
| 115 |
-
if return_logits:
|
| 116 |
-
return logits
|
| 117 |
-
return F.log_softmax(logits, dim=-1)
|
| 118 |
-
|
| 119 |
-
def extract_features_aligned_to_words(
|
| 120 |
-
self, sentence: str, return_all_hiddens: bool = False
|
| 121 |
-
) -> torch.Tensor:
|
| 122 |
-
"""Extract RoBERTa features, aligned to spaCy's word-level tokenizer."""
|
| 123 |
-
from fairseq.models.roberta import alignment_utils
|
| 124 |
-
from spacy.tokens import Doc
|
| 125 |
-
|
| 126 |
-
nlp = alignment_utils.spacy_nlp()
|
| 127 |
-
tokenizer = alignment_utils.spacy_tokenizer()
|
| 128 |
-
|
| 129 |
-
# tokenize both with GPT-2 BPE and spaCy
|
| 130 |
-
bpe_toks = self.encode(sentence)
|
| 131 |
-
spacy_toks = tokenizer(sentence)
|
| 132 |
-
spacy_toks_ws = [t.text_with_ws for t in tokenizer(sentence)]
|
| 133 |
-
alignment = alignment_utils.align_bpe_to_words(self, bpe_toks, spacy_toks_ws)
|
| 134 |
-
|
| 135 |
-
# extract features and align them
|
| 136 |
-
features = self.extract_features(
|
| 137 |
-
bpe_toks, return_all_hiddens=return_all_hiddens
|
| 138 |
-
)
|
| 139 |
-
features = features.squeeze(0)
|
| 140 |
-
aligned_feats = alignment_utils.align_features_to_words(
|
| 141 |
-
self, features, alignment
|
| 142 |
-
)
|
| 143 |
-
|
| 144 |
-
# wrap in spaCy Doc
|
| 145 |
-
doc = Doc(
|
| 146 |
-
nlp.vocab,
|
| 147 |
-
words=["<s>"] + [x.text for x in spacy_toks] + ["</s>"],
|
| 148 |
-
spaces=[True]
|
| 149 |
-
+ [x.endswith(" ") for x in spacy_toks_ws[:-1]]
|
| 150 |
-
+ [True, False],
|
| 151 |
-
)
|
| 152 |
-
assert len(doc) == aligned_feats.size(0)
|
| 153 |
-
doc.user_token_hooks["vector"] = lambda token: aligned_feats[token.i]
|
| 154 |
-
return doc
|
| 155 |
-
|
| 156 |
-
def fill_mask(self, masked_input: str, topk: int = 5):
|
| 157 |
-
masked_token = "<mask>"
|
| 158 |
-
assert (
|
| 159 |
-
masked_token in masked_input and masked_input.count(masked_token) == 1
|
| 160 |
-
), "Please add one {0} token for the input, eg: 'He is a {0} guy'".format(
|
| 161 |
-
masked_token
|
| 162 |
-
)
|
| 163 |
-
|
| 164 |
-
text_spans = masked_input.split(masked_token)
|
| 165 |
-
text_spans_bpe = (
|
| 166 |
-
(" {0} ".format(masked_token))
|
| 167 |
-
.join([self.bpe.encode(text_span.rstrip()) for text_span in text_spans])
|
| 168 |
-
.strip()
|
| 169 |
-
)
|
| 170 |
-
tokens = self.task.source_dictionary.encode_line(
|
| 171 |
-
"<s> " + text_spans_bpe + " </s>",
|
| 172 |
-
append_eos=False,
|
| 173 |
-
add_if_not_exist=False,
|
| 174 |
-
)
|
| 175 |
-
|
| 176 |
-
masked_index = (tokens == self.task.mask_idx).nonzero(as_tuple=False)
|
| 177 |
-
if tokens.dim() == 1:
|
| 178 |
-
tokens = tokens.unsqueeze(0)
|
| 179 |
-
|
| 180 |
-
with utils.model_eval(self.model):
|
| 181 |
-
features, extra = self.model(
|
| 182 |
-
tokens.long().to(device=self.device),
|
| 183 |
-
features_only=False,
|
| 184 |
-
return_all_hiddens=False,
|
| 185 |
-
)
|
| 186 |
-
logits = features[0, masked_index, :].squeeze()
|
| 187 |
-
prob = logits.softmax(dim=0)
|
| 188 |
-
values, index = prob.topk(k=topk, dim=0)
|
| 189 |
-
topk_predicted_token_bpe = self.task.source_dictionary.string(index)
|
| 190 |
-
|
| 191 |
-
topk_filled_outputs = []
|
| 192 |
-
for index, predicted_token_bpe in enumerate(
|
| 193 |
-
topk_predicted_token_bpe.split(" ")
|
| 194 |
-
):
|
| 195 |
-
predicted_token = self.bpe.decode(predicted_token_bpe)
|
| 196 |
-
# Quick hack to fix https://github.com/pytorch/fairseq/issues/1306
|
| 197 |
-
if predicted_token_bpe.startswith("\u2581"):
|
| 198 |
-
predicted_token = " " + predicted_token
|
| 199 |
-
if " {0}".format(masked_token) in masked_input:
|
| 200 |
-
topk_filled_outputs.append(
|
| 201 |
-
(
|
| 202 |
-
masked_input.replace(
|
| 203 |
-
" {0}".format(masked_token), predicted_token
|
| 204 |
-
),
|
| 205 |
-
values[index].item(),
|
| 206 |
-
predicted_token,
|
| 207 |
-
)
|
| 208 |
-
)
|
| 209 |
-
else:
|
| 210 |
-
topk_filled_outputs.append(
|
| 211 |
-
(
|
| 212 |
-
masked_input.replace(masked_token, predicted_token),
|
| 213 |
-
values[index].item(),
|
| 214 |
-
predicted_token,
|
| 215 |
-
)
|
| 216 |
-
)
|
| 217 |
-
return topk_filled_outputs
|
| 218 |
-
|
| 219 |
-
def disambiguate_pronoun(self, sentence: str) -> bool:
|
| 220 |
-
"""
|
| 221 |
-
Usage::
|
| 222 |
-
|
| 223 |
-
>>> disambiguate_pronoun('The _trophy_ would not fit in the brown suitcase because [it] was too big.')
|
| 224 |
-
True
|
| 225 |
-
|
| 226 |
-
>>> disambiguate_pronoun('The trophy would not fit in the brown suitcase because [it] was too big.')
|
| 227 |
-
'The trophy'
|
| 228 |
-
"""
|
| 229 |
-
assert hasattr(
|
| 230 |
-
self.task, "disambiguate_pronoun"
|
| 231 |
-
), "roberta.disambiguate_pronoun() requires a model trained with the WSC task."
|
| 232 |
-
with utils.model_eval(self.model):
|
| 233 |
-
return self.task.disambiguate_pronoun(
|
| 234 |
-
self.model, sentence, use_cuda=self.device.type == "cuda"
|
| 235 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/model.py
DELETED
|
@@ -1,699 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
"""
|
| 6 |
-
RoBERTa: A Robustly Optimized BERT Pretraining Approach.
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
import logging
|
| 10 |
-
|
| 11 |
-
import torch
|
| 12 |
-
import torch.nn as nn
|
| 13 |
-
import torch.nn.functional as F
|
| 14 |
-
from fairseq import utils
|
| 15 |
-
from fairseq.models import (
|
| 16 |
-
FairseqEncoder,
|
| 17 |
-
FairseqEncoderModel,
|
| 18 |
-
register_model,
|
| 19 |
-
register_model_architecture,
|
| 20 |
-
)
|
| 21 |
-
from fairseq.models.transformer import DEFAULT_MIN_PARAMS_TO_WRAP, TransformerEncoder
|
| 22 |
-
from fairseq.modules import LayerNorm
|
| 23 |
-
from fairseq.modules.quant_noise import quant_noise as apply_quant_noise_
|
| 24 |
-
from fairseq.modules.transformer_sentence_encoder import init_bert_params
|
| 25 |
-
from fairseq.utils import safe_getattr, safe_hasattr
|
| 26 |
-
|
| 27 |
-
from .hub_interface import RobertaHubInterface
|
| 28 |
-
|
| 29 |
-
logger = logging.getLogger(__name__)
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
@register_model("roberta")
|
| 33 |
-
class RobertaModel(FairseqEncoderModel):
|
| 34 |
-
@classmethod
|
| 35 |
-
def hub_models(cls):
|
| 36 |
-
return {
|
| 37 |
-
"roberta.base": "http://dl.fbaipublicfiles.com/fairseq/models/roberta.base.tar.gz",
|
| 38 |
-
"roberta.large": "http://dl.fbaipublicfiles.com/fairseq/models/roberta.large.tar.gz",
|
| 39 |
-
"roberta.large.mnli": "http://dl.fbaipublicfiles.com/fairseq/models/roberta.large.mnli.tar.gz",
|
| 40 |
-
"roberta.large.wsc": "http://dl.fbaipublicfiles.com/fairseq/models/roberta.large.wsc.tar.gz",
|
| 41 |
-
}
|
| 42 |
-
|
| 43 |
-
def __init__(self, args, encoder):
|
| 44 |
-
super().__init__(encoder)
|
| 45 |
-
self.args = args
|
| 46 |
-
|
| 47 |
-
# We follow BERT's random weight initialization
|
| 48 |
-
self.apply(init_bert_params)
|
| 49 |
-
|
| 50 |
-
self.classification_heads = nn.ModuleDict()
|
| 51 |
-
|
| 52 |
-
@staticmethod
|
| 53 |
-
def add_args(parser):
|
| 54 |
-
"""Add model-specific arguments to the parser."""
|
| 55 |
-
parser.add_argument(
|
| 56 |
-
"--encoder-layers", type=int, metavar="L", help="num encoder layers"
|
| 57 |
-
)
|
| 58 |
-
parser.add_argument(
|
| 59 |
-
"--encoder-embed-dim",
|
| 60 |
-
type=int,
|
| 61 |
-
metavar="H",
|
| 62 |
-
help="encoder embedding dimension",
|
| 63 |
-
)
|
| 64 |
-
parser.add_argument(
|
| 65 |
-
"--encoder-ffn-embed-dim",
|
| 66 |
-
type=int,
|
| 67 |
-
metavar="F",
|
| 68 |
-
help="encoder embedding dimension for FFN",
|
| 69 |
-
)
|
| 70 |
-
parser.add_argument(
|
| 71 |
-
"--encoder-attention-heads",
|
| 72 |
-
type=int,
|
| 73 |
-
metavar="A",
|
| 74 |
-
help="num encoder attention heads",
|
| 75 |
-
)
|
| 76 |
-
parser.add_argument(
|
| 77 |
-
"--activation-fn",
|
| 78 |
-
choices=utils.get_available_activation_fns(),
|
| 79 |
-
help="activation function to use",
|
| 80 |
-
)
|
| 81 |
-
parser.add_argument(
|
| 82 |
-
"--pooler-activation-fn",
|
| 83 |
-
choices=utils.get_available_activation_fns(),
|
| 84 |
-
help="activation function to use for pooler layer",
|
| 85 |
-
)
|
| 86 |
-
parser.add_argument(
|
| 87 |
-
"--encoder-normalize-before",
|
| 88 |
-
action="store_true",
|
| 89 |
-
help="apply layernorm before each encoder block",
|
| 90 |
-
)
|
| 91 |
-
parser.add_argument(
|
| 92 |
-
"--layernorm-embedding",
|
| 93 |
-
action="store_true",
|
| 94 |
-
help="add layernorm to embedding",
|
| 95 |
-
)
|
| 96 |
-
parser.add_argument(
|
| 97 |
-
"--dropout", type=float, metavar="D", help="dropout probability"
|
| 98 |
-
)
|
| 99 |
-
parser.add_argument(
|
| 100 |
-
"--attention-dropout",
|
| 101 |
-
type=float,
|
| 102 |
-
metavar="D",
|
| 103 |
-
help="dropout probability for attention weights",
|
| 104 |
-
)
|
| 105 |
-
parser.add_argument(
|
| 106 |
-
"--activation-dropout",
|
| 107 |
-
type=float,
|
| 108 |
-
metavar="D",
|
| 109 |
-
help="dropout probability after activation in FFN",
|
| 110 |
-
)
|
| 111 |
-
parser.add_argument(
|
| 112 |
-
"--pooler-dropout",
|
| 113 |
-
type=float,
|
| 114 |
-
metavar="D",
|
| 115 |
-
help="dropout probability in the masked_lm pooler layers",
|
| 116 |
-
)
|
| 117 |
-
parser.add_argument(
|
| 118 |
-
"--max-positions", type=int, help="number of positional embeddings to learn"
|
| 119 |
-
)
|
| 120 |
-
parser.add_argument(
|
| 121 |
-
"--load-checkpoint-heads",
|
| 122 |
-
action="store_true",
|
| 123 |
-
help="(re-)register and load heads when loading checkpoints",
|
| 124 |
-
)
|
| 125 |
-
parser.add_argument(
|
| 126 |
-
"--untie-weights-roberta",
|
| 127 |
-
action="store_true",
|
| 128 |
-
help="Untie weights between embeddings and classifiers in RoBERTa",
|
| 129 |
-
)
|
| 130 |
-
# args for "Reducing Transformer Depth on Demand with Structured Dropout" (Fan et al., 2019)
|
| 131 |
-
parser.add_argument(
|
| 132 |
-
"--encoder-layerdrop",
|
| 133 |
-
type=float,
|
| 134 |
-
metavar="D",
|
| 135 |
-
default=0,
|
| 136 |
-
help="LayerDrop probability for encoder",
|
| 137 |
-
)
|
| 138 |
-
parser.add_argument(
|
| 139 |
-
"--encoder-layers-to-keep",
|
| 140 |
-
default=None,
|
| 141 |
-
help="which layers to *keep* when pruning as a comma-separated list",
|
| 142 |
-
)
|
| 143 |
-
# args for Training with Quantization Noise for Extreme Model Compression ({Fan*, Stock*} et al., 2020)
|
| 144 |
-
parser.add_argument(
|
| 145 |
-
"--quant-noise-pq",
|
| 146 |
-
type=float,
|
| 147 |
-
metavar="D",
|
| 148 |
-
default=0,
|
| 149 |
-
help="iterative PQ quantization noise at training time",
|
| 150 |
-
)
|
| 151 |
-
parser.add_argument(
|
| 152 |
-
"--quant-noise-pq-block-size",
|
| 153 |
-
type=int,
|
| 154 |
-
metavar="D",
|
| 155 |
-
default=8,
|
| 156 |
-
help="block size of quantization noise at training time",
|
| 157 |
-
)
|
| 158 |
-
parser.add_argument(
|
| 159 |
-
"--quant-noise-scalar",
|
| 160 |
-
type=float,
|
| 161 |
-
metavar="D",
|
| 162 |
-
default=0,
|
| 163 |
-
help="scalar quantization noise and scalar quantization at training time",
|
| 164 |
-
)
|
| 165 |
-
# args for "Better Fine-Tuning by Reducing Representational Collapse" (Aghajanyan et al. 2020)
|
| 166 |
-
parser.add_argument(
|
| 167 |
-
"--spectral-norm-classification-head",
|
| 168 |
-
action="store_true",
|
| 169 |
-
default=False,
|
| 170 |
-
help="Apply spectral normalization on the classification head",
|
| 171 |
-
)
|
| 172 |
-
# args for Fully Sharded Data Parallel (FSDP) training
|
| 173 |
-
parser.add_argument(
|
| 174 |
-
"--min-params-to-wrap",
|
| 175 |
-
type=int,
|
| 176 |
-
metavar="D",
|
| 177 |
-
default=DEFAULT_MIN_PARAMS_TO_WRAP,
|
| 178 |
-
help=(
|
| 179 |
-
"minimum number of params for a layer to be wrapped with FSDP() when "
|
| 180 |
-
"training with --ddp-backend=fully_sharded. Smaller values will "
|
| 181 |
-
"improve memory efficiency, but may make torch.distributed "
|
| 182 |
-
"communication less efficient due to smaller input sizes. This option "
|
| 183 |
-
"is set to 0 (i.e., always wrap) when --checkpoint-activations or "
|
| 184 |
-
"--offload-activations are passed."
|
| 185 |
-
),
|
| 186 |
-
)
|
| 187 |
-
# args for AdaPruning
|
| 188 |
-
# In short, it adds regularizarion for the multihead attention module and feed forward neural nets
|
| 189 |
-
# For more details, please refer to the paper https://openreview.net/forum?id=_CMSV7FTzGI
|
| 190 |
-
parser.add_argument(
|
| 191 |
-
"--mha-reg-scale-factor",
|
| 192 |
-
type=float,
|
| 193 |
-
metavar="D",
|
| 194 |
-
default=0.0,
|
| 195 |
-
help="scaling factor for regularization term in adptive pruning, recommendation is 0.000375",
|
| 196 |
-
)
|
| 197 |
-
parser.add_argument(
|
| 198 |
-
"--ffn-reg-scale-factor",
|
| 199 |
-
type=float,
|
| 200 |
-
metavar="D",
|
| 201 |
-
default=0.0,
|
| 202 |
-
help="scaling factor for regularization term in adptive pruning, recommendation is 0.000375",
|
| 203 |
-
)
|
| 204 |
-
parser.add_argument(
|
| 205 |
-
"--mha-heads-to-keep",
|
| 206 |
-
type=int,
|
| 207 |
-
metavar="D",
|
| 208 |
-
default=-1,
|
| 209 |
-
help="number of heads to keep in each multi-head attention module, -1 means keeping all heads",
|
| 210 |
-
)
|
| 211 |
-
parser.add_argument(
|
| 212 |
-
"--ffn-blocks-to-remove",
|
| 213 |
-
type=int,
|
| 214 |
-
metavar="D",
|
| 215 |
-
default=-1,
|
| 216 |
-
help="number of feedforward blocks to remove in each transformer layer, -1 means keeping all ffn blocks",
|
| 217 |
-
)
|
| 218 |
-
|
| 219 |
-
@classmethod
|
| 220 |
-
def build_model(cls, args, task):
|
| 221 |
-
"""Build a new model instance."""
|
| 222 |
-
|
| 223 |
-
from omegaconf import OmegaConf
|
| 224 |
-
|
| 225 |
-
if OmegaConf.is_config(args):
|
| 226 |
-
OmegaConf.set_struct(args, False)
|
| 227 |
-
|
| 228 |
-
# make sure all arguments are present
|
| 229 |
-
base_architecture(args)
|
| 230 |
-
|
| 231 |
-
if not safe_hasattr(args, "max_positions"):
|
| 232 |
-
if not safe_hasattr(args, "tokens_per_sample"):
|
| 233 |
-
args.tokens_per_sample = task.max_positions()
|
| 234 |
-
args.max_positions = args.tokens_per_sample
|
| 235 |
-
|
| 236 |
-
encoder = RobertaEncoder(args, task.source_dictionary)
|
| 237 |
-
|
| 238 |
-
if OmegaConf.is_config(args):
|
| 239 |
-
OmegaConf.set_struct(args, True)
|
| 240 |
-
|
| 241 |
-
return cls(args, encoder)
|
| 242 |
-
|
| 243 |
-
def forward(
|
| 244 |
-
self,
|
| 245 |
-
src_tokens,
|
| 246 |
-
features_only=False,
|
| 247 |
-
return_all_hiddens=False,
|
| 248 |
-
classification_head_name=None,
|
| 249 |
-
**kwargs,
|
| 250 |
-
):
|
| 251 |
-
if classification_head_name is not None:
|
| 252 |
-
features_only = True
|
| 253 |
-
|
| 254 |
-
x, extra = self.encoder(src_tokens, features_only, return_all_hiddens, **kwargs)
|
| 255 |
-
|
| 256 |
-
if classification_head_name is not None:
|
| 257 |
-
x = self.classification_heads[classification_head_name](x)
|
| 258 |
-
return x, extra
|
| 259 |
-
|
| 260 |
-
def _get_adaptive_head_loss(self):
|
| 261 |
-
norm_loss = 0
|
| 262 |
-
scaling = float(self.args.mha_reg_scale_factor)
|
| 263 |
-
for layer in self.encoder.sentence_encoder.layers:
|
| 264 |
-
norm_loss_layer = 0
|
| 265 |
-
for i in range(layer.self_attn.num_heads):
|
| 266 |
-
start_idx = i * layer.self_attn.head_dim
|
| 267 |
-
end_idx = (i + 1) * layer.self_attn.head_dim
|
| 268 |
-
norm_loss_layer += scaling * (
|
| 269 |
-
torch.sum(
|
| 270 |
-
torch.abs(
|
| 271 |
-
layer.self_attn.q_proj.weight[
|
| 272 |
-
start_idx:end_idx,
|
| 273 |
-
]
|
| 274 |
-
)
|
| 275 |
-
)
|
| 276 |
-
+ torch.sum(
|
| 277 |
-
torch.abs(layer.self_attn.q_proj.bias[start_idx:end_idx])
|
| 278 |
-
)
|
| 279 |
-
)
|
| 280 |
-
norm_loss_layer += scaling * (
|
| 281 |
-
torch.sum(
|
| 282 |
-
torch.abs(
|
| 283 |
-
layer.self_attn.k_proj.weight[
|
| 284 |
-
start_idx:end_idx,
|
| 285 |
-
]
|
| 286 |
-
)
|
| 287 |
-
)
|
| 288 |
-
+ torch.sum(
|
| 289 |
-
torch.abs(layer.self_attn.k_proj.bias[start_idx:end_idx])
|
| 290 |
-
)
|
| 291 |
-
)
|
| 292 |
-
norm_loss_layer += scaling * (
|
| 293 |
-
torch.sum(
|
| 294 |
-
torch.abs(
|
| 295 |
-
layer.self_attn.v_proj.weight[
|
| 296 |
-
start_idx:end_idx,
|
| 297 |
-
]
|
| 298 |
-
)
|
| 299 |
-
)
|
| 300 |
-
+ torch.sum(
|
| 301 |
-
torch.abs(layer.self_attn.v_proj.bias[start_idx:end_idx])
|
| 302 |
-
)
|
| 303 |
-
)
|
| 304 |
-
|
| 305 |
-
norm_loss += norm_loss_layer
|
| 306 |
-
return norm_loss
|
| 307 |
-
|
| 308 |
-
def _get_adaptive_ffn_loss(self):
|
| 309 |
-
ffn_scale_factor = float(self.args.ffn_reg_scale_factor)
|
| 310 |
-
filter_loss = 0
|
| 311 |
-
for layer in self.encoder.sentence_encoder.layers:
|
| 312 |
-
filter_loss += torch.sum(
|
| 313 |
-
torch.abs(layer.fc1.weight * ffn_scale_factor)
|
| 314 |
-
) + torch.sum(torch.abs(layer.fc2.weight * ffn_scale_factor))
|
| 315 |
-
filter_loss += torch.sum(
|
| 316 |
-
torch.abs(layer.fc1.bias * ffn_scale_factor)
|
| 317 |
-
) + torch.sum(torch.abs(layer.fc2.bias * ffn_scale_factor))
|
| 318 |
-
return filter_loss
|
| 319 |
-
|
| 320 |
-
def get_normalized_probs(self, net_output, log_probs, sample=None):
|
| 321 |
-
"""Get normalized probabilities (or log probs) from a net's output."""
|
| 322 |
-
logits = net_output[0].float()
|
| 323 |
-
if log_probs:
|
| 324 |
-
return F.log_softmax(logits, dim=-1)
|
| 325 |
-
else:
|
| 326 |
-
return F.softmax(logits, dim=-1)
|
| 327 |
-
|
| 328 |
-
def register_classification_head(
|
| 329 |
-
self, name, num_classes=None, inner_dim=None, **kwargs
|
| 330 |
-
):
|
| 331 |
-
"""Register a classification head."""
|
| 332 |
-
if name in self.classification_heads:
|
| 333 |
-
prev_num_classes = self.classification_heads[name].out_proj.out_features
|
| 334 |
-
prev_inner_dim = self.classification_heads[name].dense.out_features
|
| 335 |
-
if num_classes != prev_num_classes or inner_dim != prev_inner_dim:
|
| 336 |
-
logger.warning(
|
| 337 |
-
're-registering head "{}" with num_classes {} (prev: {}) '
|
| 338 |
-
"and inner_dim {} (prev: {})".format(
|
| 339 |
-
name, num_classes, prev_num_classes, inner_dim, prev_inner_dim
|
| 340 |
-
)
|
| 341 |
-
)
|
| 342 |
-
self.classification_heads[name] = RobertaClassificationHead(
|
| 343 |
-
input_dim=self.args.encoder_embed_dim,
|
| 344 |
-
inner_dim=inner_dim or self.args.encoder_embed_dim,
|
| 345 |
-
num_classes=num_classes,
|
| 346 |
-
activation_fn=self.args.pooler_activation_fn,
|
| 347 |
-
pooler_dropout=self.args.pooler_dropout,
|
| 348 |
-
q_noise=self.args.quant_noise_pq,
|
| 349 |
-
qn_block_size=self.args.quant_noise_pq_block_size,
|
| 350 |
-
do_spectral_norm=self.args.spectral_norm_classification_head,
|
| 351 |
-
)
|
| 352 |
-
|
| 353 |
-
@property
|
| 354 |
-
def supported_targets(self):
|
| 355 |
-
return {"self"}
|
| 356 |
-
|
| 357 |
-
@classmethod
|
| 358 |
-
def from_pretrained(
|
| 359 |
-
cls,
|
| 360 |
-
model_name_or_path,
|
| 361 |
-
checkpoint_file="model.pt",
|
| 362 |
-
data_name_or_path=".",
|
| 363 |
-
bpe="gpt2",
|
| 364 |
-
**kwargs,
|
| 365 |
-
):
|
| 366 |
-
from fairseq import hub_utils
|
| 367 |
-
|
| 368 |
-
x = hub_utils.from_pretrained(
|
| 369 |
-
model_name_or_path,
|
| 370 |
-
checkpoint_file,
|
| 371 |
-
data_name_or_path,
|
| 372 |
-
archive_map=cls.hub_models(),
|
| 373 |
-
bpe=bpe,
|
| 374 |
-
load_checkpoint_heads=True,
|
| 375 |
-
**kwargs,
|
| 376 |
-
)
|
| 377 |
-
|
| 378 |
-
logger.info(x["args"])
|
| 379 |
-
return RobertaHubInterface(x["args"], x["task"], x["models"][0])
|
| 380 |
-
|
| 381 |
-
def upgrade_state_dict_named(self, state_dict, name):
|
| 382 |
-
prefix = name + "." if name != "" else ""
|
| 383 |
-
|
| 384 |
-
# rename decoder -> encoder before upgrading children modules
|
| 385 |
-
for k in list(state_dict.keys()):
|
| 386 |
-
if k.startswith(prefix + "decoder"):
|
| 387 |
-
new_k = prefix + "encoder" + k[len(prefix + "decoder") :]
|
| 388 |
-
state_dict[new_k] = state_dict[k]
|
| 389 |
-
del state_dict[k]
|
| 390 |
-
|
| 391 |
-
# rename emb_layer_norm -> layernorm_embedding
|
| 392 |
-
for k in list(state_dict.keys()):
|
| 393 |
-
if ".emb_layer_norm." in k:
|
| 394 |
-
new_k = k.replace(".emb_layer_norm.", ".layernorm_embedding.")
|
| 395 |
-
state_dict[new_k] = state_dict[k]
|
| 396 |
-
del state_dict[k]
|
| 397 |
-
|
| 398 |
-
# upgrade children modules
|
| 399 |
-
super().upgrade_state_dict_named(state_dict, name)
|
| 400 |
-
|
| 401 |
-
# Handle new classification heads present in the state dict.
|
| 402 |
-
current_head_names = (
|
| 403 |
-
[]
|
| 404 |
-
if not hasattr(self, "classification_heads")
|
| 405 |
-
else self.classification_heads.keys()
|
| 406 |
-
)
|
| 407 |
-
keys_to_delete = []
|
| 408 |
-
for k in state_dict.keys():
|
| 409 |
-
if not k.startswith(prefix + "classification_heads."):
|
| 410 |
-
continue
|
| 411 |
-
|
| 412 |
-
head_name = k[len(prefix + "classification_heads.") :].split(".")[0]
|
| 413 |
-
num_classes = state_dict[
|
| 414 |
-
prefix + "classification_heads." + head_name + ".out_proj.weight"
|
| 415 |
-
].size(0)
|
| 416 |
-
inner_dim = state_dict[
|
| 417 |
-
prefix + "classification_heads." + head_name + ".dense.weight"
|
| 418 |
-
].size(0)
|
| 419 |
-
|
| 420 |
-
if getattr(self.args, "load_checkpoint_heads", False):
|
| 421 |
-
if head_name not in current_head_names:
|
| 422 |
-
self.register_classification_head(head_name, num_classes, inner_dim)
|
| 423 |
-
else:
|
| 424 |
-
if head_name not in current_head_names:
|
| 425 |
-
logger.warning(
|
| 426 |
-
"deleting classification head ({}) from checkpoint "
|
| 427 |
-
"not present in current model: {}".format(head_name, k)
|
| 428 |
-
)
|
| 429 |
-
keys_to_delete.append(k)
|
| 430 |
-
elif (
|
| 431 |
-
num_classes
|
| 432 |
-
!= self.classification_heads[head_name].out_proj.out_features
|
| 433 |
-
or inner_dim
|
| 434 |
-
!= self.classification_heads[head_name].dense.out_features
|
| 435 |
-
):
|
| 436 |
-
logger.warning(
|
| 437 |
-
"deleting classification head ({}) from checkpoint "
|
| 438 |
-
"with different dimensions than current model: {}".format(
|
| 439 |
-
head_name, k
|
| 440 |
-
)
|
| 441 |
-
)
|
| 442 |
-
keys_to_delete.append(k)
|
| 443 |
-
for k in keys_to_delete:
|
| 444 |
-
del state_dict[k]
|
| 445 |
-
|
| 446 |
-
# Copy any newly-added classification heads into the state dict
|
| 447 |
-
# with their current weights.
|
| 448 |
-
if hasattr(self, "classification_heads"):
|
| 449 |
-
cur_state = self.classification_heads.state_dict()
|
| 450 |
-
for k, v in cur_state.items():
|
| 451 |
-
if prefix + "classification_heads." + k not in state_dict:
|
| 452 |
-
logger.info("Overwriting " + prefix + "classification_heads." + k)
|
| 453 |
-
state_dict[prefix + "classification_heads." + k] = v
|
| 454 |
-
|
| 455 |
-
# adapt data2vec models
|
| 456 |
-
if (
|
| 457 |
-
"encoder._ema" in state_dict
|
| 458 |
-
and "encoder.lm_head.weight" not in state_dict
|
| 459 |
-
):
|
| 460 |
-
lm_state = self.encoder.lm_head.state_dict()
|
| 461 |
-
for k, v in lm_state.items():
|
| 462 |
-
state_dict["encoder.lm_head." + k] = v
|
| 463 |
-
|
| 464 |
-
for k in list(state_dict.keys()):
|
| 465 |
-
if k.startswith("encoder.regression_head") or k == "encoder._ema":
|
| 466 |
-
del state_dict[k]
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
class RobertaLMHead(nn.Module):
|
| 470 |
-
"""Head for masked language modeling."""
|
| 471 |
-
|
| 472 |
-
def __init__(self, embed_dim, output_dim, activation_fn, weight=None):
|
| 473 |
-
super().__init__()
|
| 474 |
-
self.dense = nn.Linear(embed_dim, embed_dim)
|
| 475 |
-
self.activation_fn = utils.get_activation_fn(activation_fn)
|
| 476 |
-
self.layer_norm = LayerNorm(embed_dim)
|
| 477 |
-
|
| 478 |
-
if weight is None:
|
| 479 |
-
weight = nn.Linear(embed_dim, output_dim, bias=False).weight
|
| 480 |
-
self.weight = weight
|
| 481 |
-
self.bias = nn.Parameter(torch.zeros(output_dim))
|
| 482 |
-
|
| 483 |
-
def forward(self, features, masked_tokens=None, **kwargs):
|
| 484 |
-
# Only project the masked tokens while training,
|
| 485 |
-
# saves both memory and computation
|
| 486 |
-
if masked_tokens is not None:
|
| 487 |
-
features = features[masked_tokens, :]
|
| 488 |
-
|
| 489 |
-
x = self.dense(features)
|
| 490 |
-
x = self.activation_fn(x)
|
| 491 |
-
x = self.layer_norm(x)
|
| 492 |
-
# project back to size of vocabulary with bias
|
| 493 |
-
x = F.linear(x, self.weight) + self.bias
|
| 494 |
-
return x
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
class RobertaClassificationHead(nn.Module):
|
| 498 |
-
"""Head for sentence-level classification tasks."""
|
| 499 |
-
|
| 500 |
-
def __init__(
|
| 501 |
-
self,
|
| 502 |
-
input_dim,
|
| 503 |
-
inner_dim,
|
| 504 |
-
num_classes,
|
| 505 |
-
activation_fn,
|
| 506 |
-
pooler_dropout,
|
| 507 |
-
q_noise=0,
|
| 508 |
-
qn_block_size=8,
|
| 509 |
-
do_spectral_norm=False,
|
| 510 |
-
):
|
| 511 |
-
super().__init__()
|
| 512 |
-
self.dense = nn.Linear(input_dim, inner_dim)
|
| 513 |
-
self.activation_fn = utils.get_activation_fn(activation_fn)
|
| 514 |
-
self.dropout = nn.Dropout(p=pooler_dropout)
|
| 515 |
-
self.out_proj = apply_quant_noise_(
|
| 516 |
-
nn.Linear(inner_dim, num_classes), q_noise, qn_block_size
|
| 517 |
-
)
|
| 518 |
-
if do_spectral_norm:
|
| 519 |
-
if q_noise != 0:
|
| 520 |
-
raise NotImplementedError(
|
| 521 |
-
"Attempting to use Spectral Normalization with Quant Noise. This is not officially supported"
|
| 522 |
-
)
|
| 523 |
-
self.out_proj = torch.nn.utils.spectral_norm(self.out_proj)
|
| 524 |
-
|
| 525 |
-
def forward(self, features, **kwargs):
|
| 526 |
-
x = features[:, 0, :] # take <s> token (equiv. to [CLS])
|
| 527 |
-
x = self.dropout(x)
|
| 528 |
-
x = self.dense(x)
|
| 529 |
-
x = self.activation_fn(x)
|
| 530 |
-
x = self.dropout(x)
|
| 531 |
-
x = self.out_proj(x)
|
| 532 |
-
return x
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
class RobertaEncoder(FairseqEncoder):
|
| 536 |
-
"""RoBERTa encoder."""
|
| 537 |
-
|
| 538 |
-
def __init__(self, args, dictionary):
|
| 539 |
-
super().__init__(dictionary)
|
| 540 |
-
|
| 541 |
-
# set any missing default values
|
| 542 |
-
base_architecture(args)
|
| 543 |
-
self.args = args
|
| 544 |
-
|
| 545 |
-
if args.encoder_layers_to_keep:
|
| 546 |
-
args.encoder_layers = len(args.encoder_layers_to_keep.split(","))
|
| 547 |
-
|
| 548 |
-
embed_tokens = self.build_embedding(
|
| 549 |
-
len(dictionary), args.encoder_embed_dim, dictionary.pad()
|
| 550 |
-
)
|
| 551 |
-
|
| 552 |
-
self.sentence_encoder = self.build_encoder(args, dictionary, embed_tokens)
|
| 553 |
-
|
| 554 |
-
self.lm_head = self.build_lm_head(
|
| 555 |
-
embed_dim=args.encoder_embed_dim,
|
| 556 |
-
output_dim=len(dictionary),
|
| 557 |
-
activation_fn=args.activation_fn,
|
| 558 |
-
weight=(
|
| 559 |
-
self.sentence_encoder.embed_tokens.weight
|
| 560 |
-
if not args.untie_weights_roberta
|
| 561 |
-
else None
|
| 562 |
-
),
|
| 563 |
-
)
|
| 564 |
-
|
| 565 |
-
def build_embedding(self, vocab_size, embedding_dim, padding_idx):
|
| 566 |
-
return nn.Embedding(vocab_size, embedding_dim, padding_idx)
|
| 567 |
-
|
| 568 |
-
def build_encoder(self, args, dictionary, embed_tokens):
|
| 569 |
-
encoder = TransformerEncoder(args, dictionary, embed_tokens)
|
| 570 |
-
encoder.apply(init_bert_params)
|
| 571 |
-
return encoder
|
| 572 |
-
|
| 573 |
-
def build_lm_head(self, embed_dim, output_dim, activation_fn, weight):
|
| 574 |
-
return RobertaLMHead(embed_dim, output_dim, activation_fn, weight)
|
| 575 |
-
|
| 576 |
-
def forward(
|
| 577 |
-
self,
|
| 578 |
-
src_tokens,
|
| 579 |
-
features_only=False,
|
| 580 |
-
return_all_hiddens=False,
|
| 581 |
-
masked_tokens=None,
|
| 582 |
-
**unused,
|
| 583 |
-
):
|
| 584 |
-
"""
|
| 585 |
-
Args:
|
| 586 |
-
src_tokens (LongTensor): input tokens of shape `(batch, src_len)`
|
| 587 |
-
features_only (bool, optional): skip LM head and just return
|
| 588 |
-
features. If True, the output will be of shape
|
| 589 |
-
`(batch, src_len, embed_dim)`.
|
| 590 |
-
return_all_hiddens (bool, optional): also return all of the
|
| 591 |
-
intermediate hidden states (default: False).
|
| 592 |
-
|
| 593 |
-
Returns:
|
| 594 |
-
tuple:
|
| 595 |
-
- the LM output of shape `(batch, src_len, vocab)`
|
| 596 |
-
- a dictionary of additional data, where 'inner_states'
|
| 597 |
-
is a list of hidden states. Note that the hidden
|
| 598 |
-
states have shape `(src_len, batch, vocab)`.
|
| 599 |
-
"""
|
| 600 |
-
x, extra = self.extract_features(
|
| 601 |
-
src_tokens, return_all_hiddens=return_all_hiddens
|
| 602 |
-
)
|
| 603 |
-
if not features_only:
|
| 604 |
-
x = self.output_layer(x, masked_tokens=masked_tokens)
|
| 605 |
-
return x, extra
|
| 606 |
-
|
| 607 |
-
def extract_features(self, src_tokens, return_all_hiddens=False, **kwargs):
|
| 608 |
-
encoder_out = self.sentence_encoder(
|
| 609 |
-
src_tokens,
|
| 610 |
-
return_all_hiddens=return_all_hiddens,
|
| 611 |
-
token_embeddings=kwargs.get("token_embeddings", None),
|
| 612 |
-
)
|
| 613 |
-
# T x B x C -> B x T x C
|
| 614 |
-
features = encoder_out["encoder_out"][0].transpose(0, 1)
|
| 615 |
-
inner_states = encoder_out["encoder_states"] if return_all_hiddens else None
|
| 616 |
-
return features, {"inner_states": inner_states}
|
| 617 |
-
|
| 618 |
-
def output_layer(self, features, masked_tokens=None, **unused):
|
| 619 |
-
return self.lm_head(features, masked_tokens)
|
| 620 |
-
|
| 621 |
-
def max_positions(self):
|
| 622 |
-
"""Maximum output length supported by the encoder."""
|
| 623 |
-
return self.args.max_positions
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
@register_model_architecture("roberta", "roberta")
|
| 627 |
-
def base_architecture(args):
|
| 628 |
-
args.encoder_layers = safe_getattr(args, "encoder_layers", 12)
|
| 629 |
-
args.encoder_embed_dim = safe_getattr(args, "encoder_embed_dim", 768)
|
| 630 |
-
args.encoder_ffn_embed_dim = safe_getattr(args, "encoder_ffn_embed_dim", 3072)
|
| 631 |
-
args.encoder_attention_heads = safe_getattr(args, "encoder_attention_heads", 12)
|
| 632 |
-
|
| 633 |
-
args.dropout = safe_getattr(args, "dropout", 0.1)
|
| 634 |
-
args.attention_dropout = safe_getattr(args, "attention_dropout", 0.1)
|
| 635 |
-
args.activation_dropout = safe_getattr(args, "activation_dropout", 0.0)
|
| 636 |
-
args.pooler_dropout = safe_getattr(args, "pooler_dropout", 0.0)
|
| 637 |
-
|
| 638 |
-
args.max_source_positions = safe_getattr(args, "max_positions", 512)
|
| 639 |
-
args.no_token_positional_embeddings = safe_getattr(
|
| 640 |
-
args, "no_token_positional_embeddings", False
|
| 641 |
-
)
|
| 642 |
-
|
| 643 |
-
# BERT has a few structural differences compared to the original Transformer
|
| 644 |
-
args.encoder_learned_pos = safe_getattr(args, "encoder_learned_pos", True)
|
| 645 |
-
args.layernorm_embedding = safe_getattr(args, "layernorm_embedding", True)
|
| 646 |
-
args.no_scale_embedding = safe_getattr(args, "no_scale_embedding", True)
|
| 647 |
-
args.activation_fn = safe_getattr(args, "activation_fn", "gelu")
|
| 648 |
-
args.encoder_normalize_before = safe_getattr(
|
| 649 |
-
args, "encoder_normalize_before", False
|
| 650 |
-
)
|
| 651 |
-
args.pooler_activation_fn = safe_getattr(args, "pooler_activation_fn", "tanh")
|
| 652 |
-
args.untie_weights_roberta = safe_getattr(args, "untie_weights_roberta", False)
|
| 653 |
-
|
| 654 |
-
# Adaptive input config
|
| 655 |
-
args.adaptive_input = safe_getattr(args, "adaptive_input", False)
|
| 656 |
-
|
| 657 |
-
# LayerDrop config
|
| 658 |
-
args.encoder_layerdrop = safe_getattr(args, "encoder_layerdrop", 0.0)
|
| 659 |
-
args.encoder_layers_to_keep = safe_getattr(args, "encoder_layers_to_keep", None)
|
| 660 |
-
|
| 661 |
-
# Quantization noise config
|
| 662 |
-
args.quant_noise_pq = safe_getattr(args, "quant_noise_pq", 0)
|
| 663 |
-
args.quant_noise_pq_block_size = safe_getattr(args, "quant_noise_pq_block_size", 8)
|
| 664 |
-
args.quant_noise_scalar = safe_getattr(args, "quant_noise_scalar", 0)
|
| 665 |
-
|
| 666 |
-
# R4F config
|
| 667 |
-
args.spectral_norm_classification_head = safe_getattr(
|
| 668 |
-
args, "spectral_norm_classification_head", False
|
| 669 |
-
)
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
@register_model_architecture("roberta", "roberta_prenorm")
|
| 673 |
-
def roberta_prenorm_architecture(args):
|
| 674 |
-
args.layernorm_embedding = safe_getattr(args, "layernorm_embedding", False)
|
| 675 |
-
args.encoder_normalize_before = safe_getattr(args, "encoder_normalize_before", True)
|
| 676 |
-
base_architecture(args)
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
@register_model_architecture("roberta", "roberta_base")
|
| 680 |
-
def roberta_base_architecture(args):
|
| 681 |
-
base_architecture(args)
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
@register_model_architecture("roberta", "roberta_large")
|
| 685 |
-
def roberta_large_architecture(args):
|
| 686 |
-
args.encoder_layers = safe_getattr(args, "encoder_layers", 24)
|
| 687 |
-
args.encoder_embed_dim = safe_getattr(args, "encoder_embed_dim", 1024)
|
| 688 |
-
args.encoder_ffn_embed_dim = safe_getattr(args, "encoder_ffn_embed_dim", 4096)
|
| 689 |
-
args.encoder_attention_heads = safe_getattr(args, "encoder_attention_heads", 16)
|
| 690 |
-
base_architecture(args)
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
@register_model_architecture("roberta", "xlm")
|
| 694 |
-
def xlm_architecture(args):
|
| 695 |
-
args.encoder_layers = safe_getattr(args, "encoder_layers", 16)
|
| 696 |
-
args.encoder_embed_dim = safe_getattr(args, "encoder_embed_dim", 1280)
|
| 697 |
-
args.encoder_ffn_embed_dim = safe_getattr(args, "encoder_ffn_embed_dim", 1280 * 4)
|
| 698 |
-
args.encoder_attention_heads = safe_getattr(args, "encoder_attention_heads", 16)
|
| 699 |
-
base_architecture(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/model_camembert.py
DELETED
|
@@ -1,50 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
"""
|
| 6 |
-
CamemBERT: a Tasty French Language Model
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
from fairseq.models import register_model
|
| 10 |
-
|
| 11 |
-
from .hub_interface import RobertaHubInterface
|
| 12 |
-
from .model import RobertaModel
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
@register_model("camembert")
|
| 16 |
-
class CamembertModel(RobertaModel):
|
| 17 |
-
@classmethod
|
| 18 |
-
def hub_models(cls):
|
| 19 |
-
return {
|
| 20 |
-
"camembert": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-base.tar.gz",
|
| 21 |
-
"camembert.v0": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-base.tar.gz",
|
| 22 |
-
"camembert-base": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-base.tar.gz",
|
| 23 |
-
"camembert-large": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-large.tar.gz",
|
| 24 |
-
"camembert-base-ccnet": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-base-ccnet.tar.gz",
|
| 25 |
-
"camembert-base-ccnet-4gb": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-base-ccnet-4gb.tar.gz",
|
| 26 |
-
"camembert-base-wikipedia-4gb": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-base-wikipedia-4gb.tar.gz",
|
| 27 |
-
"camembert-base-oscar-4gb": "http://dl.fbaipublicfiles.com/fairseq/models/camembert-base-oscar-4gb.tar.gz",
|
| 28 |
-
}
|
| 29 |
-
|
| 30 |
-
@classmethod
|
| 31 |
-
def from_pretrained(
|
| 32 |
-
cls,
|
| 33 |
-
model_name_or_path,
|
| 34 |
-
checkpoint_file="model.pt",
|
| 35 |
-
data_name_or_path=".",
|
| 36 |
-
bpe="sentencepiece",
|
| 37 |
-
**kwargs
|
| 38 |
-
):
|
| 39 |
-
from fairseq import hub_utils
|
| 40 |
-
|
| 41 |
-
x = hub_utils.from_pretrained(
|
| 42 |
-
model_name_or_path,
|
| 43 |
-
checkpoint_file,
|
| 44 |
-
data_name_or_path,
|
| 45 |
-
archive_map=cls.hub_models(),
|
| 46 |
-
bpe=bpe,
|
| 47 |
-
load_checkpoint_heads=True,
|
| 48 |
-
**kwargs,
|
| 49 |
-
)
|
| 50 |
-
return RobertaHubInterface(x["args"], x["task"], x["models"][0])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/model_gottbert.py
DELETED
|
@@ -1,49 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
"""
|
| 6 |
-
GottBERT: a pure German Language Model
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
from fairseq.models import register_model
|
| 10 |
-
|
| 11 |
-
from .hub_interface import RobertaHubInterface
|
| 12 |
-
from .model import RobertaModel
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
@register_model("gottbert")
|
| 16 |
-
class GottbertModel(RobertaModel):
|
| 17 |
-
@classmethod
|
| 18 |
-
def hub_models(cls):
|
| 19 |
-
return {
|
| 20 |
-
"gottbert-base": "https://dl.gottbert.de/fairseq/models/gottbert-base.tar.gz",
|
| 21 |
-
}
|
| 22 |
-
|
| 23 |
-
@classmethod
|
| 24 |
-
def from_pretrained(
|
| 25 |
-
cls,
|
| 26 |
-
model_name_or_path,
|
| 27 |
-
checkpoint_file="model.pt",
|
| 28 |
-
data_name_or_path=".",
|
| 29 |
-
bpe="hf_byte_bpe",
|
| 30 |
-
bpe_vocab="vocab.json",
|
| 31 |
-
bpe_merges="merges.txt",
|
| 32 |
-
bpe_add_prefix_space=False,
|
| 33 |
-
**kwargs
|
| 34 |
-
):
|
| 35 |
-
from fairseq import hub_utils
|
| 36 |
-
|
| 37 |
-
x = hub_utils.from_pretrained(
|
| 38 |
-
model_name_or_path,
|
| 39 |
-
checkpoint_file,
|
| 40 |
-
data_name_or_path,
|
| 41 |
-
archive_map=cls.hub_models(),
|
| 42 |
-
bpe=bpe,
|
| 43 |
-
load_checkpoint_heads=True,
|
| 44 |
-
bpe_vocab=bpe_vocab,
|
| 45 |
-
bpe_merges=bpe_merges,
|
| 46 |
-
bpe_add_prefix_space=bpe_add_prefix_space,
|
| 47 |
-
**kwargs,
|
| 48 |
-
)
|
| 49 |
-
return RobertaHubInterface(x["args"], x["task"], x["models"][0])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/roberta/model_xlmr.py
DELETED
|
@@ -1,46 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
"""
|
| 6 |
-
Unsupervised Cross-lingual Representation Learning at Scale
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
from fairseq.models import register_model
|
| 10 |
-
|
| 11 |
-
from .hub_interface import RobertaHubInterface
|
| 12 |
-
from .model import RobertaModel
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
@register_model("xlmr")
|
| 16 |
-
class XLMRModel(RobertaModel):
|
| 17 |
-
@classmethod
|
| 18 |
-
def hub_models(cls):
|
| 19 |
-
return {
|
| 20 |
-
"xlmr.base": "http://dl.fbaipublicfiles.com/fairseq/models/xlmr.base.tar.gz",
|
| 21 |
-
"xlmr.large": "http://dl.fbaipublicfiles.com/fairseq/models/xlmr.large.tar.gz",
|
| 22 |
-
"xlmr.xl": "http://dl.fbaipublicfiles.com/fairseq/models/xlmr/xlmr.xl.tar.gz",
|
| 23 |
-
"xlmr.xxl": "http://dl.fbaipublicfiles.com/fairseq/models/xlmr/xlmr.xxl.tar.gz",
|
| 24 |
-
}
|
| 25 |
-
|
| 26 |
-
@classmethod
|
| 27 |
-
def from_pretrained(
|
| 28 |
-
cls,
|
| 29 |
-
model_name_or_path,
|
| 30 |
-
checkpoint_file="model.pt",
|
| 31 |
-
data_name_or_path=".",
|
| 32 |
-
bpe="sentencepiece",
|
| 33 |
-
**kwargs
|
| 34 |
-
):
|
| 35 |
-
from fairseq import hub_utils
|
| 36 |
-
|
| 37 |
-
x = hub_utils.from_pretrained(
|
| 38 |
-
model_name_or_path,
|
| 39 |
-
checkpoint_file,
|
| 40 |
-
data_name_or_path,
|
| 41 |
-
archive_map=cls.hub_models(),
|
| 42 |
-
bpe=bpe,
|
| 43 |
-
load_checkpoint_heads=True,
|
| 44 |
-
**kwargs,
|
| 45 |
-
)
|
| 46 |
-
return RobertaHubInterface(x["args"], x["task"], x["models"][0])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_speech/__init__.py
DELETED
|
@@ -1,8 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
from .modules import * # noqa
|
| 7 |
-
from .s2s_conformer import * # noqa
|
| 8 |
-
from .s2s_transformer import * # noqa
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_speech/modules.py
DELETED
|
@@ -1,58 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import torch
|
| 7 |
-
from fairseq.models import FairseqEncoder
|
| 8 |
-
from fairseq.models.transformer import Linear
|
| 9 |
-
from torch import nn
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
class CTCDecoder(FairseqEncoder):
|
| 13 |
-
def __init__(self, dictionary, in_dim):
|
| 14 |
-
super().__init__(dictionary)
|
| 15 |
-
self.proj = nn.Linear(in_dim, len(dictionary))
|
| 16 |
-
|
| 17 |
-
def forward(self, src_tokens, src_lengths=None, **kwargs):
|
| 18 |
-
encoder_out = self.proj(src_tokens)
|
| 19 |
-
return {"encoder_out": encoder_out}
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
class StackedEmbedding(nn.Embedding):
|
| 23 |
-
"""Embedding module that supports stacked units -> single embedding"""
|
| 24 |
-
|
| 25 |
-
def __init__(self, num_embeddings, embed_dim, padding_idx, num_stacked=1):
|
| 26 |
-
super().__init__(num_embeddings, embed_dim, padding_idx)
|
| 27 |
-
# follow transformer.Embedding
|
| 28 |
-
nn.init.normal_(self.weight, mean=0, std=embed_dim**-0.5)
|
| 29 |
-
nn.init.constant_(self.weight[padding_idx], 0)
|
| 30 |
-
|
| 31 |
-
self.offset = (
|
| 32 |
-
4 # skip <bos>, <pad>, <eos>, <unk>, specific to fairseq dictionary
|
| 33 |
-
)
|
| 34 |
-
self.vocab_size = num_embeddings - self.offset
|
| 35 |
-
self.num_stacked = num_stacked
|
| 36 |
-
|
| 37 |
-
if self.num_stacked > 1:
|
| 38 |
-
self.project_in_dim = Linear(embed_dim * num_stacked, embed_dim, bias=False)
|
| 39 |
-
|
| 40 |
-
def forward(self, input):
|
| 41 |
-
if self.num_stacked == 1:
|
| 42 |
-
return super().forward(input)
|
| 43 |
-
|
| 44 |
-
# expand input indices
|
| 45 |
-
mask = input >= self.offset
|
| 46 |
-
stacked_input = []
|
| 47 |
-
cum_input = input.new_zeros(input.shape)
|
| 48 |
-
for i in range(1, self.num_stacked + 1):
|
| 49 |
-
div = pow(self.vocab_size, i)
|
| 50 |
-
next_input = torch.remainder(input - self.offset - cum_input, div)
|
| 51 |
-
cum_input += next_input
|
| 52 |
-
next_input = torch.floor_divide(next_input, div // self.vocab_size)
|
| 53 |
-
stacked_input.append((next_input + self.offset) * mask + input * ~mask)
|
| 54 |
-
|
| 55 |
-
stacked_input = torch.stack(stacked_input[::-1], dim=2)
|
| 56 |
-
embed = super().forward(stacked_input).view(input.size(0), input.size(1), -1)
|
| 57 |
-
embed = self.project_in_dim(embed)
|
| 58 |
-
return embed
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_speech/s2s_conformer.py
DELETED
|
@@ -1,112 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import logging
|
| 7 |
-
from pathlib import Path
|
| 8 |
-
|
| 9 |
-
import torch
|
| 10 |
-
from fairseq import checkpoint_utils
|
| 11 |
-
from fairseq.data.audio.data_cfg import S2SDataConfig
|
| 12 |
-
from fairseq.models import (
|
| 13 |
-
register_model,
|
| 14 |
-
register_model_architecture,
|
| 15 |
-
)
|
| 16 |
-
from fairseq.models.speech_to_speech import (
|
| 17 |
-
S2UTTransformerModel,
|
| 18 |
-
)
|
| 19 |
-
from fairseq.models.speech_to_speech import (
|
| 20 |
-
s2ut_architecture_base as s2ut_transformer_architecture_base,
|
| 21 |
-
)
|
| 22 |
-
from fairseq.models.speech_to_text import S2TConformerEncoder
|
| 23 |
-
from fairseq.models.transformer import (
|
| 24 |
-
Linear,
|
| 25 |
-
)
|
| 26 |
-
|
| 27 |
-
logger = logging.getLogger(__name__)
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
class S2SConformerEncoder(S2TConformerEncoder):
|
| 31 |
-
"""Based on S2T transformer encoder, with support
|
| 32 |
-
to incorporate target speaker embedding."""
|
| 33 |
-
|
| 34 |
-
def __init__(self, args):
|
| 35 |
-
super().__init__(args)
|
| 36 |
-
|
| 37 |
-
self.spk_emb_proj = None
|
| 38 |
-
if args.target_speaker_embed:
|
| 39 |
-
self.spk_emb_proj = Linear(
|
| 40 |
-
args.encoder_embed_dim + args.speaker_embed_dim, args.encoder_embed_dim
|
| 41 |
-
)
|
| 42 |
-
|
| 43 |
-
def forward(
|
| 44 |
-
self, src_tokens, src_lengths, tgt_speaker=None, return_all_hiddens=False
|
| 45 |
-
):
|
| 46 |
-
out = super().forward(src_tokens, src_lengths, return_all_hiddens)
|
| 47 |
-
|
| 48 |
-
if self.spk_emb_proj:
|
| 49 |
-
x = out["encoder_out"][0]
|
| 50 |
-
seq_len, bsz, _ = x.size()
|
| 51 |
-
tgt_speaker_emb = tgt_speaker.view(1, bsz, -1).expand(seq_len, bsz, -1)
|
| 52 |
-
x = self.spk_emb_proj(torch.cat([x, tgt_speaker_emb], dim=2))
|
| 53 |
-
out["encoder_out"][0] = x
|
| 54 |
-
|
| 55 |
-
return out
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
@register_model("s2ut_conformer")
|
| 59 |
-
class S2UTConformerModel(S2UTTransformerModel):
|
| 60 |
-
"""
|
| 61 |
-
Direct speech-to-speech translation model with S2T Conformer encoder + Transformer discrete unit decoder
|
| 62 |
-
"""
|
| 63 |
-
|
| 64 |
-
@staticmethod
|
| 65 |
-
def add_args(parser):
|
| 66 |
-
S2UTTransformerModel.add_args(parser)
|
| 67 |
-
parser.add_argument("--depthwise-conv-kernel-size", default=31)
|
| 68 |
-
parser.add_argument(
|
| 69 |
-
"--attn-type",
|
| 70 |
-
default=None,
|
| 71 |
-
help="If not specified uses fairseq MHA. Other valid option is espnet for using conformer",
|
| 72 |
-
)
|
| 73 |
-
parser.add_argument(
|
| 74 |
-
"--pos-enc-type",
|
| 75 |
-
default="abs",
|
| 76 |
-
help="Must be specified in addition to attn-type=espnet for rel_pos and rope",
|
| 77 |
-
)
|
| 78 |
-
|
| 79 |
-
@classmethod
|
| 80 |
-
def build_encoder(cls, args):
|
| 81 |
-
print(args)
|
| 82 |
-
data_cfg = S2SDataConfig(Path(args.data) / args.config_yaml)
|
| 83 |
-
args.input_feat_per_channel = data_cfg.input_feat_per_channel
|
| 84 |
-
args.input_channels = data_cfg.input_transformed_channels
|
| 85 |
-
|
| 86 |
-
encoder = S2SConformerEncoder(args)
|
| 87 |
-
pretraining_path = getattr(args, "load_pretrained_encoder_from", None)
|
| 88 |
-
if pretraining_path is not None:
|
| 89 |
-
if not Path(pretraining_path).exists():
|
| 90 |
-
logger.warning(
|
| 91 |
-
f"skipped pretraining because {pretraining_path} does not exist"
|
| 92 |
-
)
|
| 93 |
-
else:
|
| 94 |
-
encoder = checkpoint_utils.load_pretrained_component_from_model(
|
| 95 |
-
component=encoder, checkpoint=pretraining_path
|
| 96 |
-
)
|
| 97 |
-
logger.info(f"loaded pretrained encoder from: {pretraining_path}")
|
| 98 |
-
return encoder
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
@register_model_architecture("s2ut_conformer", "s2ut_conformer")
|
| 102 |
-
def s2ut_base_architecture(args):
|
| 103 |
-
args.attn_type = getattr(args, "attn_type", None)
|
| 104 |
-
args.pos_enc_type = getattr(args, "pos_enc_type", "abs")
|
| 105 |
-
args.max_source_positions = getattr(args, "max_source_positions", 6000)
|
| 106 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 256)
|
| 107 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 2048)
|
| 108 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 4)
|
| 109 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 110 |
-
args.encoder_layers = getattr(args, "encoder_layers", 16)
|
| 111 |
-
args.depthwise_conv_kernel_size = getattr(args, "depthwise_conv_kernel_size", 31)
|
| 112 |
-
s2ut_transformer_architecture_base(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_speech/s2s_transformer.py
DELETED
|
@@ -1,701 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import logging
|
| 7 |
-
from pathlib import Path
|
| 8 |
-
from typing import Any, Dict, List, Optional
|
| 9 |
-
|
| 10 |
-
import torch
|
| 11 |
-
from fairseq import checkpoint_utils, utils
|
| 12 |
-
from fairseq.models import (
|
| 13 |
-
FairseqEncoderDecoderModel,
|
| 14 |
-
FairseqEncoderModel,
|
| 15 |
-
FairseqLanguageModel,
|
| 16 |
-
register_model,
|
| 17 |
-
register_model_architecture,
|
| 18 |
-
)
|
| 19 |
-
from fairseq.models.speech_to_speech.modules import CTCDecoder, StackedEmbedding
|
| 20 |
-
from fairseq.models.speech_to_text import S2TTransformerEncoder
|
| 21 |
-
from fairseq.models.text_to_speech import TTSTransformerDecoder
|
| 22 |
-
from fairseq.models.transformer import (
|
| 23 |
-
Linear,
|
| 24 |
-
TransformerDecoder,
|
| 25 |
-
TransformerModelBase,
|
| 26 |
-
)
|
| 27 |
-
from torch import Tensor
|
| 28 |
-
|
| 29 |
-
logger = logging.getLogger(__name__)
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
class S2STransformerEncoder(S2TTransformerEncoder):
|
| 33 |
-
"""Based on S2T transformer encoder, with support
|
| 34 |
-
to incorporate target speaker embedding."""
|
| 35 |
-
|
| 36 |
-
def __init__(self, args):
|
| 37 |
-
super().__init__(args)
|
| 38 |
-
|
| 39 |
-
self.spk_emb_proj = None
|
| 40 |
-
if args.target_speaker_embed:
|
| 41 |
-
self.spk_emb_proj = Linear(
|
| 42 |
-
args.encoder_embed_dim + args.speaker_embed_dim, args.encoder_embed_dim
|
| 43 |
-
)
|
| 44 |
-
|
| 45 |
-
def forward(
|
| 46 |
-
self, src_tokens, src_lengths, tgt_speaker=None, return_all_hiddens=False
|
| 47 |
-
):
|
| 48 |
-
out = super().forward(src_tokens, src_lengths, return_all_hiddens)
|
| 49 |
-
|
| 50 |
-
if self.spk_emb_proj:
|
| 51 |
-
x = out["encoder_out"][0]
|
| 52 |
-
seq_len, bsz, _ = x.size()
|
| 53 |
-
tgt_speaker_emb = tgt_speaker.view(1, bsz, -1).expand(seq_len, bsz, -1)
|
| 54 |
-
x = self.spk_emb_proj(torch.cat([x, tgt_speaker_emb], dim=2))
|
| 55 |
-
out["encoder_out"][0] = x
|
| 56 |
-
|
| 57 |
-
return out
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
class TransformerUnitDecoder(TransformerDecoder):
|
| 61 |
-
"""Based on Transformer decoder, with support to decoding stacked units"""
|
| 62 |
-
|
| 63 |
-
def __init__(
|
| 64 |
-
self,
|
| 65 |
-
args,
|
| 66 |
-
dictionary,
|
| 67 |
-
embed_tokens,
|
| 68 |
-
no_encoder_attn=False,
|
| 69 |
-
output_projection=None,
|
| 70 |
-
):
|
| 71 |
-
super().__init__(
|
| 72 |
-
args, dictionary, embed_tokens, no_encoder_attn, output_projection
|
| 73 |
-
)
|
| 74 |
-
self.n_frames_per_step = args.n_frames_per_step
|
| 75 |
-
|
| 76 |
-
self.out_proj_n_frames = (
|
| 77 |
-
Linear(
|
| 78 |
-
self.output_embed_dim,
|
| 79 |
-
self.output_embed_dim * self.n_frames_per_step,
|
| 80 |
-
bias=False,
|
| 81 |
-
)
|
| 82 |
-
if self.n_frames_per_step > 1
|
| 83 |
-
else None
|
| 84 |
-
)
|
| 85 |
-
|
| 86 |
-
def forward(
|
| 87 |
-
self,
|
| 88 |
-
prev_output_tokens,
|
| 89 |
-
encoder_out: Optional[Dict[str, List[Tensor]]] = None,
|
| 90 |
-
incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
|
| 91 |
-
features_only: bool = False,
|
| 92 |
-
full_context_alignment: bool = False,
|
| 93 |
-
alignment_layer: Optional[int] = None,
|
| 94 |
-
alignment_heads: Optional[int] = None,
|
| 95 |
-
src_lengths: Optional[Any] = None,
|
| 96 |
-
return_all_hiddens: bool = False,
|
| 97 |
-
):
|
| 98 |
-
"""
|
| 99 |
-
Args:
|
| 100 |
-
prev_output_tokens (LongTensor): previous decoder outputs of shape
|
| 101 |
-
`(batch, tgt_len)`, for teacher forcing
|
| 102 |
-
encoder_out (optional): output from the encoder, used for
|
| 103 |
-
encoder-side attention, should be of size T x B x C
|
| 104 |
-
incremental_state (dict): dictionary used for storing state during
|
| 105 |
-
:ref:`Incremental decoding`
|
| 106 |
-
features_only (bool, optional): only return features without
|
| 107 |
-
applying output layer (default: False).
|
| 108 |
-
full_context_alignment (bool, optional): don't apply
|
| 109 |
-
auto-regressive mask to self-attention (default: False).
|
| 110 |
-
|
| 111 |
-
Returns:
|
| 112 |
-
tuple:
|
| 113 |
-
- the decoder's output of shape `(batch, tgt_len, vocab)`
|
| 114 |
-
- a dictionary with any model-specific outputs
|
| 115 |
-
"""
|
| 116 |
-
|
| 117 |
-
x, extra = self.extract_features(
|
| 118 |
-
prev_output_tokens,
|
| 119 |
-
encoder_out=encoder_out,
|
| 120 |
-
incremental_state=incremental_state,
|
| 121 |
-
full_context_alignment=full_context_alignment,
|
| 122 |
-
alignment_layer=alignment_layer,
|
| 123 |
-
alignment_heads=alignment_heads,
|
| 124 |
-
)
|
| 125 |
-
|
| 126 |
-
if not features_only:
|
| 127 |
-
bsz, seq_len, d = x.size()
|
| 128 |
-
if self.out_proj_n_frames:
|
| 129 |
-
x = self.out_proj_n_frames(x)
|
| 130 |
-
x = self.output_layer(x.view(bsz, seq_len, self.n_frames_per_step, d))
|
| 131 |
-
x = x.view(bsz, seq_len * self.n_frames_per_step, -1)
|
| 132 |
-
if (
|
| 133 |
-
incremental_state is None and self.n_frames_per_step > 1
|
| 134 |
-
): # teacher-forcing mode in training
|
| 135 |
-
x = x[
|
| 136 |
-
:, : -(self.n_frames_per_step - 1), :
|
| 137 |
-
] # remove extra frames after <eos>
|
| 138 |
-
|
| 139 |
-
return x, extra
|
| 140 |
-
|
| 141 |
-
def upgrade_state_dict_named(self, state_dict, name):
|
| 142 |
-
if self.n_frames_per_step > 1:
|
| 143 |
-
move_keys = [
|
| 144 |
-
(
|
| 145 |
-
f"{name}.project_in_dim.weight",
|
| 146 |
-
f"{name}.embed_tokens.project_in_dim.weight",
|
| 147 |
-
)
|
| 148 |
-
]
|
| 149 |
-
for from_k, to_k in move_keys:
|
| 150 |
-
if from_k in state_dict and to_k not in state_dict:
|
| 151 |
-
state_dict[to_k] = state_dict[from_k]
|
| 152 |
-
del state_dict[from_k]
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
class S2STransformerMultitaskModelBase(FairseqEncoderDecoderModel):
|
| 156 |
-
@classmethod
|
| 157 |
-
def build_encoder(cls, args):
|
| 158 |
-
encoder = S2STransformerEncoder(args)
|
| 159 |
-
pretraining_path = getattr(args, "load_pretrained_encoder_from", None)
|
| 160 |
-
if pretraining_path is not None:
|
| 161 |
-
if not Path(pretraining_path).exists():
|
| 162 |
-
logger.warning(
|
| 163 |
-
f"skipped pretraining because {pretraining_path} does not exist"
|
| 164 |
-
)
|
| 165 |
-
else:
|
| 166 |
-
encoder = checkpoint_utils.load_pretrained_component_from_model(
|
| 167 |
-
component=encoder, checkpoint=pretraining_path
|
| 168 |
-
)
|
| 169 |
-
logger.info(f"loaded pretrained encoder from: {pretraining_path}")
|
| 170 |
-
return encoder
|
| 171 |
-
|
| 172 |
-
@classmethod
|
| 173 |
-
def build_multitask_decoder(cls, args, tgt_dict, in_dim):
|
| 174 |
-
decoder_args = args.decoder_args
|
| 175 |
-
decoder_args.encoder_embed_dim = in_dim
|
| 176 |
-
if args.decoder_type == "transformer":
|
| 177 |
-
base_multitask_text_transformer_decoder_arch(decoder_args)
|
| 178 |
-
task_decoder = TransformerDecoder(
|
| 179 |
-
decoder_args,
|
| 180 |
-
tgt_dict,
|
| 181 |
-
embed_tokens=TransformerModelBase.build_embedding(
|
| 182 |
-
decoder_args,
|
| 183 |
-
tgt_dict,
|
| 184 |
-
decoder_args.decoder_embed_dim,
|
| 185 |
-
),
|
| 186 |
-
)
|
| 187 |
-
elif args.decoder_type == "ctc":
|
| 188 |
-
task_decoder = CTCDecoder(
|
| 189 |
-
dictionary=tgt_dict,
|
| 190 |
-
in_dim=in_dim,
|
| 191 |
-
)
|
| 192 |
-
else:
|
| 193 |
-
raise NotImplementedError(
|
| 194 |
-
"currently only support multitask decoder_type 'transformer', 'ctc'"
|
| 195 |
-
)
|
| 196 |
-
|
| 197 |
-
return task_decoder
|
| 198 |
-
|
| 199 |
-
@classmethod
|
| 200 |
-
def build_model(cls, args, task):
|
| 201 |
-
encoder = cls.build_encoder(args)
|
| 202 |
-
decoder = (
|
| 203 |
-
cls.build_decoder(args, task.target_dictionary)
|
| 204 |
-
if task.args.target_is_code
|
| 205 |
-
else cls.build_decoder(args)
|
| 206 |
-
)
|
| 207 |
-
base_model = cls(encoder, decoder)
|
| 208 |
-
|
| 209 |
-
# set up multitask decoders
|
| 210 |
-
base_model.multitask_decoders = {}
|
| 211 |
-
for task_name, task_obj in task.multitask_tasks.items():
|
| 212 |
-
in_dim = (
|
| 213 |
-
args.encoder_embed_dim
|
| 214 |
-
if task_obj.args.input_from == "encoder"
|
| 215 |
-
else args.decoder_embed_dim
|
| 216 |
-
)
|
| 217 |
-
task_decoder = cls.build_multitask_decoder(
|
| 218 |
-
task_obj.args, task_obj.target_dictionary, in_dim
|
| 219 |
-
)
|
| 220 |
-
|
| 221 |
-
setattr(base_model, f"{task_name}_decoder", task_decoder)
|
| 222 |
-
decoder_model_cls = (
|
| 223 |
-
FairseqEncoderModel
|
| 224 |
-
if task_obj.args.decoder_type == "ctc"
|
| 225 |
-
else FairseqLanguageModel
|
| 226 |
-
)
|
| 227 |
-
base_model.multitask_decoders[task_name] = decoder_model_cls(
|
| 228 |
-
getattr(base_model, f"{task_name}_decoder")
|
| 229 |
-
)
|
| 230 |
-
|
| 231 |
-
return base_model
|
| 232 |
-
|
| 233 |
-
def forward_encoder(self, src_tokens, src_lengths, speaker=None, **kwargs):
|
| 234 |
-
return self.encoder(
|
| 235 |
-
src_tokens, src_lengths=src_lengths, tgt_speaker=speaker, **kwargs
|
| 236 |
-
)
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
@register_model("s2ut_transformer")
|
| 240 |
-
class S2UTTransformerModel(S2STransformerMultitaskModelBase):
|
| 241 |
-
"""
|
| 242 |
-
Direct speech-to-speech translation model with S2T Transformer encoder + Transformer discrete unit decoder
|
| 243 |
-
https://arxiv.org/abs/2107.05604
|
| 244 |
-
"""
|
| 245 |
-
|
| 246 |
-
@staticmethod
|
| 247 |
-
def add_args(parser):
|
| 248 |
-
# input
|
| 249 |
-
parser.add_argument(
|
| 250 |
-
"--conv-kernel-sizes",
|
| 251 |
-
type=str,
|
| 252 |
-
metavar="N",
|
| 253 |
-
help="kernel sizes of Conv1d subsampling layers",
|
| 254 |
-
)
|
| 255 |
-
parser.add_argument(
|
| 256 |
-
"--conv-channels",
|
| 257 |
-
type=int,
|
| 258 |
-
metavar="N",
|
| 259 |
-
help="# of channels in Conv1d subsampling layers",
|
| 260 |
-
)
|
| 261 |
-
# Transformer
|
| 262 |
-
parser.add_argument(
|
| 263 |
-
"--activation-fn",
|
| 264 |
-
type=str,
|
| 265 |
-
default="relu",
|
| 266 |
-
choices=utils.get_available_activation_fns(),
|
| 267 |
-
help="activation function to use",
|
| 268 |
-
)
|
| 269 |
-
parser.add_argument(
|
| 270 |
-
"--dropout", type=float, metavar="D", help="dropout probability"
|
| 271 |
-
)
|
| 272 |
-
parser.add_argument(
|
| 273 |
-
"--attention-dropout",
|
| 274 |
-
type=float,
|
| 275 |
-
metavar="D",
|
| 276 |
-
help="dropout probability for attention weights",
|
| 277 |
-
)
|
| 278 |
-
parser.add_argument(
|
| 279 |
-
"--activation-dropout",
|
| 280 |
-
"--relu-dropout",
|
| 281 |
-
type=float,
|
| 282 |
-
metavar="D",
|
| 283 |
-
help="dropout probability after activation in FFN.",
|
| 284 |
-
)
|
| 285 |
-
parser.add_argument(
|
| 286 |
-
"--encoder-embed-dim",
|
| 287 |
-
type=int,
|
| 288 |
-
metavar="N",
|
| 289 |
-
help="encoder embedding dimension",
|
| 290 |
-
)
|
| 291 |
-
parser.add_argument(
|
| 292 |
-
"--encoder-ffn-embed-dim",
|
| 293 |
-
type=int,
|
| 294 |
-
metavar="N",
|
| 295 |
-
help="encoder embedding dimension for FFN",
|
| 296 |
-
)
|
| 297 |
-
parser.add_argument(
|
| 298 |
-
"--encoder-layers", type=int, metavar="N", help="num encoder layers"
|
| 299 |
-
)
|
| 300 |
-
parser.add_argument(
|
| 301 |
-
"--encoder-attention-heads",
|
| 302 |
-
type=int,
|
| 303 |
-
metavar="N",
|
| 304 |
-
help="num encoder attention heads",
|
| 305 |
-
)
|
| 306 |
-
parser.add_argument(
|
| 307 |
-
"--encoder-normalize-before",
|
| 308 |
-
action="store_true",
|
| 309 |
-
help="apply layernorm before each encoder block",
|
| 310 |
-
)
|
| 311 |
-
parser.add_argument(
|
| 312 |
-
"--decoder-embed-dim",
|
| 313 |
-
type=int,
|
| 314 |
-
metavar="N",
|
| 315 |
-
help="decoder embedding dimension",
|
| 316 |
-
)
|
| 317 |
-
parser.add_argument(
|
| 318 |
-
"--decoder-ffn-embed-dim",
|
| 319 |
-
type=int,
|
| 320 |
-
metavar="N",
|
| 321 |
-
help="decoder embedding dimension for FFN",
|
| 322 |
-
)
|
| 323 |
-
parser.add_argument(
|
| 324 |
-
"--decoder-layers", type=int, metavar="N", help="num decoder layers"
|
| 325 |
-
)
|
| 326 |
-
parser.add_argument(
|
| 327 |
-
"--decoder-attention-heads",
|
| 328 |
-
type=int,
|
| 329 |
-
metavar="N",
|
| 330 |
-
help="num decoder attention heads",
|
| 331 |
-
)
|
| 332 |
-
parser.add_argument(
|
| 333 |
-
"--decoder-normalize-before",
|
| 334 |
-
action="store_true",
|
| 335 |
-
help="apply layernorm before each decoder block",
|
| 336 |
-
)
|
| 337 |
-
parser.add_argument(
|
| 338 |
-
"--share-decoder-input-output-embed",
|
| 339 |
-
action="store_true",
|
| 340 |
-
help="share decoder input and output embeddings",
|
| 341 |
-
)
|
| 342 |
-
parser.add_argument(
|
| 343 |
-
"--layernorm-embedding",
|
| 344 |
-
action="store_true",
|
| 345 |
-
help="add layernorm to embedding",
|
| 346 |
-
)
|
| 347 |
-
parser.add_argument(
|
| 348 |
-
"--no-scale-embedding",
|
| 349 |
-
action="store_true",
|
| 350 |
-
help="if True, dont scale embeddings",
|
| 351 |
-
)
|
| 352 |
-
parser.add_argument(
|
| 353 |
-
"--load-pretrained-encoder-from",
|
| 354 |
-
type=str,
|
| 355 |
-
metavar="STR",
|
| 356 |
-
help="model to take encoder weights from (for initialization)",
|
| 357 |
-
)
|
| 358 |
-
parser.add_argument(
|
| 359 |
-
"--encoder-freezing-updates",
|
| 360 |
-
type=int,
|
| 361 |
-
metavar="N",
|
| 362 |
-
help="freeze encoder for first N updates",
|
| 363 |
-
)
|
| 364 |
-
# speaker
|
| 365 |
-
parser.add_argument(
|
| 366 |
-
"--speaker-embed-dim",
|
| 367 |
-
type=int,
|
| 368 |
-
metavar="N",
|
| 369 |
-
help="speaker embedding dimension",
|
| 370 |
-
)
|
| 371 |
-
|
| 372 |
-
@classmethod
|
| 373 |
-
def build_decoder(cls, args, tgt_dict):
|
| 374 |
-
num_embeddings = len(tgt_dict)
|
| 375 |
-
padding_idx = tgt_dict.pad()
|
| 376 |
-
embed_tokens = StackedEmbedding(
|
| 377 |
-
num_embeddings,
|
| 378 |
-
args.decoder_embed_dim,
|
| 379 |
-
padding_idx,
|
| 380 |
-
num_stacked=args.n_frames_per_step,
|
| 381 |
-
)
|
| 382 |
-
|
| 383 |
-
return TransformerUnitDecoder(
|
| 384 |
-
args,
|
| 385 |
-
tgt_dict,
|
| 386 |
-
embed_tokens,
|
| 387 |
-
)
|
| 388 |
-
|
| 389 |
-
def forward(
|
| 390 |
-
self,
|
| 391 |
-
src_tokens,
|
| 392 |
-
src_lengths,
|
| 393 |
-
prev_output_tokens,
|
| 394 |
-
tgt_speaker=None,
|
| 395 |
-
return_all_hiddens=False,
|
| 396 |
-
):
|
| 397 |
-
encoder_out = self.encoder(
|
| 398 |
-
src_tokens,
|
| 399 |
-
src_lengths=src_lengths,
|
| 400 |
-
tgt_speaker=tgt_speaker,
|
| 401 |
-
return_all_hiddens=return_all_hiddens,
|
| 402 |
-
)
|
| 403 |
-
decoder_out = self.decoder(
|
| 404 |
-
prev_output_tokens,
|
| 405 |
-
encoder_out=encoder_out,
|
| 406 |
-
)
|
| 407 |
-
if return_all_hiddens:
|
| 408 |
-
decoder_out[-1]["encoder_states"] = encoder_out["encoder_states"]
|
| 409 |
-
decoder_out[-1]["encoder_padding_mask"] = encoder_out[
|
| 410 |
-
"encoder_padding_mask"
|
| 411 |
-
]
|
| 412 |
-
return decoder_out
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
@register_model("s2spect_transformer")
|
| 416 |
-
class S2SpecTTransformerModel(S2STransformerMultitaskModelBase):
|
| 417 |
-
"""
|
| 418 |
-
Speech-to-spectrogram model with S2T Transformer encoder + TTS Transformer decoder
|
| 419 |
-
"""
|
| 420 |
-
|
| 421 |
-
@staticmethod
|
| 422 |
-
def add_args(parser):
|
| 423 |
-
# input
|
| 424 |
-
parser.add_argument(
|
| 425 |
-
"--conv-kernel-sizes",
|
| 426 |
-
type=str,
|
| 427 |
-
metavar="N",
|
| 428 |
-
help="kernel sizes of Conv1d subsampling layers",
|
| 429 |
-
)
|
| 430 |
-
parser.add_argument(
|
| 431 |
-
"--conv-channels",
|
| 432 |
-
type=int,
|
| 433 |
-
metavar="N",
|
| 434 |
-
help="# of channels in Conv1d subsampling layers",
|
| 435 |
-
)
|
| 436 |
-
# Transformer
|
| 437 |
-
parser.add_argument(
|
| 438 |
-
"--activation-fn",
|
| 439 |
-
type=str,
|
| 440 |
-
default="relu",
|
| 441 |
-
choices=utils.get_available_activation_fns(),
|
| 442 |
-
help="activation function to use",
|
| 443 |
-
)
|
| 444 |
-
parser.add_argument(
|
| 445 |
-
"--dropout", type=float, metavar="D", help="dropout probability"
|
| 446 |
-
)
|
| 447 |
-
parser.add_argument(
|
| 448 |
-
"--attention-dropout",
|
| 449 |
-
type=float,
|
| 450 |
-
metavar="D",
|
| 451 |
-
help="dropout probability for attention weights",
|
| 452 |
-
)
|
| 453 |
-
parser.add_argument(
|
| 454 |
-
"--activation-dropout",
|
| 455 |
-
"--relu-dropout",
|
| 456 |
-
type=float,
|
| 457 |
-
metavar="D",
|
| 458 |
-
help="dropout probability after activation in FFN.",
|
| 459 |
-
)
|
| 460 |
-
parser.add_argument(
|
| 461 |
-
"--encoder-embed-dim",
|
| 462 |
-
type=int,
|
| 463 |
-
metavar="N",
|
| 464 |
-
help="encoder embedding dimension",
|
| 465 |
-
)
|
| 466 |
-
parser.add_argument(
|
| 467 |
-
"--encoder-ffn-embed-dim",
|
| 468 |
-
type=int,
|
| 469 |
-
metavar="N",
|
| 470 |
-
help="encoder embedding dimension for FFN",
|
| 471 |
-
)
|
| 472 |
-
parser.add_argument(
|
| 473 |
-
"--encoder-layers", type=int, metavar="N", help="num encoder layers"
|
| 474 |
-
)
|
| 475 |
-
parser.add_argument(
|
| 476 |
-
"--encoder-attention-heads",
|
| 477 |
-
type=int,
|
| 478 |
-
metavar="N",
|
| 479 |
-
help="num encoder attention heads",
|
| 480 |
-
)
|
| 481 |
-
parser.add_argument(
|
| 482 |
-
"--encoder-normalize-before",
|
| 483 |
-
action="store_true",
|
| 484 |
-
help="apply layernorm before each encoder block",
|
| 485 |
-
)
|
| 486 |
-
parser.add_argument(
|
| 487 |
-
"--no-scale-embedding",
|
| 488 |
-
action="store_true",
|
| 489 |
-
help="if True, dont scale embeddings",
|
| 490 |
-
)
|
| 491 |
-
parser.add_argument(
|
| 492 |
-
"--load-pretrained-encoder-from",
|
| 493 |
-
type=str,
|
| 494 |
-
metavar="STR",
|
| 495 |
-
help="model to take encoder weights from (for initialization)",
|
| 496 |
-
)
|
| 497 |
-
parser.add_argument(
|
| 498 |
-
"--encoder-freezing-updates",
|
| 499 |
-
type=int,
|
| 500 |
-
metavar="N",
|
| 501 |
-
help="freeze encoder for first N updates",
|
| 502 |
-
)
|
| 503 |
-
# speaker
|
| 504 |
-
parser.add_argument(
|
| 505 |
-
"--speaker-embed-dim",
|
| 506 |
-
type=int,
|
| 507 |
-
metavar="N",
|
| 508 |
-
help="speaker embedding dimension",
|
| 509 |
-
)
|
| 510 |
-
# decoder
|
| 511 |
-
parser.add_argument("--output-frame-dim", type=int)
|
| 512 |
-
# decoder prenet
|
| 513 |
-
parser.add_argument("--prenet-dropout", type=float)
|
| 514 |
-
parser.add_argument("--prenet-layers", type=int)
|
| 515 |
-
parser.add_argument("--prenet-dim", type=int)
|
| 516 |
-
# decoder postnet
|
| 517 |
-
parser.add_argument("--postnet-dropout", type=float)
|
| 518 |
-
parser.add_argument("--postnet-layers", type=int)
|
| 519 |
-
parser.add_argument("--postnet-conv-dim", type=int)
|
| 520 |
-
parser.add_argument("--postnet-conv-kernel-size", type=int)
|
| 521 |
-
# decoder transformer layers
|
| 522 |
-
parser.add_argument("--decoder-transformer-layers", type=int)
|
| 523 |
-
parser.add_argument("--decoder-embed-dim", type=int)
|
| 524 |
-
parser.add_argument("--decoder-ffn-embed-dim", type=int)
|
| 525 |
-
parser.add_argument("--decoder-normalize-before", action="store_true")
|
| 526 |
-
parser.add_argument("--decoder-attention-heads", type=int)
|
| 527 |
-
|
| 528 |
-
@classmethod
|
| 529 |
-
def build_decoder(cls, args):
|
| 530 |
-
return TTSTransformerDecoder(args, None, padding_idx=1)
|
| 531 |
-
|
| 532 |
-
def forward(
|
| 533 |
-
self,
|
| 534 |
-
src_tokens,
|
| 535 |
-
src_lengths,
|
| 536 |
-
prev_output_tokens,
|
| 537 |
-
tgt_speaker=None,
|
| 538 |
-
incremental_state=None,
|
| 539 |
-
target_lengths=None,
|
| 540 |
-
speaker=None,
|
| 541 |
-
return_all_hiddens=False,
|
| 542 |
-
):
|
| 543 |
-
encoder_out = self.encoder(
|
| 544 |
-
src_tokens,
|
| 545 |
-
src_lengths=src_lengths,
|
| 546 |
-
tgt_speaker=tgt_speaker,
|
| 547 |
-
return_all_hiddens=return_all_hiddens,
|
| 548 |
-
)
|
| 549 |
-
decoder_out = self.decoder(
|
| 550 |
-
prev_output_tokens,
|
| 551 |
-
encoder_out=encoder_out,
|
| 552 |
-
incremental_state=incremental_state,
|
| 553 |
-
target_lengths=target_lengths,
|
| 554 |
-
speaker=speaker,
|
| 555 |
-
)
|
| 556 |
-
if return_all_hiddens:
|
| 557 |
-
decoder_out[-1]["encoder_states"] = encoder_out["encoder_states"]
|
| 558 |
-
decoder_out[-1]["encoder_padding_mask"] = encoder_out[
|
| 559 |
-
"encoder_padding_mask"
|
| 560 |
-
]
|
| 561 |
-
return decoder_out
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
def base_multitask_text_transformer_decoder_arch(args):
|
| 565 |
-
args.dropout = getattr(args, "dropout", 0.3)
|
| 566 |
-
args.decoder_layerdrop = getattr(args, "decoder_layerdrop", 0.0)
|
| 567 |
-
args.share_decoder_input_output_embed = getattr(
|
| 568 |
-
args, "share_decoder_input_output_embed", True
|
| 569 |
-
)
|
| 570 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 256)
|
| 571 |
-
args.decoder_output_dim = getattr(
|
| 572 |
-
args, "decoder_output_dim", args.decoder_embed_dim
|
| 573 |
-
)
|
| 574 |
-
args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim)
|
| 575 |
-
|
| 576 |
-
args.max_target_positions = getattr(args, "max_target_positions", 1024)
|
| 577 |
-
args.no_scale_embedding = getattr(args, "no_scale_embedding", False)
|
| 578 |
-
|
| 579 |
-
args.adaptive_input = getattr(args, "adaptive_input", False)
|
| 580 |
-
args.quant_noise_pq = getattr(args, "quant_noise_pq", 0)
|
| 581 |
-
|
| 582 |
-
args.decoder_learned_pos = getattr(args, "decoder_learned_pos", False)
|
| 583 |
-
args.no_token_positional_embeddings = getattr(
|
| 584 |
-
args, "no_token_positional_embeddings", False
|
| 585 |
-
)
|
| 586 |
-
|
| 587 |
-
args.decoder_layers = getattr(args, "decoder_layers", 2)
|
| 588 |
-
|
| 589 |
-
args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
|
| 590 |
-
|
| 591 |
-
# decoder layer
|
| 592 |
-
args.activation_dropout = getattr(args, "activation_dropout", args.dropout)
|
| 593 |
-
args.activation_fn = getattr(args, "activation_fn", "relu")
|
| 594 |
-
args.decoder_normalize_before = getattr(args, "decoder_normalize_before", True)
|
| 595 |
-
args.decoder_ffn_embed_dim = getattr(args, "decoder_ffn_embed_dim", 2048)
|
| 596 |
-
|
| 597 |
-
args.attention_dropout = getattr(args, "attention_dropout", args.dropout)
|
| 598 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 4)
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
def base_s2st_transformer_encoder_architecture(args):
|
| 602 |
-
args.encoder_freezing_updates = getattr(args, "encoder_freezing_updates", 0)
|
| 603 |
-
|
| 604 |
-
# Convolutional subsampler
|
| 605 |
-
args.conv_kernel_sizes = getattr(args, "conv_kernel_sizes", "5,5")
|
| 606 |
-
args.conv_channels = getattr(args, "conv_channels", 1024)
|
| 607 |
-
# Transformer
|
| 608 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
|
| 609 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 2048)
|
| 610 |
-
args.encoder_layers = getattr(args, "encoder_layers", 12)
|
| 611 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8)
|
| 612 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", True)
|
| 613 |
-
args.no_scale_embedding = getattr(args, "no_scale_embedding", False)
|
| 614 |
-
|
| 615 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 616 |
-
args.attention_dropout = getattr(args, "attention_dropout", args.dropout)
|
| 617 |
-
args.activation_dropout = getattr(args, "activation_dropout", args.dropout)
|
| 618 |
-
args.activation_fn = getattr(args, "activation_fn", "relu")
|
| 619 |
-
|
| 620 |
-
args.speaker_embed_dim = getattr(args, "speaker_embed_dim", 256)
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
@register_model_architecture(
|
| 624 |
-
model_name="s2ut_transformer", arch_name="s2ut_transformer"
|
| 625 |
-
)
|
| 626 |
-
def s2ut_architecture_base(args):
|
| 627 |
-
base_s2st_transformer_encoder_architecture(args)
|
| 628 |
-
|
| 629 |
-
# decoder
|
| 630 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", args.encoder_embed_dim)
|
| 631 |
-
args.decoder_ffn_embed_dim = getattr(
|
| 632 |
-
args, "decoder_ffn_embed_dim", args.encoder_ffn_embed_dim
|
| 633 |
-
)
|
| 634 |
-
args.decoder_layers = getattr(args, "decoder_layers", 6)
|
| 635 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 8)
|
| 636 |
-
args.decoder_normalize_before = getattr(args, "decoder_normalize_before", True)
|
| 637 |
-
args.decoder_learned_pos = getattr(args, "decoder_learned_pos", False)
|
| 638 |
-
args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
|
| 639 |
-
args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
|
| 640 |
-
args.share_decoder_input_output_embed = getattr(
|
| 641 |
-
args, "share_decoder_input_output_embed", False
|
| 642 |
-
)
|
| 643 |
-
args.no_token_positional_embeddings = getattr(
|
| 644 |
-
args, "no_token_positional_embeddings", False
|
| 645 |
-
)
|
| 646 |
-
args.adaptive_input = getattr(args, "adaptive_input", False)
|
| 647 |
-
args.decoder_layerdrop = getattr(args, "decoder_layerdrop", 0.0)
|
| 648 |
-
args.decoder_output_dim = getattr(
|
| 649 |
-
args, "decoder_output_dim", args.decoder_embed_dim
|
| 650 |
-
)
|
| 651 |
-
args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim)
|
| 652 |
-
args.quant_noise_pq = getattr(args, "quant_noise_pq", 0)
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
@register_model_architecture("s2ut_transformer", "s2ut_transformer_fisher")
|
| 656 |
-
def s2ut_architecture_fisher(args):
|
| 657 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 256)
|
| 658 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 4)
|
| 659 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 660 |
-
|
| 661 |
-
s2ut_architecture_base(args)
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
@register_model_architecture(
|
| 665 |
-
model_name="s2spect_transformer", arch_name="s2spect_transformer"
|
| 666 |
-
)
|
| 667 |
-
def s2spect_architecture_base(args):
|
| 668 |
-
base_s2st_transformer_encoder_architecture(args)
|
| 669 |
-
|
| 670 |
-
# decoder
|
| 671 |
-
args.output_frame_dim = getattr(args, "output_frame_dim", 80)
|
| 672 |
-
# decoder prenet
|
| 673 |
-
args.prenet_dropout = getattr(args, "prenet_dropout", 0.5)
|
| 674 |
-
args.prenet_layers = getattr(args, "prenet_layers", 2)
|
| 675 |
-
args.prenet_dim = getattr(args, "prenet_dim", 256)
|
| 676 |
-
# decoder postnet
|
| 677 |
-
args.postnet_dropout = getattr(args, "postnet_dropout", 0.5)
|
| 678 |
-
args.postnet_layers = getattr(args, "postnet_layers", 5)
|
| 679 |
-
args.postnet_conv_dim = getattr(args, "postnet_conv_dim", 512)
|
| 680 |
-
args.postnet_conv_kernel_size = getattr(args, "postnet_conv_kernel_size", 5)
|
| 681 |
-
# decoder transformer layers
|
| 682 |
-
args.decoder_transformer_layers = getattr(args, "decoder_transformer_layers", 6)
|
| 683 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 512)
|
| 684 |
-
args.decoder_ffn_embed_dim = getattr(
|
| 685 |
-
args, "decoder_ffn_embed_dim", 4 * args.decoder_embed_dim
|
| 686 |
-
)
|
| 687 |
-
args.decoder_normalize_before = getattr(args, "decoder_normalize_before", False)
|
| 688 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 4)
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
@register_model_architecture("s2spect_transformer", "s2spect_transformer_fisher")
|
| 692 |
-
def s2spect_architecture_fisher(args):
|
| 693 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 256)
|
| 694 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 256 * 8)
|
| 695 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 4)
|
| 696 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 697 |
-
|
| 698 |
-
# decoder
|
| 699 |
-
args.prenet_dim = getattr(args, "prenet_dim", 32)
|
| 700 |
-
|
| 701 |
-
s2spect_architecture_base(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_text/__init__.py
DELETED
|
@@ -1,12 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
from .berard import * # noqa
|
| 7 |
-
from .convtransformer import * # noqa
|
| 8 |
-
from .multi_modality_model import * # noqa
|
| 9 |
-
from .s2t_conformer import * # noqa
|
| 10 |
-
from .s2t_transformer import * # noqa
|
| 11 |
-
from .s2t_wav_transformer import * # noqa
|
| 12 |
-
from .xm_transformer import * # noqa
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_text/berard.py
DELETED
|
@@ -1,606 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
|
| 3 |
-
from ast import literal_eval
|
| 4 |
-
from typing import List, Tuple
|
| 5 |
-
|
| 6 |
-
import torch
|
| 7 |
-
import torch.nn as nn
|
| 8 |
-
import torch.nn.functional as F
|
| 9 |
-
from fairseq import checkpoint_utils, utils
|
| 10 |
-
from fairseq.data.data_utils import lengths_to_padding_mask
|
| 11 |
-
from fairseq.models import (
|
| 12 |
-
FairseqEncoder,
|
| 13 |
-
FairseqEncoderDecoderModel,
|
| 14 |
-
FairseqIncrementalDecoder,
|
| 15 |
-
register_model,
|
| 16 |
-
register_model_architecture,
|
| 17 |
-
)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
@register_model("s2t_berard")
|
| 21 |
-
class BerardModel(FairseqEncoderDecoderModel):
|
| 22 |
-
"""Implementation of a model similar to https://arxiv.org/abs/1802.04200
|
| 23 |
-
|
| 24 |
-
Paper title: End-to-End Automatic Speech Translation of Audiobooks
|
| 25 |
-
An implementation is available in tensorflow at
|
| 26 |
-
https://github.com/eske/seq2seq
|
| 27 |
-
Relevant files in this implementation are the config
|
| 28 |
-
(https://github.com/eske/seq2seq/blob/master/config/LibriSpeech/AST.yaml)
|
| 29 |
-
and the model code
|
| 30 |
-
(https://github.com/eske/seq2seq/blob/master/translate/models.py).
|
| 31 |
-
The encoder and decoder try to be close to the original implementation.
|
| 32 |
-
The attention is an MLP as in Bahdanau et al.
|
| 33 |
-
(https://arxiv.org/abs/1409.0473).
|
| 34 |
-
There is no state initialization by averaging the encoder outputs.
|
| 35 |
-
"""
|
| 36 |
-
|
| 37 |
-
def __init__(self, encoder, decoder):
|
| 38 |
-
super().__init__(encoder, decoder)
|
| 39 |
-
|
| 40 |
-
@staticmethod
|
| 41 |
-
def add_args(parser):
|
| 42 |
-
parser.add_argument(
|
| 43 |
-
"--input-layers",
|
| 44 |
-
type=str,
|
| 45 |
-
metavar="EXPR",
|
| 46 |
-
help="List of linear layer dimensions. These "
|
| 47 |
-
"layers are applied to the input features and "
|
| 48 |
-
"are followed by tanh and possibly dropout.",
|
| 49 |
-
)
|
| 50 |
-
parser.add_argument(
|
| 51 |
-
"--dropout",
|
| 52 |
-
type=float,
|
| 53 |
-
metavar="D",
|
| 54 |
-
help="Dropout probability to use in the encoder/decoder. "
|
| 55 |
-
"Note that this parameters control dropout in various places, "
|
| 56 |
-
"there is no fine-grained control for dropout for embeddings "
|
| 57 |
-
"vs LSTM layers for example.",
|
| 58 |
-
)
|
| 59 |
-
parser.add_argument(
|
| 60 |
-
"--in-channels",
|
| 61 |
-
type=int,
|
| 62 |
-
metavar="N",
|
| 63 |
-
help="Number of encoder input channels. " "Typically value is 1.",
|
| 64 |
-
)
|
| 65 |
-
parser.add_argument(
|
| 66 |
-
"--conv-layers",
|
| 67 |
-
type=str,
|
| 68 |
-
metavar="EXPR",
|
| 69 |
-
help="List of conv layers " "(format: (channels, kernel, stride)).",
|
| 70 |
-
)
|
| 71 |
-
parser.add_argument(
|
| 72 |
-
"--num-blstm-layers",
|
| 73 |
-
type=int,
|
| 74 |
-
metavar="N",
|
| 75 |
-
help="Number of encoder bi-LSTM layers.",
|
| 76 |
-
)
|
| 77 |
-
parser.add_argument(
|
| 78 |
-
"--lstm-size", type=int, metavar="N", help="LSTM hidden size."
|
| 79 |
-
)
|
| 80 |
-
parser.add_argument(
|
| 81 |
-
"--decoder-embed-dim",
|
| 82 |
-
type=int,
|
| 83 |
-
metavar="N",
|
| 84 |
-
help="Embedding dimension of the decoder target tokens.",
|
| 85 |
-
)
|
| 86 |
-
parser.add_argument(
|
| 87 |
-
"--decoder-hidden-dim",
|
| 88 |
-
type=int,
|
| 89 |
-
metavar="N",
|
| 90 |
-
help="Decoder LSTM hidden dimension.",
|
| 91 |
-
)
|
| 92 |
-
parser.add_argument(
|
| 93 |
-
"--decoder-num-layers",
|
| 94 |
-
type=int,
|
| 95 |
-
metavar="N",
|
| 96 |
-
help="Number of decoder LSTM layers.",
|
| 97 |
-
)
|
| 98 |
-
parser.add_argument(
|
| 99 |
-
"--attention-dim",
|
| 100 |
-
type=int,
|
| 101 |
-
metavar="N",
|
| 102 |
-
help="Hidden layer dimension in MLP attention.",
|
| 103 |
-
)
|
| 104 |
-
parser.add_argument(
|
| 105 |
-
"--output-layer-dim",
|
| 106 |
-
type=int,
|
| 107 |
-
metavar="N",
|
| 108 |
-
help="Hidden layer dim for linear layer prior to output projection.",
|
| 109 |
-
)
|
| 110 |
-
parser.add_argument(
|
| 111 |
-
"--load-pretrained-encoder-from",
|
| 112 |
-
type=str,
|
| 113 |
-
metavar="STR",
|
| 114 |
-
help="model to take encoder weights from (for initialization)",
|
| 115 |
-
)
|
| 116 |
-
parser.add_argument(
|
| 117 |
-
"--load-pretrained-decoder-from",
|
| 118 |
-
type=str,
|
| 119 |
-
metavar="STR",
|
| 120 |
-
help="model to take decoder weights from (for initialization)",
|
| 121 |
-
)
|
| 122 |
-
|
| 123 |
-
@classmethod
|
| 124 |
-
def build_encoder(cls, args, task):
|
| 125 |
-
encoder = BerardEncoder(
|
| 126 |
-
input_layers=literal_eval(args.input_layers),
|
| 127 |
-
conv_layers=literal_eval(args.conv_layers),
|
| 128 |
-
in_channels=args.input_channels,
|
| 129 |
-
input_feat_per_channel=args.input_feat_per_channel,
|
| 130 |
-
num_blstm_layers=args.num_blstm_layers,
|
| 131 |
-
lstm_size=args.lstm_size,
|
| 132 |
-
dropout=args.dropout,
|
| 133 |
-
)
|
| 134 |
-
if getattr(args, "load_pretrained_encoder_from", None):
|
| 135 |
-
encoder = checkpoint_utils.load_pretrained_component_from_model(
|
| 136 |
-
component=encoder, checkpoint=args.load_pretrained_encoder_from
|
| 137 |
-
)
|
| 138 |
-
return encoder
|
| 139 |
-
|
| 140 |
-
@classmethod
|
| 141 |
-
def build_decoder(cls, args, task):
|
| 142 |
-
decoder = LSTMDecoder(
|
| 143 |
-
dictionary=task.target_dictionary,
|
| 144 |
-
embed_dim=args.decoder_embed_dim,
|
| 145 |
-
num_layers=args.decoder_num_layers,
|
| 146 |
-
hidden_size=args.decoder_hidden_dim,
|
| 147 |
-
dropout=args.dropout,
|
| 148 |
-
encoder_output_dim=2 * args.lstm_size, # bidirectional
|
| 149 |
-
attention_dim=args.attention_dim,
|
| 150 |
-
output_layer_dim=args.output_layer_dim,
|
| 151 |
-
)
|
| 152 |
-
if getattr(args, "load_pretrained_decoder_from", None):
|
| 153 |
-
decoder = checkpoint_utils.load_pretrained_component_from_model(
|
| 154 |
-
component=decoder, checkpoint=args.load_pretrained_decoder_from
|
| 155 |
-
)
|
| 156 |
-
return decoder
|
| 157 |
-
|
| 158 |
-
@classmethod
|
| 159 |
-
def build_model(cls, args, task):
|
| 160 |
-
"""Build a new model instance."""
|
| 161 |
-
encoder = cls.build_encoder(args, task)
|
| 162 |
-
decoder = cls.build_decoder(args, task)
|
| 163 |
-
|
| 164 |
-
return cls(encoder, decoder)
|
| 165 |
-
|
| 166 |
-
def get_normalized_probs(self, net_output, log_probs, sample=None):
|
| 167 |
-
# net_output['encoder_out'] is a (B, T, D) tensor
|
| 168 |
-
lprobs = super().get_normalized_probs(net_output, log_probs, sample)
|
| 169 |
-
# lprobs is a (B, T, D) tensor
|
| 170 |
-
lprobs.batch_first = True
|
| 171 |
-
return lprobs
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
class BerardEncoder(FairseqEncoder):
|
| 175 |
-
def __init__(
|
| 176 |
-
self,
|
| 177 |
-
input_layers: List[int],
|
| 178 |
-
conv_layers: List[Tuple[int]],
|
| 179 |
-
in_channels: int,
|
| 180 |
-
input_feat_per_channel: int,
|
| 181 |
-
num_blstm_layers: int,
|
| 182 |
-
lstm_size: int,
|
| 183 |
-
dropout: float,
|
| 184 |
-
):
|
| 185 |
-
"""
|
| 186 |
-
Args:
|
| 187 |
-
input_layers: list of linear layer dimensions. These layers are
|
| 188 |
-
applied to the input features and are followed by tanh and
|
| 189 |
-
possibly dropout.
|
| 190 |
-
conv_layers: list of conv2d layer configurations. A configuration is
|
| 191 |
-
a tuple (out_channels, conv_kernel_size, stride).
|
| 192 |
-
in_channels: number of input channels.
|
| 193 |
-
input_feat_per_channel: number of input features per channel. These
|
| 194 |
-
are speech features, typically 40 or 80.
|
| 195 |
-
num_blstm_layers: number of bidirectional LSTM layers.
|
| 196 |
-
lstm_size: size of the LSTM hidden (and cell) size.
|
| 197 |
-
dropout: dropout probability. Dropout can be applied after the
|
| 198 |
-
linear layers and LSTM layers but not to the convolutional
|
| 199 |
-
layers.
|
| 200 |
-
"""
|
| 201 |
-
super().__init__(None)
|
| 202 |
-
|
| 203 |
-
self.input_layers = nn.ModuleList()
|
| 204 |
-
in_features = input_feat_per_channel
|
| 205 |
-
for out_features in input_layers:
|
| 206 |
-
if dropout > 0:
|
| 207 |
-
self.input_layers.append(
|
| 208 |
-
nn.Sequential(
|
| 209 |
-
nn.Linear(in_features, out_features), nn.Dropout(p=dropout)
|
| 210 |
-
)
|
| 211 |
-
)
|
| 212 |
-
else:
|
| 213 |
-
self.input_layers.append(nn.Linear(in_features, out_features))
|
| 214 |
-
in_features = out_features
|
| 215 |
-
|
| 216 |
-
self.in_channels = in_channels
|
| 217 |
-
self.input_dim = input_feat_per_channel
|
| 218 |
-
self.conv_kernel_sizes_and_strides = []
|
| 219 |
-
self.conv_layers = nn.ModuleList()
|
| 220 |
-
lstm_input_dim = input_layers[-1]
|
| 221 |
-
for conv_layer in conv_layers:
|
| 222 |
-
out_channels, conv_kernel_size, conv_stride = conv_layer
|
| 223 |
-
self.conv_layers.append(
|
| 224 |
-
nn.Conv2d(
|
| 225 |
-
in_channels,
|
| 226 |
-
out_channels,
|
| 227 |
-
conv_kernel_size,
|
| 228 |
-
stride=conv_stride,
|
| 229 |
-
padding=conv_kernel_size // 2,
|
| 230 |
-
)
|
| 231 |
-
)
|
| 232 |
-
self.conv_kernel_sizes_and_strides.append((conv_kernel_size, conv_stride))
|
| 233 |
-
in_channels = out_channels
|
| 234 |
-
lstm_input_dim //= conv_stride
|
| 235 |
-
|
| 236 |
-
lstm_input_dim *= conv_layers[-1][0]
|
| 237 |
-
self.lstm_size = lstm_size
|
| 238 |
-
self.num_blstm_layers = num_blstm_layers
|
| 239 |
-
self.lstm = nn.LSTM(
|
| 240 |
-
input_size=lstm_input_dim,
|
| 241 |
-
hidden_size=lstm_size,
|
| 242 |
-
num_layers=num_blstm_layers,
|
| 243 |
-
dropout=dropout,
|
| 244 |
-
bidirectional=True,
|
| 245 |
-
)
|
| 246 |
-
self.output_dim = 2 * lstm_size # bidirectional
|
| 247 |
-
if dropout > 0:
|
| 248 |
-
self.dropout = nn.Dropout(p=dropout)
|
| 249 |
-
else:
|
| 250 |
-
self.dropout = None
|
| 251 |
-
|
| 252 |
-
def forward(self, src_tokens, src_lengths=None, **kwargs):
|
| 253 |
-
"""
|
| 254 |
-
Args
|
| 255 |
-
src_tokens: padded tensor (B, T, C * feat)
|
| 256 |
-
src_lengths: tensor of original lengths of input utterances (B,)
|
| 257 |
-
"""
|
| 258 |
-
bsz, max_seq_len, _ = src_tokens.size()
|
| 259 |
-
# (B, C, T, feat)
|
| 260 |
-
x = (
|
| 261 |
-
src_tokens.view(bsz, max_seq_len, self.in_channels, self.input_dim)
|
| 262 |
-
.transpose(1, 2)
|
| 263 |
-
.contiguous()
|
| 264 |
-
)
|
| 265 |
-
|
| 266 |
-
for input_layer in self.input_layers:
|
| 267 |
-
x = input_layer(x)
|
| 268 |
-
x = torch.tanh(x)
|
| 269 |
-
|
| 270 |
-
for conv_layer in self.conv_layers:
|
| 271 |
-
x = conv_layer(x)
|
| 272 |
-
|
| 273 |
-
bsz, _, output_seq_len, _ = x.size()
|
| 274 |
-
|
| 275 |
-
# (B, C, T, feat) -> (B, T, C, feat) -> (T, B, C, feat) ->
|
| 276 |
-
# (T, B, C * feat)
|
| 277 |
-
x = x.transpose(1, 2).transpose(0, 1).contiguous().view(output_seq_len, bsz, -1)
|
| 278 |
-
|
| 279 |
-
input_lengths = src_lengths.clone()
|
| 280 |
-
for k, s in self.conv_kernel_sizes_and_strides:
|
| 281 |
-
p = k // 2
|
| 282 |
-
input_lengths = (input_lengths.float() + 2 * p - k) / s + 1
|
| 283 |
-
input_lengths = input_lengths.floor().long()
|
| 284 |
-
|
| 285 |
-
packed_x = nn.utils.rnn.pack_padded_sequence(x, input_lengths)
|
| 286 |
-
|
| 287 |
-
h0 = x.new(2 * self.num_blstm_layers, bsz, self.lstm_size).zero_()
|
| 288 |
-
c0 = x.new(2 * self.num_blstm_layers, bsz, self.lstm_size).zero_()
|
| 289 |
-
packed_outs, _ = self.lstm(packed_x, (h0, c0))
|
| 290 |
-
|
| 291 |
-
# unpack outputs and apply dropout
|
| 292 |
-
x, output_lengths = nn.utils.rnn.pad_packed_sequence(packed_outs)
|
| 293 |
-
if self.dropout is not None:
|
| 294 |
-
x = self.dropout(x)
|
| 295 |
-
|
| 296 |
-
encoder_padding_mask = (
|
| 297 |
-
lengths_to_padding_mask(output_lengths).to(src_tokens.device).t()
|
| 298 |
-
)
|
| 299 |
-
|
| 300 |
-
return {
|
| 301 |
-
"encoder_out": x, # (T, B, C)
|
| 302 |
-
"encoder_padding_mask": encoder_padding_mask, # (T, B)
|
| 303 |
-
}
|
| 304 |
-
|
| 305 |
-
def reorder_encoder_out(self, encoder_out, new_order):
|
| 306 |
-
encoder_out["encoder_out"] = encoder_out["encoder_out"].index_select(
|
| 307 |
-
1, new_order
|
| 308 |
-
)
|
| 309 |
-
encoder_out["encoder_padding_mask"] = encoder_out[
|
| 310 |
-
"encoder_padding_mask"
|
| 311 |
-
].index_select(1, new_order)
|
| 312 |
-
return encoder_out
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
class MLPAttention(nn.Module):
|
| 316 |
-
"""The original attention from Badhanau et al. (2014)
|
| 317 |
-
|
| 318 |
-
https://arxiv.org/abs/1409.0473, based on a Multi-Layer Perceptron.
|
| 319 |
-
The attention score between position i in the encoder and position j in the
|
| 320 |
-
decoder is: alpha_ij = V_a * tanh(W_ae * enc_i + W_ad * dec_j + b_a)
|
| 321 |
-
"""
|
| 322 |
-
|
| 323 |
-
def __init__(self, decoder_hidden_state_dim, context_dim, attention_dim):
|
| 324 |
-
super().__init__()
|
| 325 |
-
|
| 326 |
-
self.context_dim = context_dim
|
| 327 |
-
self.attention_dim = attention_dim
|
| 328 |
-
# W_ae and b_a
|
| 329 |
-
self.encoder_proj = nn.Linear(context_dim, self.attention_dim, bias=True)
|
| 330 |
-
# W_ad
|
| 331 |
-
self.decoder_proj = nn.Linear(
|
| 332 |
-
decoder_hidden_state_dim, self.attention_dim, bias=False
|
| 333 |
-
)
|
| 334 |
-
# V_a
|
| 335 |
-
self.to_scores = nn.Linear(self.attention_dim, 1, bias=False)
|
| 336 |
-
|
| 337 |
-
def forward(self, decoder_state, source_hids, encoder_padding_mask):
|
| 338 |
-
"""The expected input dimensions are:
|
| 339 |
-
decoder_state: bsz x decoder_hidden_state_dim
|
| 340 |
-
source_hids: src_len x bsz x context_dim
|
| 341 |
-
encoder_padding_mask: src_len x bsz
|
| 342 |
-
"""
|
| 343 |
-
src_len, bsz, _ = source_hids.size()
|
| 344 |
-
# (src_len*bsz) x context_dim (to feed through linear)
|
| 345 |
-
flat_source_hids = source_hids.view(-1, self.context_dim)
|
| 346 |
-
# (src_len*bsz) x attention_dim
|
| 347 |
-
encoder_component = self.encoder_proj(flat_source_hids)
|
| 348 |
-
# src_len x bsz x attention_dim
|
| 349 |
-
encoder_component = encoder_component.view(src_len, bsz, self.attention_dim)
|
| 350 |
-
# 1 x bsz x attention_dim
|
| 351 |
-
decoder_component = self.decoder_proj(decoder_state).unsqueeze(0)
|
| 352 |
-
# Sum with broadcasting and apply the non linearity
|
| 353 |
-
# src_len x bsz x attention_dim
|
| 354 |
-
hidden_att = torch.tanh(
|
| 355 |
-
(decoder_component + encoder_component).view(-1, self.attention_dim)
|
| 356 |
-
)
|
| 357 |
-
# Project onto the reals to get attentions scores (src_len x bsz)
|
| 358 |
-
attn_scores = self.to_scores(hidden_att).view(src_len, bsz)
|
| 359 |
-
|
| 360 |
-
# Mask + softmax (src_len x bsz)
|
| 361 |
-
if encoder_padding_mask is not None:
|
| 362 |
-
attn_scores = (
|
| 363 |
-
attn_scores.float()
|
| 364 |
-
.masked_fill_(encoder_padding_mask, float("-inf"))
|
| 365 |
-
.type_as(attn_scores)
|
| 366 |
-
) # FP16 support: cast to float and back
|
| 367 |
-
# srclen x bsz
|
| 368 |
-
normalized_masked_attn_scores = F.softmax(attn_scores, dim=0)
|
| 369 |
-
|
| 370 |
-
# Sum weighted sources (bsz x context_dim)
|
| 371 |
-
attn_weighted_context = (
|
| 372 |
-
source_hids * normalized_masked_attn_scores.unsqueeze(2)
|
| 373 |
-
).sum(dim=0)
|
| 374 |
-
|
| 375 |
-
return attn_weighted_context, normalized_masked_attn_scores
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
class LSTMDecoder(FairseqIncrementalDecoder):
|
| 379 |
-
def __init__(
|
| 380 |
-
self,
|
| 381 |
-
dictionary,
|
| 382 |
-
embed_dim,
|
| 383 |
-
num_layers,
|
| 384 |
-
hidden_size,
|
| 385 |
-
dropout,
|
| 386 |
-
encoder_output_dim,
|
| 387 |
-
attention_dim,
|
| 388 |
-
output_layer_dim,
|
| 389 |
-
):
|
| 390 |
-
"""
|
| 391 |
-
Args:
|
| 392 |
-
dictionary: target text dictionary.
|
| 393 |
-
embed_dim: embedding dimension for target tokens.
|
| 394 |
-
num_layers: number of LSTM layers.
|
| 395 |
-
hidden_size: hidden size for LSTM layers.
|
| 396 |
-
dropout: dropout probability. Dropout can be applied to the
|
| 397 |
-
embeddings, the LSTM layers, and the context vector.
|
| 398 |
-
encoder_output_dim: encoder output dimension (hidden size of
|
| 399 |
-
encoder LSTM).
|
| 400 |
-
attention_dim: attention dimension for MLP attention.
|
| 401 |
-
output_layer_dim: size of the linear layer prior to output
|
| 402 |
-
projection.
|
| 403 |
-
"""
|
| 404 |
-
super().__init__(dictionary)
|
| 405 |
-
self.num_layers = num_layers
|
| 406 |
-
self.hidden_size = hidden_size
|
| 407 |
-
num_embeddings = len(dictionary)
|
| 408 |
-
padding_idx = dictionary.pad()
|
| 409 |
-
self.embed_tokens = nn.Embedding(num_embeddings, embed_dim, padding_idx)
|
| 410 |
-
if dropout > 0:
|
| 411 |
-
self.dropout = nn.Dropout(p=dropout)
|
| 412 |
-
else:
|
| 413 |
-
self.dropout = None
|
| 414 |
-
|
| 415 |
-
self.layers = nn.ModuleList()
|
| 416 |
-
for layer_id in range(num_layers):
|
| 417 |
-
input_size = embed_dim if layer_id == 0 else encoder_output_dim
|
| 418 |
-
self.layers.append(
|
| 419 |
-
nn.LSTMCell(input_size=input_size, hidden_size=hidden_size)
|
| 420 |
-
)
|
| 421 |
-
|
| 422 |
-
self.context_dim = encoder_output_dim
|
| 423 |
-
self.attention = MLPAttention(
|
| 424 |
-
decoder_hidden_state_dim=hidden_size,
|
| 425 |
-
context_dim=encoder_output_dim,
|
| 426 |
-
attention_dim=attention_dim,
|
| 427 |
-
)
|
| 428 |
-
|
| 429 |
-
self.deep_output_layer = nn.Linear(
|
| 430 |
-
hidden_size + encoder_output_dim + embed_dim, output_layer_dim
|
| 431 |
-
)
|
| 432 |
-
self.output_projection = nn.Linear(output_layer_dim, num_embeddings)
|
| 433 |
-
|
| 434 |
-
def forward(
|
| 435 |
-
self, prev_output_tokens, encoder_out=None, incremental_state=None, **kwargs
|
| 436 |
-
):
|
| 437 |
-
encoder_padding_mask = encoder_out["encoder_padding_mask"]
|
| 438 |
-
encoder_outs = encoder_out["encoder_out"]
|
| 439 |
-
|
| 440 |
-
if incremental_state is not None:
|
| 441 |
-
prev_output_tokens = prev_output_tokens[:, -1:]
|
| 442 |
-
bsz, seqlen = prev_output_tokens.size()
|
| 443 |
-
|
| 444 |
-
srclen = encoder_outs.size(0)
|
| 445 |
-
|
| 446 |
-
# embed tokens
|
| 447 |
-
embeddings = self.embed_tokens(prev_output_tokens)
|
| 448 |
-
x = embeddings
|
| 449 |
-
if self.dropout is not None:
|
| 450 |
-
x = self.dropout(x)
|
| 451 |
-
|
| 452 |
-
# B x T x C -> T x B x C
|
| 453 |
-
x = x.transpose(0, 1)
|
| 454 |
-
|
| 455 |
-
# initialize previous states (or get from cache during incremental
|
| 456 |
-
# generation)
|
| 457 |
-
cached_state = utils.get_incremental_state(
|
| 458 |
-
self, incremental_state, "cached_state"
|
| 459 |
-
)
|
| 460 |
-
if cached_state is not None:
|
| 461 |
-
prev_hiddens, prev_cells = cached_state
|
| 462 |
-
else:
|
| 463 |
-
prev_hiddens = [encoder_out["encoder_out"].mean(dim=0)] * self.num_layers
|
| 464 |
-
prev_cells = [x.new_zeros(bsz, self.hidden_size)] * self.num_layers
|
| 465 |
-
|
| 466 |
-
attn_scores = x.new_zeros(bsz, srclen)
|
| 467 |
-
attention_outs = []
|
| 468 |
-
outs = []
|
| 469 |
-
for j in range(seqlen):
|
| 470 |
-
input = x[j, :, :]
|
| 471 |
-
attention_out = None
|
| 472 |
-
for i, layer in enumerate(self.layers):
|
| 473 |
-
# the previous state is one layer below except for the bottom
|
| 474 |
-
# layer where the previous state is the state emitted by the
|
| 475 |
-
# top layer
|
| 476 |
-
hidden, cell = layer(
|
| 477 |
-
input,
|
| 478 |
-
(
|
| 479 |
-
prev_hiddens[(i - 1) % self.num_layers],
|
| 480 |
-
prev_cells[(i - 1) % self.num_layers],
|
| 481 |
-
),
|
| 482 |
-
)
|
| 483 |
-
if self.dropout is not None:
|
| 484 |
-
hidden = self.dropout(hidden)
|
| 485 |
-
prev_hiddens[i] = hidden
|
| 486 |
-
prev_cells[i] = cell
|
| 487 |
-
if attention_out is None:
|
| 488 |
-
attention_out, attn_scores = self.attention(
|
| 489 |
-
hidden, encoder_outs, encoder_padding_mask
|
| 490 |
-
)
|
| 491 |
-
if self.dropout is not None:
|
| 492 |
-
attention_out = self.dropout(attention_out)
|
| 493 |
-
attention_outs.append(attention_out)
|
| 494 |
-
input = attention_out
|
| 495 |
-
|
| 496 |
-
# collect the output of the top layer
|
| 497 |
-
outs.append(hidden)
|
| 498 |
-
|
| 499 |
-
# cache previous states (no-op except during incremental generation)
|
| 500 |
-
utils.set_incremental_state(
|
| 501 |
-
self, incremental_state, "cached_state", (prev_hiddens, prev_cells)
|
| 502 |
-
)
|
| 503 |
-
|
| 504 |
-
# collect outputs across time steps
|
| 505 |
-
x = torch.cat(outs, dim=0).view(seqlen, bsz, self.hidden_size)
|
| 506 |
-
attention_outs_concat = torch.cat(attention_outs, dim=0).view(
|
| 507 |
-
seqlen, bsz, self.context_dim
|
| 508 |
-
)
|
| 509 |
-
|
| 510 |
-
# T x B x C -> B x T x C
|
| 511 |
-
x = x.transpose(0, 1)
|
| 512 |
-
attention_outs_concat = attention_outs_concat.transpose(0, 1)
|
| 513 |
-
|
| 514 |
-
# concat LSTM output, attention output and embedding
|
| 515 |
-
# before output projection
|
| 516 |
-
x = torch.cat((x, attention_outs_concat, embeddings), dim=2)
|
| 517 |
-
x = self.deep_output_layer(x)
|
| 518 |
-
x = torch.tanh(x)
|
| 519 |
-
if self.dropout is not None:
|
| 520 |
-
x = self.dropout(x)
|
| 521 |
-
# project back to size of vocabulary
|
| 522 |
-
x = self.output_projection(x)
|
| 523 |
-
|
| 524 |
-
# to return the full attn_scores tensor, we need to fix the decoder
|
| 525 |
-
# to account for subsampling input frames
|
| 526 |
-
# return x, attn_scores
|
| 527 |
-
return x, None
|
| 528 |
-
|
| 529 |
-
def reorder_incremental_state(self, incremental_state, new_order):
|
| 530 |
-
super().reorder_incremental_state(incremental_state, new_order)
|
| 531 |
-
cached_state = utils.get_incremental_state(
|
| 532 |
-
self, incremental_state, "cached_state"
|
| 533 |
-
)
|
| 534 |
-
if cached_state is None:
|
| 535 |
-
return
|
| 536 |
-
|
| 537 |
-
def reorder_state(state):
|
| 538 |
-
if isinstance(state, list):
|
| 539 |
-
return [reorder_state(state_i) for state_i in state]
|
| 540 |
-
return state.index_select(0, new_order)
|
| 541 |
-
|
| 542 |
-
new_state = tuple(map(reorder_state, cached_state))
|
| 543 |
-
utils.set_incremental_state(self, incremental_state, "cached_state", new_state)
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
@register_model_architecture(model_name="s2t_berard", arch_name="s2t_berard")
|
| 547 |
-
def berard(args):
|
| 548 |
-
"""The original version: "End-to-End Automatic Speech Translation of
|
| 549 |
-
Audiobooks" (https://arxiv.org/abs/1802.04200)
|
| 550 |
-
"""
|
| 551 |
-
args.input_layers = getattr(args, "input_layers", "[256, 128]")
|
| 552 |
-
args.conv_layers = getattr(args, "conv_layers", "[(16, 3, 2), (16, 3, 2)]")
|
| 553 |
-
args.num_blstm_layers = getattr(args, "num_blstm_layers", 3)
|
| 554 |
-
args.lstm_size = getattr(args, "lstm_size", 256)
|
| 555 |
-
args.dropout = getattr(args, "dropout", 0.2)
|
| 556 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 128)
|
| 557 |
-
args.decoder_num_layers = getattr(args, "decoder_num_layers", 2)
|
| 558 |
-
args.decoder_hidden_dim = getattr(args, "decoder_hidden_dim", 512)
|
| 559 |
-
args.attention_dim = getattr(args, "attention_dim", 512)
|
| 560 |
-
args.output_layer_dim = getattr(args, "output_layer_dim", 128)
|
| 561 |
-
args.load_pretrained_encoder_from = getattr(
|
| 562 |
-
args, "load_pretrained_encoder_from", None
|
| 563 |
-
)
|
| 564 |
-
args.load_pretrained_decoder_from = getattr(
|
| 565 |
-
args, "load_pretrained_decoder_from", None
|
| 566 |
-
)
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
@register_model_architecture(model_name="s2t_berard", arch_name="s2t_berard_256_3_3")
|
| 570 |
-
def berard_256_3_3(args):
|
| 571 |
-
"""Used in
|
| 572 |
-
* "Harnessing Indirect Training Data for End-to-End Automatic Speech
|
| 573 |
-
Translation: Tricks of the Trade" (https://arxiv.org/abs/1909.06515)
|
| 574 |
-
* "CoVoST: A Diverse Multilingual Speech-To-Text Translation Corpus"
|
| 575 |
-
(https://arxiv.org/pdf/2002.01320.pdf)
|
| 576 |
-
* "Self-Supervised Representations Improve End-to-End Speech Translation"
|
| 577 |
-
(https://arxiv.org/abs/2006.12124)
|
| 578 |
-
"""
|
| 579 |
-
args.decoder_num_layers = getattr(args, "decoder_num_layers", 3)
|
| 580 |
-
berard(args)
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
@register_model_architecture(model_name="s2t_berard", arch_name="s2t_berard_512_3_2")
|
| 584 |
-
def berard_512_3_2(args):
|
| 585 |
-
args.num_blstm_layers = getattr(args, "num_blstm_layers", 3)
|
| 586 |
-
args.lstm_size = getattr(args, "lstm_size", 512)
|
| 587 |
-
args.dropout = getattr(args, "dropout", 0.3)
|
| 588 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 256)
|
| 589 |
-
args.decoder_num_layers = getattr(args, "decoder_num_layers", 2)
|
| 590 |
-
args.decoder_hidden_dim = getattr(args, "decoder_hidden_dim", 1024)
|
| 591 |
-
args.attention_dim = getattr(args, "attention_dim", 512)
|
| 592 |
-
args.output_layer_dim = getattr(args, "output_layer_dim", 256)
|
| 593 |
-
berard(args)
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
@register_model_architecture(model_name="s2t_berard", arch_name="s2t_berard_512_5_3")
|
| 597 |
-
def berard_512_5_3(args):
|
| 598 |
-
args.num_blstm_layers = getattr(args, "num_blstm_layers", 5)
|
| 599 |
-
args.lstm_size = getattr(args, "lstm_size", 512)
|
| 600 |
-
args.dropout = getattr(args, "dropout", 0.3)
|
| 601 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 256)
|
| 602 |
-
args.decoder_num_layers = getattr(args, "decoder_num_layers", 3)
|
| 603 |
-
args.decoder_hidden_dim = getattr(args, "decoder_hidden_dim", 1024)
|
| 604 |
-
args.attention_dim = getattr(args, "attention_dim", 512)
|
| 605 |
-
args.output_layer_dim = getattr(args, "output_layer_dim", 256)
|
| 606 |
-
berard(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_text/convtransformer.py
DELETED
|
@@ -1,448 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
|
| 3 |
-
import logging
|
| 4 |
-
import math
|
| 5 |
-
from typing import Dict, List, Optional, Tuple
|
| 6 |
-
|
| 7 |
-
import torch
|
| 8 |
-
import torch.nn as nn
|
| 9 |
-
import torch.nn.functional as F
|
| 10 |
-
from fairseq import checkpoint_utils, utils
|
| 11 |
-
from fairseq.data.data_utils import lengths_to_padding_mask
|
| 12 |
-
from fairseq.models import (
|
| 13 |
-
FairseqEncoder,
|
| 14 |
-
FairseqEncoderDecoderModel,
|
| 15 |
-
register_model,
|
| 16 |
-
register_model_architecture,
|
| 17 |
-
)
|
| 18 |
-
from fairseq.models.transformer import Embedding, TransformerDecoder
|
| 19 |
-
from fairseq.modules import LayerNorm, PositionalEmbedding, TransformerEncoderLayer
|
| 20 |
-
from torch import Tensor
|
| 21 |
-
|
| 22 |
-
logger = logging.getLogger(__name__)
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
@register_model("convtransformer")
|
| 26 |
-
class ConvTransformerModel(FairseqEncoderDecoderModel):
|
| 27 |
-
"""
|
| 28 |
-
Transformer-based Speech translation model from ESPNet-ST
|
| 29 |
-
https://arxiv.org/abs/2004.10234
|
| 30 |
-
"""
|
| 31 |
-
|
| 32 |
-
def __init__(self, encoder, decoder):
|
| 33 |
-
super().__init__(encoder, decoder)
|
| 34 |
-
|
| 35 |
-
@staticmethod
|
| 36 |
-
def add_args(parser):
|
| 37 |
-
"""Add model-specific arguments to the parser."""
|
| 38 |
-
parser.add_argument(
|
| 39 |
-
"--input-feat-per-channel",
|
| 40 |
-
type=int,
|
| 41 |
-
metavar="N",
|
| 42 |
-
help="encoder input dimension per input channel",
|
| 43 |
-
)
|
| 44 |
-
parser.add_argument(
|
| 45 |
-
"--activation-fn",
|
| 46 |
-
choices=utils.get_available_activation_fns(),
|
| 47 |
-
help="activation function to use",
|
| 48 |
-
)
|
| 49 |
-
parser.add_argument(
|
| 50 |
-
"--dropout", type=float, metavar="D", help="dropout probability"
|
| 51 |
-
)
|
| 52 |
-
parser.add_argument(
|
| 53 |
-
"--attention-dropout",
|
| 54 |
-
type=float,
|
| 55 |
-
metavar="D",
|
| 56 |
-
help="dropout probability for attention weights",
|
| 57 |
-
)
|
| 58 |
-
parser.add_argument(
|
| 59 |
-
"--activation-dropout",
|
| 60 |
-
"--relu-dropout",
|
| 61 |
-
type=float,
|
| 62 |
-
metavar="D",
|
| 63 |
-
help="dropout probability after activation in FFN.",
|
| 64 |
-
)
|
| 65 |
-
parser.add_argument(
|
| 66 |
-
"--encoder-embed-dim",
|
| 67 |
-
type=int,
|
| 68 |
-
metavar="N",
|
| 69 |
-
help="encoder embedding dimension",
|
| 70 |
-
)
|
| 71 |
-
parser.add_argument(
|
| 72 |
-
"--encoder-ffn-embed-dim",
|
| 73 |
-
type=int,
|
| 74 |
-
metavar="N",
|
| 75 |
-
help="encoder embedding dimension for FFN",
|
| 76 |
-
)
|
| 77 |
-
parser.add_argument(
|
| 78 |
-
"--encoder-layers", type=int, metavar="N", help="num encoder layers"
|
| 79 |
-
)
|
| 80 |
-
parser.add_argument(
|
| 81 |
-
"--encoder-attention-heads",
|
| 82 |
-
type=int,
|
| 83 |
-
metavar="N",
|
| 84 |
-
help="num encoder attention heads",
|
| 85 |
-
)
|
| 86 |
-
parser.add_argument(
|
| 87 |
-
"--encoder-normalize-before",
|
| 88 |
-
action="store_true",
|
| 89 |
-
help="apply layernorm before each encoder block",
|
| 90 |
-
)
|
| 91 |
-
parser.add_argument(
|
| 92 |
-
"--decoder-embed-dim",
|
| 93 |
-
type=int,
|
| 94 |
-
metavar="N",
|
| 95 |
-
help="decoder embedding dimension",
|
| 96 |
-
)
|
| 97 |
-
parser.add_argument(
|
| 98 |
-
"--decoder-ffn-embed-dim",
|
| 99 |
-
type=int,
|
| 100 |
-
metavar="N",
|
| 101 |
-
help="decoder embedding dimension for FFN",
|
| 102 |
-
)
|
| 103 |
-
parser.add_argument(
|
| 104 |
-
"--decoder-layers", type=int, metavar="N", help="num decoder layers"
|
| 105 |
-
)
|
| 106 |
-
parser.add_argument(
|
| 107 |
-
"--decoder-attention-heads",
|
| 108 |
-
type=int,
|
| 109 |
-
metavar="N",
|
| 110 |
-
help="num decoder attention heads",
|
| 111 |
-
)
|
| 112 |
-
parser.add_argument(
|
| 113 |
-
"--decoder-normalize-before",
|
| 114 |
-
action="store_true",
|
| 115 |
-
help="apply layernorm before each decoder block",
|
| 116 |
-
)
|
| 117 |
-
parser.add_argument(
|
| 118 |
-
"--decoder-output-dim",
|
| 119 |
-
type=int,
|
| 120 |
-
metavar="N",
|
| 121 |
-
help="decoder output dimension (extra linear layer if different from decoder embed dim)",
|
| 122 |
-
)
|
| 123 |
-
parser.add_argument(
|
| 124 |
-
"--share-decoder-input-output-embed",
|
| 125 |
-
action="store_true",
|
| 126 |
-
help="share decoder input and output embeddings",
|
| 127 |
-
)
|
| 128 |
-
parser.add_argument(
|
| 129 |
-
"--layernorm-embedding",
|
| 130 |
-
action="store_true",
|
| 131 |
-
help="add layernorm to embedding",
|
| 132 |
-
)
|
| 133 |
-
parser.add_argument(
|
| 134 |
-
"--no-scale-embedding",
|
| 135 |
-
action="store_true",
|
| 136 |
-
help="if True, dont scale embeddings",
|
| 137 |
-
)
|
| 138 |
-
parser.add_argument(
|
| 139 |
-
"--load-pretrained-encoder-from",
|
| 140 |
-
type=str,
|
| 141 |
-
metavar="STR",
|
| 142 |
-
help="model to take encoder weights from (for initialization)",
|
| 143 |
-
)
|
| 144 |
-
parser.add_argument(
|
| 145 |
-
"--load-pretrained-decoder-from",
|
| 146 |
-
type=str,
|
| 147 |
-
metavar="STR",
|
| 148 |
-
help="model to take decoder weights from (for initialization)",
|
| 149 |
-
)
|
| 150 |
-
parser.add_argument(
|
| 151 |
-
"--conv-out-channels",
|
| 152 |
-
type=int,
|
| 153 |
-
metavar="INT",
|
| 154 |
-
help="the number of output channels of conv layer",
|
| 155 |
-
)
|
| 156 |
-
|
| 157 |
-
@classmethod
|
| 158 |
-
def build_encoder(cls, args):
|
| 159 |
-
encoder = ConvTransformerEncoder(args)
|
| 160 |
-
if getattr(args, "load_pretrained_encoder_from", None):
|
| 161 |
-
encoder = checkpoint_utils.load_pretrained_component_from_model(
|
| 162 |
-
component=encoder, checkpoint=args.load_pretrained_encoder_from
|
| 163 |
-
)
|
| 164 |
-
return encoder
|
| 165 |
-
|
| 166 |
-
@classmethod
|
| 167 |
-
def build_decoder(cls, args, task, embed_tokens):
|
| 168 |
-
decoder = TransformerDecoderNoExtra(args, task.target_dictionary, embed_tokens)
|
| 169 |
-
if getattr(args, "load_pretrained_decoder_from", None):
|
| 170 |
-
decoder = checkpoint_utils.load_pretrained_component_from_model(
|
| 171 |
-
component=decoder, checkpoint=args.load_pretrained_decoder_from
|
| 172 |
-
)
|
| 173 |
-
return decoder
|
| 174 |
-
|
| 175 |
-
@classmethod
|
| 176 |
-
def build_model(cls, args, task):
|
| 177 |
-
"""Build a new model instance."""
|
| 178 |
-
|
| 179 |
-
# make sure all arguments are present in older models
|
| 180 |
-
base_architecture(args)
|
| 181 |
-
|
| 182 |
-
def build_embedding(dictionary, embed_dim):
|
| 183 |
-
num_embeddings = len(dictionary)
|
| 184 |
-
padding_idx = dictionary.pad()
|
| 185 |
-
return Embedding(num_embeddings, embed_dim, padding_idx)
|
| 186 |
-
|
| 187 |
-
decoder_embed_tokens = build_embedding(
|
| 188 |
-
task.target_dictionary, args.decoder_embed_dim
|
| 189 |
-
)
|
| 190 |
-
encoder = cls.build_encoder(args)
|
| 191 |
-
decoder = cls.build_decoder(args, task, decoder_embed_tokens)
|
| 192 |
-
return cls(encoder, decoder)
|
| 193 |
-
|
| 194 |
-
@staticmethod
|
| 195 |
-
@torch.jit.unused
|
| 196 |
-
def set_batch_first(lprobs):
|
| 197 |
-
lprobs.batch_first = True
|
| 198 |
-
|
| 199 |
-
def get_normalized_probs(
|
| 200 |
-
self,
|
| 201 |
-
net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]],
|
| 202 |
-
log_probs: bool,
|
| 203 |
-
sample: Optional[Dict[str, Tensor]] = None,
|
| 204 |
-
):
|
| 205 |
-
# net_output['encoder_out'] is a (B, T, D) tensor
|
| 206 |
-
lprobs = self.get_normalized_probs_scriptable(net_output, log_probs, sample)
|
| 207 |
-
if self.training:
|
| 208 |
-
self.set_batch_first(lprobs)
|
| 209 |
-
return lprobs
|
| 210 |
-
|
| 211 |
-
def output_layout(self):
|
| 212 |
-
return "BTD"
|
| 213 |
-
|
| 214 |
-
"""
|
| 215 |
-
The forward method inherited from the base class has a **kwargs argument in
|
| 216 |
-
its input, which is not supported in torchscript. This method overrites the forward
|
| 217 |
-
method definition without **kwargs.
|
| 218 |
-
"""
|
| 219 |
-
|
| 220 |
-
def forward(self, src_tokens, src_lengths, prev_output_tokens):
|
| 221 |
-
encoder_out = self.encoder(src_tokens=src_tokens, src_lengths=src_lengths)
|
| 222 |
-
decoder_out = self.decoder(
|
| 223 |
-
prev_output_tokens=prev_output_tokens, encoder_out=encoder_out
|
| 224 |
-
)
|
| 225 |
-
return decoder_out
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
class ConvTransformerEncoder(FairseqEncoder):
|
| 229 |
-
"""Conv + Transformer encoder"""
|
| 230 |
-
|
| 231 |
-
def __init__(self, args):
|
| 232 |
-
"""Construct an Encoder object."""
|
| 233 |
-
super().__init__(None)
|
| 234 |
-
|
| 235 |
-
self.dropout = args.dropout
|
| 236 |
-
self.embed_scale = (
|
| 237 |
-
1.0 if args.no_scale_embedding else math.sqrt(args.encoder_embed_dim)
|
| 238 |
-
)
|
| 239 |
-
self.padding_idx = 1
|
| 240 |
-
self.in_channels = 1
|
| 241 |
-
self.input_dim = args.input_feat_per_channel
|
| 242 |
-
self.conv = torch.nn.Sequential(
|
| 243 |
-
torch.nn.Conv2d(1, args.conv_out_channels, 3, stride=2, padding=3 // 2),
|
| 244 |
-
torch.nn.ReLU(),
|
| 245 |
-
torch.nn.Conv2d(
|
| 246 |
-
args.conv_out_channels,
|
| 247 |
-
args.conv_out_channels,
|
| 248 |
-
3,
|
| 249 |
-
stride=2,
|
| 250 |
-
padding=3 // 2,
|
| 251 |
-
),
|
| 252 |
-
torch.nn.ReLU(),
|
| 253 |
-
)
|
| 254 |
-
transformer_input_dim = self.infer_conv_output_dim(
|
| 255 |
-
self.in_channels, self.input_dim, args.conv_out_channels
|
| 256 |
-
)
|
| 257 |
-
self.out = torch.nn.Linear(transformer_input_dim, args.encoder_embed_dim)
|
| 258 |
-
self.embed_positions = PositionalEmbedding(
|
| 259 |
-
args.max_source_positions,
|
| 260 |
-
args.encoder_embed_dim,
|
| 261 |
-
self.padding_idx,
|
| 262 |
-
learned=False,
|
| 263 |
-
)
|
| 264 |
-
|
| 265 |
-
self.transformer_layers = nn.ModuleList([])
|
| 266 |
-
self.transformer_layers.extend(
|
| 267 |
-
[TransformerEncoderLayer(args) for i in range(args.encoder_layers)]
|
| 268 |
-
)
|
| 269 |
-
if args.encoder_normalize_before:
|
| 270 |
-
self.layer_norm = LayerNorm(args.encoder_embed_dim)
|
| 271 |
-
else:
|
| 272 |
-
self.layer_norm = None
|
| 273 |
-
|
| 274 |
-
def pooling_ratio(self):
|
| 275 |
-
return 4
|
| 276 |
-
|
| 277 |
-
def infer_conv_output_dim(self, in_channels, input_dim, out_channels):
|
| 278 |
-
sample_seq_len = 200
|
| 279 |
-
sample_bsz = 10
|
| 280 |
-
x = torch.randn(sample_bsz, in_channels, sample_seq_len, input_dim)
|
| 281 |
-
x = torch.nn.Conv2d(1, out_channels, 3, stride=2, padding=3 // 2)(x)
|
| 282 |
-
x = torch.nn.Conv2d(out_channels, out_channels, 3, stride=2, padding=3 // 2)(x)
|
| 283 |
-
x = x.transpose(1, 2)
|
| 284 |
-
mb, seq = x.size()[:2]
|
| 285 |
-
return x.contiguous().view(mb, seq, -1).size(-1)
|
| 286 |
-
|
| 287 |
-
def forward(self, src_tokens, src_lengths):
|
| 288 |
-
"""Encode input sequence.
|
| 289 |
-
:param torch.Tensor xs: input tensor
|
| 290 |
-
:param torch.Tensor masks: input mask
|
| 291 |
-
:return: position embedded tensor and mask
|
| 292 |
-
:rtype Tuple[torch.Tensor, torch.Tensor]:
|
| 293 |
-
"""
|
| 294 |
-
bsz, max_seq_len, _ = src_tokens.size()
|
| 295 |
-
x = (
|
| 296 |
-
src_tokens.view(bsz, max_seq_len, self.in_channels, self.input_dim)
|
| 297 |
-
.transpose(1, 2)
|
| 298 |
-
.contiguous()
|
| 299 |
-
)
|
| 300 |
-
x = self.conv(x)
|
| 301 |
-
bsz, _, output_seq_len, _ = x.size()
|
| 302 |
-
x = x.transpose(1, 2).transpose(0, 1).contiguous().view(output_seq_len, bsz, -1)
|
| 303 |
-
x = self.out(x)
|
| 304 |
-
x = self.embed_scale * x
|
| 305 |
-
|
| 306 |
-
subsampling_factor = int(max_seq_len * 1.0 / output_seq_len + 0.5)
|
| 307 |
-
input_len_0 = (src_lengths.float() / subsampling_factor).ceil().long()
|
| 308 |
-
input_len_1 = x.size(0) * torch.ones([src_lengths.size(0)]).long().to(
|
| 309 |
-
input_len_0.device
|
| 310 |
-
)
|
| 311 |
-
input_lengths = torch.min(input_len_0, input_len_1)
|
| 312 |
-
|
| 313 |
-
encoder_padding_mask = lengths_to_padding_mask(input_lengths)
|
| 314 |
-
|
| 315 |
-
positions = self.embed_positions(encoder_padding_mask).transpose(0, 1)
|
| 316 |
-
x += positions
|
| 317 |
-
x = F.dropout(x, p=self.dropout, training=self.training)
|
| 318 |
-
|
| 319 |
-
for layer in self.transformer_layers:
|
| 320 |
-
x = layer(x, encoder_padding_mask)
|
| 321 |
-
|
| 322 |
-
if not encoder_padding_mask.any():
|
| 323 |
-
maybe_encoder_padding_mask = None
|
| 324 |
-
else:
|
| 325 |
-
maybe_encoder_padding_mask = encoder_padding_mask
|
| 326 |
-
|
| 327 |
-
return {
|
| 328 |
-
"encoder_out": [x],
|
| 329 |
-
"encoder_padding_mask": [maybe_encoder_padding_mask]
|
| 330 |
-
if maybe_encoder_padding_mask is not None
|
| 331 |
-
else [],
|
| 332 |
-
"encoder_embedding": [],
|
| 333 |
-
"encoder_states": [],
|
| 334 |
-
"src_tokens": [],
|
| 335 |
-
"src_lengths": [],
|
| 336 |
-
}
|
| 337 |
-
|
| 338 |
-
@torch.jit.export
|
| 339 |
-
def reorder_encoder_out(self, encoder_out: Dict[str, List[Tensor]], new_order):
|
| 340 |
-
"""
|
| 341 |
-
Reorder encoder output according to *new_order*.
|
| 342 |
-
|
| 343 |
-
Args:
|
| 344 |
-
encoder_out: output from the ``forward()`` method
|
| 345 |
-
new_order (LongTensor): desired order
|
| 346 |
-
|
| 347 |
-
Returns:
|
| 348 |
-
*encoder_out* rearranged according to *new_order*
|
| 349 |
-
"""
|
| 350 |
-
new_encoder_out = [encoder_out["encoder_out"][0].index_select(1, new_order)]
|
| 351 |
-
if len(encoder_out["encoder_padding_mask"]) == 0:
|
| 352 |
-
new_encoder_padding_mask = []
|
| 353 |
-
else:
|
| 354 |
-
new_encoder_padding_mask = [
|
| 355 |
-
(encoder_out["encoder_padding_mask"][0]).index_select(0, new_order)
|
| 356 |
-
]
|
| 357 |
-
if len(encoder_out["encoder_embedding"]) == 0:
|
| 358 |
-
new_encoder_embedding = []
|
| 359 |
-
else:
|
| 360 |
-
new_encoder_embedding = [
|
| 361 |
-
(encoder_out["encoder_embedding"][0]).index_select(0, new_order)
|
| 362 |
-
]
|
| 363 |
-
encoder_states = encoder_out["encoder_states"]
|
| 364 |
-
if len(encoder_states) > 0:
|
| 365 |
-
for idx, state in enumerate(encoder_states):
|
| 366 |
-
encoder_states[idx] = state.index_select(1, new_order)
|
| 367 |
-
|
| 368 |
-
return {
|
| 369 |
-
"encoder_out": new_encoder_out,
|
| 370 |
-
"encoder_padding_mask": new_encoder_padding_mask,
|
| 371 |
-
"encoder_embedding": new_encoder_embedding,
|
| 372 |
-
"encoder_states": encoder_states,
|
| 373 |
-
"src_tokens": [],
|
| 374 |
-
"src_lengths": [],
|
| 375 |
-
}
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
class TransformerDecoderNoExtra(TransformerDecoder):
|
| 379 |
-
def extract_features(
|
| 380 |
-
self,
|
| 381 |
-
prev_output_tokens,
|
| 382 |
-
encoder_out: Optional[Dict[str, List[Tensor]]],
|
| 383 |
-
incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
|
| 384 |
-
full_context_alignment: bool = False,
|
| 385 |
-
alignment_layer: Optional[int] = None,
|
| 386 |
-
alignment_heads: Optional[int] = None,
|
| 387 |
-
):
|
| 388 |
-
# call scriptable method from parent class
|
| 389 |
-
x, _ = self.extract_features_scriptable(
|
| 390 |
-
prev_output_tokens,
|
| 391 |
-
encoder_out,
|
| 392 |
-
incremental_state,
|
| 393 |
-
full_context_alignment,
|
| 394 |
-
alignment_layer,
|
| 395 |
-
alignment_heads,
|
| 396 |
-
)
|
| 397 |
-
return x, None
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
@register_model_architecture(model_name="convtransformer", arch_name="convtransformer")
|
| 401 |
-
def base_architecture(args):
|
| 402 |
-
args.input_feat_per_channel = getattr(args, "input_feat_per_channel", 80)
|
| 403 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
|
| 404 |
-
args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 2048)
|
| 405 |
-
args.encoder_layers = getattr(args, "encoder_layers", 6)
|
| 406 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8)
|
| 407 |
-
args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
|
| 408 |
-
args.decoder_embed_dim = getattr(args, "decoder_embed_dim", args.encoder_embed_dim)
|
| 409 |
-
args.decoder_ffn_embed_dim = getattr(
|
| 410 |
-
args, "decoder_ffn_embed_dim", args.encoder_ffn_embed_dim
|
| 411 |
-
)
|
| 412 |
-
args.decoder_layers = getattr(args, "decoder_layers", 6)
|
| 413 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 8)
|
| 414 |
-
args.decoder_normalize_before = getattr(args, "decoder_normalize_before", False)
|
| 415 |
-
args.decoder_learned_pos = getattr(args, "decoder_learned_pos", False)
|
| 416 |
-
args.attention_dropout = getattr(args, "attention_dropout", 0.0)
|
| 417 |
-
args.activation_dropout = getattr(args, "activation_dropout", 0.0)
|
| 418 |
-
args.activation_fn = getattr(args, "activation_fn", "relu")
|
| 419 |
-
args.dropout = getattr(args, "dropout", 0.1)
|
| 420 |
-
args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
|
| 421 |
-
args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
|
| 422 |
-
args.share_decoder_input_output_embed = getattr(
|
| 423 |
-
args, "share_decoder_input_output_embed", False
|
| 424 |
-
)
|
| 425 |
-
args.no_token_positional_embeddings = getattr(
|
| 426 |
-
args, "no_token_positional_embeddings", False
|
| 427 |
-
)
|
| 428 |
-
args.adaptive_input = getattr(args, "adaptive_input", False)
|
| 429 |
-
args.decoder_layerdrop = getattr(args, "decoder_layerdrop", 0.0)
|
| 430 |
-
|
| 431 |
-
args.decoder_output_dim = getattr(
|
| 432 |
-
args, "decoder_output_dim", args.decoder_embed_dim
|
| 433 |
-
)
|
| 434 |
-
args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim)
|
| 435 |
-
args.no_scale_embedding = getattr(args, "no_scale_embedding", False)
|
| 436 |
-
args.quant_noise_pq = getattr(args, "quant_noise_pq", 0)
|
| 437 |
-
args.max_source_positions = getattr(args, "max_source_positions", 3000)
|
| 438 |
-
args.max_target_positions = getattr(args, "max_target_positions", 1024)
|
| 439 |
-
args.tie_adaptive_weights = getattr(args, "tie_adaptive_weights", False)
|
| 440 |
-
args.conv_out_channels = getattr(args, "conv_out_channels", args.encoder_embed_dim)
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
@register_model_architecture("convtransformer", "convtransformer_espnet")
|
| 444 |
-
def convtransformer_espnet(args):
|
| 445 |
-
args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 256)
|
| 446 |
-
args.encoder_layers = getattr(args, "encoder_layers", 12)
|
| 447 |
-
args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 4)
|
| 448 |
-
args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 4)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
audio/safeear/safeear_repo/fairseq_ours/fairseq/models/speech_to_text/hub_interface.py
DELETED
|
@@ -1,125 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
-
#
|
| 3 |
-
# This source code is licensed under the MIT license found in the
|
| 4 |
-
# LICENSE file in the root directory of this source tree.
|
| 5 |
-
|
| 6 |
-
import logging
|
| 7 |
-
from argparse import Namespace
|
| 8 |
-
from typing import Optional, Tuple, Union
|
| 9 |
-
|
| 10 |
-
import fairseq.data.audio.feature_transforms.utterance_cmvn as utt_cmvn
|
| 11 |
-
import torch
|
| 12 |
-
import torch.nn as nn
|
| 13 |
-
import torch.nn.functional as F
|
| 14 |
-
from fairseq.data import encoders
|
| 15 |
-
from fairseq.data.audio.audio_utils import convert_waveform as convert_wav
|
| 16 |
-
from fairseq.data.audio.audio_utils import (
|
| 17 |
-
get_fbank,
|
| 18 |
-
)
|
| 19 |
-
from fairseq.data.audio.audio_utils import get_waveform as get_wav
|
| 20 |
-
from fairseq.data.audio.speech_to_text_dataset import SpeechToTextDataset
|
| 21 |
-
|
| 22 |
-
logger = logging.getLogger(__name__)
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
class S2THubInterface(nn.Module):
|
| 26 |
-
def __init__(self, cfg, task, model):
|
| 27 |
-
super().__init__()
|
| 28 |
-
self.cfg = cfg
|
| 29 |
-
self.task = task
|
| 30 |
-
self.model = model
|
| 31 |
-
self.model.eval()
|
| 32 |
-
self.generator = self.task.build_generator([self.model], self.cfg)
|
| 33 |
-
|
| 34 |
-
@classmethod
|
| 35 |
-
def get_model_input(cls, task, audio: Union[str, torch.Tensor]):
|
| 36 |
-
input_type = task.data_cfg.hub.get("input_type", "fbank80")
|
| 37 |
-
if input_type == "fbank80_w_utt_cmvn":
|
| 38 |
-
if isinstance(audio, str):
|
| 39 |
-
feat = utt_cmvn.UtteranceCMVN()(get_fbank(audio))
|
| 40 |
-
feat = feat.unsqueeze(0) # T x D -> 1 x T x D
|
| 41 |
-
else:
|
| 42 |
-
import torchaudio.compliance.kaldi as kaldi
|
| 43 |
-
|
| 44 |
-
feat = kaldi.fbank(audio, num_mel_bins=80).numpy() # 1 x T x D
|
| 45 |
-
elif input_type in {"waveform", "standardized_waveform"}:
|
| 46 |
-
if isinstance(audio, str):
|
| 47 |
-
feat, sr = get_wav(audio) # C x T
|
| 48 |
-
feat, _ = convert_wav(
|
| 49 |
-
feat, sr, to_sample_rate=16_000, to_mono=True
|
| 50 |
-
) # C x T -> 1 x T
|
| 51 |
-
else:
|
| 52 |
-
feat = audio.numpy()
|
| 53 |
-
else:
|
| 54 |
-
raise ValueError(f"Unknown value: input_type = {input_type}")
|
| 55 |
-
|
| 56 |
-
src_lengths = torch.Tensor([feat.shape[1]]).long()
|
| 57 |
-
src_tokens = torch.from_numpy(feat) # 1 x T (x D)
|
| 58 |
-
if input_type == "standardized_waveform":
|
| 59 |
-
with torch.no_grad():
|
| 60 |
-
src_tokens = F.layer_norm(src_tokens, src_tokens.shape)
|
| 61 |
-
|
| 62 |
-
return {
|
| 63 |
-
"net_input": {
|
| 64 |
-
"src_tokens": src_tokens,
|
| 65 |
-
"src_lengths": src_lengths,
|
| 66 |
-
"prev_output_tokens": None,
|
| 67 |
-
},
|
| 68 |
-
"target_lengths": None,
|
| 69 |
-
"speaker": None,
|
| 70 |
-
}
|
| 71 |
-
|
| 72 |
-
@classmethod
|
| 73 |
-
def detokenize(cls, task, tokens):
|
| 74 |
-
text = task.tgt_dict.string(tokens)
|
| 75 |
-
tkn_cfg = task.data_cfg.bpe_tokenizer
|
| 76 |
-
tokenizer = encoders.build_bpe(Namespace(**tkn_cfg))
|
| 77 |
-
return text if tokenizer is None else tokenizer.decode(text)
|
| 78 |
-
|
| 79 |
-
@classmethod
|
| 80 |
-
def get_prefix_token(cls, task, lang):
|
| 81 |
-
prefix_size = int(task.data_cfg.prepend_tgt_lang_tag)
|
| 82 |
-
prefix_tokens = None
|
| 83 |
-
if prefix_size > 0:
|
| 84 |
-
assert lang is not None
|
| 85 |
-
lang_tag = SpeechToTextDataset.get_lang_tag_idx(lang, task.tgt_dict)
|
| 86 |
-
prefix_tokens = torch.Tensor([lang_tag]).long().unsqueeze(0)
|
| 87 |
-
return prefix_tokens
|
| 88 |
-
|
| 89 |
-
@classmethod
|
| 90 |
-
def get_prediction(
|
| 91 |
-
cls, task, model, generator, sample, tgt_lang=None, synthesize_speech=False
|
| 92 |
-
) -> Union[str, Tuple[str, Tuple[torch.Tensor, int]]]:
|
| 93 |
-
_tgt_lang = tgt_lang or task.data_cfg.hub.get("tgt_lang", None)
|
| 94 |
-
prefix = cls.get_prefix_token(task, _tgt_lang)
|
| 95 |
-
pred_tokens = generator.generate([model], sample, prefix_tokens=prefix)
|
| 96 |
-
pred = cls.detokenize(task, pred_tokens[0][0]["tokens"])
|
| 97 |
-
|
| 98 |
-
if synthesize_speech:
|
| 99 |
-
pfx = f"{_tgt_lang}_" if task.data_cfg.prepend_tgt_lang_tag else ""
|
| 100 |
-
tts_model_id = task.data_cfg.hub.get(f"{pfx}tts_model_id", None)
|
| 101 |
-
if tts_model_id is None:
|
| 102 |
-
logger.warning("TTS model configuration not found")
|
| 103 |
-
else:
|
| 104 |
-
_repo, _id = tts_model_id.split(":")
|
| 105 |
-
tts_model = torch.hub.load(_repo, _id, verbose=False)
|
| 106 |
-
pred = (pred, tts_model.predict(pred))
|
| 107 |
-
return pred
|
| 108 |
-
|
| 109 |
-
def predict(
|
| 110 |
-
self,
|
| 111 |
-
audio: Union[str, torch.Tensor],
|
| 112 |
-
tgt_lang: Optional[str] = None,
|
| 113 |
-
synthesize_speech: bool = False,
|
| 114 |
-
) -> Union[str, Tuple[str, Tuple[torch.Tensor, int]]]:
|
| 115 |
-
# `audio` is either a file path or a 1xT Tensor
|
| 116 |
-
# return either text or (text, synthetic speech)
|
| 117 |
-
sample = self.get_model_input(self.task, audio)
|
| 118 |
-
return self.get_prediction(
|
| 119 |
-
self.task,
|
| 120 |
-
self.model,
|
| 121 |
-
self.generator,
|
| 122 |
-
sample,
|
| 123 |
-
tgt_lang=tgt_lang,
|
| 124 |
-
synthesize_speech=synthesize_speech,
|
| 125 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|