code
stringlengths
17
6.64M
@register_model_architecture('lightconv_lm', 'lightconv_lm') def base_lm_architecture(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 2048) args.decoder_layers = getattr(args, 'decoder_layers', 6) args.decoder_...
@register_model_architecture('lightconv_lm', 'lightconv_lm_gbw') def lightconv_lm_gbw(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.dropout = getattr(args, 'dropout', 0.1) args.attention_dropout = getattr(args, 'attention_dropout', 0.1) args.decoder_ffn_embed_dim = getat...
@register_model('multilingual_transformer') class MultilingualTransformerModel(FairseqMultiModel): 'Train Transformer models for multiple language pairs simultaneously.\n\n Requires `--task multilingual_translation`.\n\n We inherit all arguments from TransformerModel and assume that all language\n pairs ...
@register_model_architecture('multilingual_transformer', 'multilingual_transformer') def base_multilingual_architecture(args): base_architecture(args) args.share_encoder_embeddings = getattr(args, 'share_encoder_embeddings', False) args.share_decoder_embeddings = getattr(args, 'share_decoder_embeddings', ...
@register_model_architecture('multilingual_transformer', 'multilingual_transformer_iwslt_de_en') def multilingual_transformer_iwslt_de_en(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 1024) args.encoder_attention...
def align_bpe_to_words(roberta, bpe_tokens: torch.LongTensor, other_tokens: List[str]): '\n Helper to align GPT-2 BPE to other tokenization formats (e.g., spaCy).\n\n Args:\n roberta (RobertaHubInterface): RoBERTa instance\n bpe_tokens (torch.LongTensor): GPT-2 BPE tokens of shape `(T_bpe)`\n ...
def align_features_to_words(roberta, features, alignment): '\n Align given features to words.\n\n Args:\n roberta (RobertaHubInterface): RoBERTa instance\n features (torch.Tensor): features to align of shape `(T_bpe x C)`\n alignment: alignment between BPE tokens and words returned by\n...
def spacy_nlp(): if (getattr(spacy_nlp, '_nlp', None) is None): try: from spacy.lang.en import English spacy_nlp._nlp = English() except ImportError: raise ImportError('Please install spacy with: pip install spacy') return spacy_nlp._nlp
def spacy_tokenizer(): if (getattr(spacy_tokenizer, '_tokenizer', None) is None): try: nlp = spacy_nlp() spacy_tokenizer._tokenizer = nlp.Defaults.create_tokenizer(nlp) except ImportError: raise ImportError('Please install spacy with: pip install spacy') ret...
@register_model('transformer_from_pretrained_xlm') class TransformerFromPretrainedXLMModel(TransformerModel): @staticmethod def add_args(parser): 'Add model-specific arguments to the parser.' TransformerModel.add_args(parser) parser.add_argument('--pretrained-xlm-checkpoint', type=str...
def upgrade_state_dict_with_xlm_weights(state_dict: Dict[(str, Any)], pretrained_xlm_checkpoint: str) -> Dict[(str, Any)]: '\n Load XLM weights into a Transformer encoder or decoder model.\n\n Args:\n state_dict: state dict for either TransformerEncoder or\n TransformerDecoder\n pre...
class TransformerEncoderFromPretrainedXLM(TransformerEncoder): def __init__(self, args, dictionary, embed_tokens): super().__init__(args, dictionary, embed_tokens) if getattr(args, 'init_decoder_only', False): return assert hasattr(args, 'pretrained_xlm_checkpoint'), '--pretra...
class TransformerDecoderFromPretrainedXLM(TransformerDecoder): def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False): super().__init__(args, dictionary, embed_tokens, no_encoder_attn) if getattr(args, 'init_encoder_only', False): return assert hasattr(args,...
@register_model_architecture('transformer_from_pretrained_xlm', 'transformer_from_pretrained_xlm') def base_architecture(args): transformer_base_architecture(args)
@register_model('transformer_lm') class TransformerLanguageModel(FairseqLanguageModel): @classmethod def hub_models(cls): return {'transformer_lm.gbw.adaptive_huge': 'https://dl.fbaipublicfiles.com/fairseq/models/lm/adaptive_lm_gbw_huge.tar.bz2', 'transformer_lm.wiki103.adaptive': 'https://dl.fbaipub...
@register_model_architecture('transformer_lm', 'transformer_lm') def base_lm_architecture(args): if hasattr(args, 'no_tie_adaptive_proj'): args.no_decoder_final_norm = True if (args.no_tie_adaptive_proj is False): args.tie_adaptive_proj = True if hasattr(args, 'decoder_final_norm')...
@register_model_architecture('transformer_lm', 'transformer_lm_big') def transformer_lm_big(args): args.decoder_layers = getattr(args, 'decoder_layers', 12) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1024) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 4096) args....
@register_model_architecture('transformer_lm', 'transformer_lm_wiki103') @register_model_architecture('transformer_lm', 'transformer_lm_baevski_wiki103') def transformer_lm_baevski_wiki103(args): args.decoder_layers = getattr(args, 'decoder_layers', 16) args.decoder_attention_heads = getattr(args, 'decoder_at...
@register_model_architecture('transformer_lm', 'transformer_lm_gbw') @register_model_architecture('transformer_lm', 'transformer_lm_baevski_gbw') def transformer_lm_baevski_gbw(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.dropout = getattr(args, 'dropout', 0.1) args.attenti...
@register_model_architecture('transformer_lm', 'transformer_lm_gpt') def transformer_lm_gpt(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 768) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 3072) args.decoder_layers = getattr(args, 'decoder_layers', 12) args.d...
@register_model_architecture('transformer_lm', 'transformer_lm_gpt2_small') def transformer_lm_gpt2_small(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1024) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 4096) args.decoder_layers = getattr(args, 'decoder_layers',...
@register_model_architecture('transformer_lm', 'transformer_lm_gpt2_medium') def transformer_lm_gpt2_medium(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1280) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 5120) args.decoder_layers = getattr(args, 'decoder_layers...
@register_model_architecture('transformer_lm', 'transformer_lm_gpt2_big') def transformer_lm_gpt2_big(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1600) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 6400) args.decoder_layers = getattr(args, 'decoder_layers', 48)...
class AdaptiveInput(nn.Module): def __init__(self, vocab_size: int, padding_idx: int, initial_dim: int, factor: float, output_dim: int, cutoff: List[int]): super().__init__() if (vocab_size > cutoff[(- 1)]): cutoff = (cutoff + [vocab_size]) else: assert (vocab_size...
class ConvTBC(torch.nn.Module): '1D convolution over an input of shape (time x batch x channel)\n\n The implementation uses gemm to perform the convolution. This implementation\n is faster than cuDNN for small kernel sizes.\n ' def __init__(self, in_channels, out_channels, kernel_size, padding=0): ...
class DropoutSelect(nn.Module): 'docstring for D' def __init__(self, dropout_type, dropout_gama=0.5, inplace=False): super().__init__() self.dropout_type = dropout_type self.dropout_gama = dropout_gama self.inplace = inplace dropout_alpha = 1.0 self.dropout_alp...
def gen_forward(): kernels = [3, 5, 7, 15, 31, 63, 127, 255] blocks = [32, 64, 128, 256] head = '\n/**\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n#include "...
def gen_backward(): kernels = [3, 5, 7, 15, 31, 63, 127, 255] thresh = [512, 512, 512, 512, 512, 380, 256, 256] min_block = [64, 64, 64, 64, 64, 64, 128, 256] seqs = [(32 * x) for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]] head = '\n/**\n * Copyright (c) Facebook, Inc. and its a...
def gelu_accurate(x): if (not hasattr(gelu_accurate, '_a')): gelu_accurate._a = math.sqrt((2 / math.pi)) return ((0.5 * x) * (1 + torch.tanh((gelu_accurate._a * (x + (0.044715 * torch.pow(x, 3)))))))
def gelu(x: torch.Tensor) -> torch.Tensor: if hasattr(torch.nn.functional, 'gelu'): return torch.nn.functional.gelu(x.float()).type_as(x) else: return ((x * 0.5) * (1.0 + torch.erf((x / math.sqrt(2.0)))))
class GradMultiply(torch.autograd.Function): @staticmethod def forward(ctx, x, scale): ctx.scale = scale res = x.new(x) return res @staticmethod def backward(ctx, grad): return ((grad * ctx.scale), None)
class Highway(torch.nn.Module): '\n A `Highway layer <https://arxiv.org/abs/1505.00387>`_.\n Adopted from the AllenNLP implementation.\n ' def __init__(self, input_dim: int, num_layers: int=1): super(Highway, self).__init__() self.input_dim = input_dim self.layers = nn.Module...
def LayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True, export=False): if ((not export) and torch.cuda.is_available()): try: from apex.normalization import FusedLayerNorm return FusedLayerNorm(normalized_shape, eps, elementwise_affine) except ImportError: ...
class LearnedPositionalEmbedding(nn.Embedding): '\n This module learns positional embeddings up to a fixed maximum size.\n Padding ids are ignored by either offsetting based on padding_idx\n or by setting padding_idx to None and ensuring that the appropriate\n position ids are passed to the forward fu...
def gen_forward(): kernels = [3, 5, 7, 15, 31, 63, 127, 255] seqs = [(32 * x) for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]] head = '\n/**\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the...
def gen_backward(): head = '\n/**\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n#include "lightconv_cuda.cuh"\n\nstd::vector<at::Tensor> lightconv_cuda_backward(\n ...
class LogSumExpMoE(torch.autograd.Function): 'Standard LogSumExp forward pass, but use *posterior* for the backward.\n\n See `"Mixture Models for Diverse Machine Translation: Tricks of the Trade"\n (Shen et al., 2019) <https://arxiv.org/abs/1902.07816>`_.\n ' @staticmethod def forward(ctx, logp,...
@register_model('masked_lm') class MaskedLMModel(BaseFairseqModel): '\n Class for training a Masked Language Model. It also supports an\n additional sentence level prediction if the sent-loss argument is set.\n ' def __init__(self, args, encoder): super().__init__() self.args = args ...
class MaskedLMEncoder(FairseqEncoder): '\n Encoder for Masked Language Modelling.\n ' def __init__(self, args, dictionary): super().__init__(dictionary) self.padding_idx = dictionary.pad() self.vocab_size = dictionary.__len__() self.max_positions = args.max_positions ...
@register_model_architecture('masked_lm', 'masked_lm') def base_architecture(args): args.dropout = getattr(args, 'dropout', 0.1) args.attention_dropout = getattr(args, 'attention_dropout', 0.1) args.act_dropout = getattr(args, 'act_dropout', 0.0) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn...
@register_model_architecture('masked_lm', 'bert_base') def bert_base_architecture(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 768) args.share_encoder_input_output_embed = getattr(args, 'share_encoder_input_output_embed', True) args.no_token_positional_embeddings = getattr(args, 'no_...
@register_model_architecture('masked_lm', 'bert_large') def bert_large_architecture(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024) args.encoder_layers = getattr(args, 'encoder_layers', 24) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 16) args.encode...
@register_model_architecture('masked_lm', 'xlm_base') def xlm_architecture(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024) args.share_encoder_input_output_embed = getattr(args, 'share_encoder_input_output_embed', True) args.no_token_positional_embeddings = getattr(args, 'no_token_...
class MeanPoolGatingNetwork(torch.nn.Module): "A simple mean-pooling gating network for selecting experts.\n\n This module applies mean pooling over an encoder's output and returns\n reponsibilities for each expert. The encoder format is expected to match\n :class:`fairseq.models.transformer.TransformerE...
class MultiheadAttention(nn.Module): 'Multi-headed attention.\n\n See "Attention Is All You Need" for more details.\n ' def __init__(self, embed_dim, num_heads, kdim=None, vdim=None, dropout=0.0, bias=True, add_bias_kv=False, add_zero_attn=False, self_attention=False, encoder_decoder_attention=False): ...
def NormSelect(norm_type, embed_dim, head_num=None, warmup_updates=1000): if (norm_type == 'layer'): return LayerNorm(embed_dim) elif (norm_type == 'batch'): return MaskSyncBatchNorm(embed_dim) elif (norm_type == 'power'): return MaskPowerNorm(embed_dim, group_num=head_num, warmup_...
def tile(a, repeats, dim): "\n Substitute for numpy's repeat function. Taken from https://discuss.pytorch.org/t/how-to-tile-a-tensor/13853/2\n torch.repeat([1,2,3], 2) --> [1, 2, 3, 1, 2, 3]\n np.repeat([1,2,3], repeats=2, axis=0) --> [1, 1, 2, 2, 3, 3]\n\n :param a: tensor\n :param repeats: number...
class GroupNorm(nn.Module): 'Applies Group Normalization over a mini-batch of inputs as described in\n the paper `Group Normalization`_ .\n\n .. math::\n y = \\frac{x - \\mathrm{E}[x]}{ \\sqrt{\\mathrm{Var}[x] + \\epsilon}} * \\gamma + \\beta\n\n The input channels are separated into :attr:`num_gr...
class LayerNorm(nn.Module): 'Applies Layer Normalization over a mini-batch of inputs as described in\n the paper `Layer Normalization`_ .\n\n .. math::\n y = \\frac{x - \\mathrm{E}[x]}{ \\sqrt{\\mathrm{Var}[x] + \\epsilon}} * \\gamma + \\beta\n\n The mean and standard-deviation are calculated sepa...
def PositionalEmbedding(num_embeddings: int, embedding_dim: int, padding_idx: int, learned: bool=False): if learned: if (padding_idx is not None): num_embeddings = ((num_embeddings + padding_idx) + 1) m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx) nn...
class ScalarBias(torch.autograd.Function): '\n Adds a vector of scalars, used in self-attention mechanism to allow\n the model to optionally attend to this vector instead of the past\n ' @staticmethod def forward(ctx, input, dim, bias_init): size = list(input.size()) size[dim] +=...
def scalar_bias(input, dim, bias_init=0): return ScalarBias.apply(input, dim, bias_init)
class SparseMultiheadAttention(MultiheadAttention): ' Sparse Multi-Headed Attention.\n\n "Generating Long Sequences with Sparse Transformers". Implements\n fixed factorized self attention, where l=stride and c=expressivity.\n A(1) includes all words in the stride window and A(2) takes a summary of c\n ...
class SparseTransformerSentenceEncoder(TransformerSentenceEncoder): '\n Sparse implementation of the TransformerSentenceEncoder\n - see SparseMultiheadAttention\n ' def __init__(self, padding_idx: int, vocab_size: int, num_encoder_layers: int=6, embedding_dim: int=768, ffn_embedding_dim: int=3072, n...
class SparseTransformerSentenceEncoderLayer(TransformerSentenceEncoderLayer): '\n Implements a Sprase Transformer Encoder Layer (see SparseMultiheadAttention)\n ' def __init__(self, embedding_dim: float=768, ffn_embedding_dim: float=3072, num_attention_heads: float=8, dropout: float=0.1, attention_drop...
class TransformerEncoderLayer(nn.Module): 'Encoder layer block.\n\n In the original paper each operation (multi-head attention or FFN) is\n postprocessed with: `dropout -> add residual -> layernorm`. In the\n tensor2tensor code they suggest that learning is more robust when\n preprocessing each layer ...
class TransformerDecoderLayer(nn.Module): 'Decoder layer block.\n\n In the original paper each operation (multi-head attention, encoder\n attention or FFN) is postprocessed with: `dropout -> add residual ->\n layernorm`. In the tensor2tensor code they suggest that learning is more\n robust when prepro...
def Linear(in_features, out_features, bias=True): m = nn.Linear(in_features, out_features, bias) nn.init.xavier_uniform_(m.weight) if bias: nn.init.constant_(m.bias, 0.0) return m
class TransformerSentenceEncoderLayer(nn.Module): '\n Implements a Transformer Encoder Layer used in BERT/XLM style pre-trained\n models.\n ' def __init__(self, embedding_dim: float=768, ffn_embedding_dim: float=3072, num_attention_heads: float=8, dropout: float=0.1, attention_dropout: float=0.1, ac...
def unfold1d(x, kernel_size, padding_l, pad_value=0): 'unfold T x B x C to T x B x C x K' if (kernel_size > 1): (T, B, C) = x.size() x = F.pad(x, (0, 0, 0, 0, padding_l, ((kernel_size - 1) - padding_l)), value=pad_value) x = x.as_strided((T, B, C, kernel_size), ((B * C), C, 1, (B * C))...
def _pair(v): if isinstance(v, Iterable): assert (len(v) == 2), 'len(v) != 2' return v return tuple(repeat(v, 2))
def infer_conv_output_dim(conv_op, input_dim, sample_inchannel): sample_seq_len = 200 sample_bsz = 10 x = torch.randn(sample_bsz, sample_inchannel, sample_seq_len, input_dim) x = conv_op(x) x = x.transpose(1, 2) (bsz, seq) = x.size()[:2] per_channel_dim = x.size()[3] return (x.contiguo...
class VGGBlock(torch.nn.Module): '\n VGG motibated cnn module https://arxiv.org/pdf/1409.1556.pdf\n\n Args:\n in_channels: (int) number of input channels (typically 1)\n out_channels: (int) number of output channels\n conv_kernel_size: convolution channels\n pooling_kernel_size: ...
@register_optimizer('adadelta') class Adadelta(FairseqOptimizer): def __init__(self, args, params): super().__init__(args) self._optimizer = torch.optim.Adadelta(params, **self.optimizer_config) @staticmethod def add_args(parser): 'Add optimizer-specific arguments to the parser.'...
@register_optimizer('adafactor') class FairseqAdafactor(FairseqOptimizer): def __init__(self, args, params): super().__init__(args) self._optimizer = Adafactor(params, **self.optimizer_config) @staticmethod def add_args(parser): 'Add optimizer-specific arguments to the parser.' ...
class Adafactor(torch.optim.Optimizer): 'Implements Adafactor algorithm.\n\n This implementation is based on:\n `Adafactor: Adaptive Learning Rates with Sublinear Memory Cost`\n (see https://arxiv.org/abs/1804.04235)\n\n Arguments:\n params (iterable): iterable of parameters to optimize or dict...
@register_optimizer('adagrad') class Adagrad(FairseqOptimizer): def __init__(self, args, params): super().__init__(args) self._optimizer = torch.optim.Adagrad(params, **self.optimizer_config) @staticmethod def add_args(parser): 'Add optimizer-specific arguments to the parser.' ...
@register_optimizer('adam') class FairseqAdam(FairseqOptimizer): 'Adam optimizer for fairseq.\n\n Important note: this optimizer corresponds to the "AdamW" variant of\n Adam in its weight decay behavior. As such, it is most closely\n analogous to torch.optim.AdamW from PyTorch.\n ' def __init__(s...
class Adam(torch.optim.Optimizer): 'Implements Adam algorithm.\n\n This implementation is modified from torch.optim.Adam based on:\n `Fixed Weight Decay Regularization in Adam`\n (see https://arxiv.org/abs/1711.05101)\n\n It has been proposed in `Adam: A Method for Stochastic Optimization`_.\n\n Ar...
class FusedAdam(torch.optim.Optimizer): "\n Implements Adam algorithm. Currently GPU-only. Requires Apex to be installed via\n ``python setup.py install --cuda_ext --cpp_ext``.\n\n It has been proposed in `Adam: A Method for Stochastic Optimization`_.\n\n Compared to the original version in Apex, the ...
@register_optimizer('adamax') class FairseqAdamax(FairseqOptimizer): def __init__(self, args, params): super().__init__(args) self._optimizer = Adamax(params, **self.optimizer_config) @staticmethod def add_args(parser): 'Add optimizer-specific arguments to the parser.' pa...
class Adamax(torch.optim.Optimizer): 'Implements Adamax algorithm (a variant of Adam based on infinity norm).\n\n It has been proposed in `Adam: A Method for Stochastic Optimization`__.\n\n Compared to the version in PyTorch, this version implements a fix for weight decay.\n\n Arguments:\n params ...
class FairseqBMUF(FairseqOptimizer): '\n Implements incremental block distributed data parallelism similar to\n https://ieeexplore.ieee.org/document/7472805\n\n Paper title: Scalable training of deep learning machines by incremental\n block training with intra-block parallel optimization and blockwise...
class FairseqOptimizer(object): def __init__(self, args): super().__init__() self.args = args @staticmethod def add_args(parser): 'Add optimizer-specific arguments to the parser.' pass @property def optimizer(self): 'Return a torch.optim.optimizer.Optimiz...
class DynamicLossScaler(object): def __init__(self, init_scale=(2.0 ** 15), scale_factor=2.0, scale_window=2000, tolerance=0.05, threshold=None): self.loss_scale = init_scale self.scale_factor = scale_factor self.scale_window = scale_window self.tolerance = tolerance self....
class _FP16OptimizerMixin(object): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @classmethod def build_fp32_params(cls, params): total_param_size = sum((p.data.numel() for p in params)) fp32_params = params[0].new(0).float().new(total_param_size) ...
class FP16Optimizer(_FP16OptimizerMixin, optim.FairseqOptimizer): '\n Wrap an *optimizer* to support FP16 (mixed precision) training.\n ' def __init__(self, args, params, fp32_optimizer, fp32_params): super().__init__(args) self.fp16_params = params self.fp32_optimizer = fp32_op...
class MemoryEfficientFP16Optimizer(optim.FairseqOptimizer): '\n Wrap an *optimizer* to support FP16 (mixed precision) training.\n\n Compared to :class:`fairseq.optim.FP16Optimizer`, this version does not\n maintain an FP32 copy of the model. We instead expect the optimizer to\n convert the gradients t...
@register_lr_scheduler('cosine') class CosineSchedule(FairseqLRScheduler): 'Assign LR based on a cyclical schedule that follows the cosine function.\n\n See https://arxiv.org/pdf/1608.03983.pdf for details.\n\n We also support a warmup phase where we linearly increase the learning rate\n from some initia...
class FairseqLRScheduler(object): def __init__(self, args, optimizer): super().__init__() if (not isinstance(optimizer, FairseqOptimizer)): raise ValueError('optimizer must be an instance of FairseqOptimizer') self.args = args self.optimizer = optimizer self.be...
@register_lr_scheduler('fixed') class FixedSchedule(FairseqLRScheduler): 'Decay the LR on a fixed schedule.' def __init__(self, args, optimizer): super().__init__(args, optimizer) args.warmup_updates = (getattr(args, 'warmup_updates', 0) or 0) self.lr = args.lr[0] if (args.war...
@register_lr_scheduler('inverse_sqrt') class InverseSquareRootSchedule(FairseqLRScheduler): 'Decay the LR based on the inverse square root of the update number.\n\n We also support a warmup phase where we linearly increase the learning rate\n from some initial learning rate (``--warmup-init-lr``) until the ...
@register_lr_scheduler('polynomial_decay') class PolynomialDecaySchedule(FairseqLRScheduler): 'Decay the LR on a fixed schedule.' def __init__(self, args, optimizer): super().__init__(args, optimizer) args.warmup_updates = (getattr(args, 'warmup_updates', 0) or 0) self.lr = args.lr[0]...
@register_lr_scheduler('reduce_lr_on_plateau') class ReduceLROnPlateau(FairseqLRScheduler): '\n Decay the LR by a factor every time the validation loss plateaus.\n Also comes with optional warmup phase, where we linearly increase the learning rate\n from some initial learning rate (``--warmup-init-lr``) ...
@register_lr_scheduler('tri_stage') class TriStageLRSchedule(FairseqLRScheduler): 'Tristage learning rate schedulr\n\n Implement the learning rate scheduler in https://arxiv.org/pdf/1904.08779.pdf\n\n Similar to inverse_squre_root scheduler, but tri_stage learning rate employs\n three stages LR schedulin...
@register_lr_scheduler('triangular') class TriangularSchedule(FairseqLRScheduler): 'Assign LR based on a triangular cyclical schedule.\n\n See https://arxiv.org/pdf/1506.01186.pdf for details.\n ' def __init__(self, args, optimizer): super().__init__(args, optimizer) if (len(args.lr) > ...
@register_optimizer('nag') class FairseqNAG(FairseqOptimizer): def __init__(self, args, params): super().__init__(args) self._optimizer = NAG(params, **self.optimizer_config) @staticmethod def add_args(parser): 'Add optimizer-specific arguments to the parser.' parser.add_...
class NAG(Optimizer): def __init__(self, params, lr=required, momentum=0, weight_decay=0): defaults = dict(lr=lr, lr_old=lr, momentum=momentum, weight_decay=weight_decay) super(NAG, self).__init__(params, defaults) @property def supports_memory_efficient_fp16(self): return True ...
@register_optimizer('sgd') class SGD(FairseqOptimizer): def __init__(self, args, params): super().__init__(args) self._optimizer = torch.optim.SGD(params, **self.optimizer_config) @staticmethod def add_args(parser): 'Add optimizer-specific arguments to the parser.' parser...
def get_preprocessing_parser(default_task='translation'): parser = get_parser('Preprocessing', default_task) add_preprocess_args(parser) return parser
def get_training_parser(default_task='translation'): parser = get_parser('Trainer', default_task) add_dataset_args(parser, train=True) add_distributed_training_args(parser) add_model_args(parser) add_optimization_args(parser) add_checkpoint_args(parser) add_norm_args(parser) return par...
def get_generation_parser(interactive=False, default_task='translation'): parser = get_parser('Generation', default_task) add_dataset_args(parser, gen=True) add_generation_args(parser) if interactive: add_interactive_args(parser) return parser
def get_interactive_generation_parser(default_task='translation'): return get_generation_parser(interactive=True, default_task=default_task)
def get_eval_lm_parser(default_task='language_modeling'): parser = get_parser('Evaluate Language Model', default_task) add_dataset_args(parser, gen=True) add_eval_lm_args(parser) return parser
def get_validation_parser(default_task=None): parser = get_parser('Validation', default_task) add_dataset_args(parser, train=True) group = parser.add_argument_group('Evaluation') add_common_eval_args(group) return parser
def add_norm_args(parser): group = parser.add_argument_group('Normalization') parser.add_argument('--encoder-norm-self', default='layer', choices=['layer', 'batch', 'power'], help='normalization scheme for encoder') parser.add_argument('--encoder-norm-ff', default='layer', choices=['none', 'layer', 'group...
def eval_str_list(x, type=float): if (x is None): return None if isinstance(x, str): x = eval(x) try: return list(map(type, x)) except TypeError: return [type(x)]
def eval_bool(x, default=False): if (x is None): return default try: return bool(eval(x)) except TypeError: return default
def parse_args_and_arch(parser, input_args=None, parse_known=False, suppress_defaults=False): if suppress_defaults: args = parse_args_and_arch(parser, input_args=input_args, parse_known=parse_known, suppress_defaults=False) suppressed_parser = argparse.ArgumentParser(add_help=False, parents=[parse...
def get_parser(desc, default_task='translation'): usr_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False) usr_parser.add_argument('--user-dir', default=None) (usr_args, _) = usr_parser.parse_known_args() utils.import_user_module(usr_args) parser = argparse.ArgumentParser(allow_abb...