code
stringlengths
17
6.64M
@register_model_architecture('delight_transformer_lm', 'delight_transformer_lm_wiki103') def delight_transformer_lm_wiki103(args): args.delight_emb_map_dim = getattr(args, 'delight_emb_map_dim', 128) args.delight_emb_out_dim = getattr(args, 'delight_emb_out_dim', 512) args.delight_dec_min_depth = getattr(...
def DistributedFairseqModel(args, model): '\n Wrap a *model* to support distributed data parallel training.\n\n This is similar to the built-in DistributedDataParallel, but allows\n additional configuration of the DistributedDataParallel class to\n use, and also provides easier access to the wrapped m...
class FairseqDecoder(nn.Module): 'Base class for decoders.' def __init__(self, dictionary): super().__init__() self.dictionary = dictionary self.onnx_trace = False def forward(self, prev_output_tokens, encoder_out=None, **kwargs): "\n Args:\n prev_output...
class FairseqEncoder(nn.Module): 'Base class for encoders.' def __init__(self, dictionary): super().__init__() self.dictionary = dictionary def forward(self, src_tokens, src_lengths=None, **kwargs): '\n Args:\n src_tokens (LongTensor): tokens in the source langu...
@with_incremental_state class FairseqIncrementalDecoder(FairseqDecoder): 'Base class for incremental decoders.\n\n Incremental decoding is a special mode at inference time where the Model\n only receives a single timestep of input corresponding to the previous\n output token (for teacher forcing) and mus...
class BaseFairseqModel(nn.Module): 'Base class for fairseq models.' def __init__(self): super().__init__() self._is_generation_fast = False @staticmethod def add_args(parser): 'Add model-specific arguments to the parser.' pass @classmethod def build_model(cls...
class FairseqEncoderDecoderModel(BaseFairseqModel): 'Base class for encoder-decoder models.\n\n Args:\n encoder (FairseqEncoder): the encoder\n decoder (FairseqDecoder): the decoder\n ' def __init__(self, encoder, decoder): super().__init__() self.encoder = encoder ...
class FairseqModel(FairseqEncoderDecoderModel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) utils.deprecation_warning('FairseqModel is deprecated, please use FairseqEncoderDecoderModel or BaseFairseqModel instead', stacklevel=4)
class FairseqMultiModel(BaseFairseqModel): 'Base class for combining multiple encoder-decoder models.' def __init__(self, encoders, decoders): super().__init__() assert (encoders.keys() == decoders.keys()) self.keys = list(encoders.keys()) for key in self.keys: ass...
class FairseqLanguageModel(BaseFairseqModel): 'Base class for decoder-only models.\n\n Args:\n decoder (FairseqDecoder): the decoder\n ' def __init__(self, decoder): super().__init__() self.decoder = decoder assert isinstance(self.decoder, FairseqDecoder) def forward...
class FairseqEncoderModel(BaseFairseqModel): 'Base class for encoder-only models.\n\n Args:\n encoder (FairseqEncoder): the encoder\n ' def __init__(self, encoder): super().__init__() self.encoder = encoder assert isinstance(self.encoder, FairseqEncoder) def forward(...
@register_model('fconv_lm') class FConvLanguageModel(FairseqLanguageModel): def __init__(self, decoder): super().__init__(decoder) @staticmethod def add_args(parser): 'Add model-specific arguments to the parser.' parser.add_argument('--dropout', type=float, metavar='D', help='dro...
@register_model_architecture('fconv_lm', 'fconv_lm') def base_lm_architecture(args): args.dropout = getattr(args, 'dropout', 0.1) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 128) args.decoder_layers = getattr(args, 'decoder_layers', '[(1268, 4)] * 13') args.decoder_attention = getattr(...
@register_model_architecture('fconv_lm', 'fconv_lm_dauphin_wikitext103') def fconv_lm_dauphin_wikitext103(args): layers = '[(850, 6)] * 3' layers += ' + [(850, 1)] * 1' layers += ' + [(850, 5)] * 4' layers += ' + [(850, 1)] * 1' layers += ' + [(850, 4)] * 3' layers += ' + [(1024, 4)] * 1' ...
@register_model_architecture('fconv_lm', 'fconv_lm_dauphin_gbw') def fconv_lm_dauphin_gbw(args): layers = '[(512, 5)]' layers += ' + [(128, 1, 0), (128, 5, 0), (512, 1, 3)] * 3' layers += ' + [(512, 1, 0), (512, 5, 0), (1024, 1, 3)] * 3' layers += ' + [(1024, 1, 0), (1024, 5, 0), (2048, 1, 3)] * 6' ...
@register_model('fconv_self_att') class FConvModelSelfAtt(FairseqEncoderDecoderModel): @classmethod def hub_models(cls): return {'conv.stories.pretrained': {'path': 'https://dl.fbaipublicfiles.com/fairseq/models/stories_checkpoint.tar.gz', 'checkpoint_file': 'pretrained_checkpoint.pt', 'tokenizer': '...
class FConvEncoder(FairseqEncoder): 'Convolutional encoder' def __init__(self, dictionary, embed_dim=512, max_positions=1024, convolutions=(((512, 3),) * 20), dropout=0.1, attention=False, attention_nheads=1): super().__init__(dictionary) self.dropout = dropout self.num_attention_laye...
@with_incremental_state class FConvDecoder(FairseqDecoder): 'Convolutional decoder' def __init__(self, dictionary, embed_dim=512, out_embed_dim=256, max_positions=1024, convolutions=(((512, 3),) * 8), attention=True, dropout=0.1, selfattention=False, attention_nheads=1, selfattention_nheads=1, project_input=...
class SelfAttention(nn.Module): def __init__(self, out_channels, embed_dim, num_heads, project_input=False, gated=False, downsample=False): super().__init__() self.attention = DownsampledMultiHeadAttention(out_channels, embed_dim, num_heads, dropout=0, bias=True, project_input=project_input, gate...
def Embedding(num_embeddings, embedding_dim, padding_idx): m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx) m.weight.data.normal_(0, 0.1) return m
def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx): m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx) m.weight.data.normal_(0, 0.1) return m
def Linear(in_features, out_features, dropout=0.0): 'Weight-normalized Linear layer (input: N x T x C)' m = nn.Linear(in_features, out_features) m.weight.data.normal_(mean=0, std=math.sqrt(((1 - dropout) / in_features))) m.bias.data.zero_() return m
def LinearizedConv1d(in_channels, out_channels, kernel_size, dropout=0.0, **kwargs): 'Weight-normalized Conv1d layer optimized for decoding' m = LinearizedConvolution(in_channels, out_channels, kernel_size, **kwargs) std = math.sqrt(((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))) m.weight....
def ConvTBC(in_channels, out_channels, kernel_size, dropout=0, **kwargs): 'Weight-normalized Conv1d layer' from fairseq.modules import ConvTBC m = ConvTBC(in_channels, out_channels, kernel_size, **kwargs) std = math.sqrt(((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))) m.weight.data.nor...
@register_model_architecture('fconv_self_att', 'fconv_self_att') def base_architecture(args): args.dropout = getattr(args, 'dropout', 0.1) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_layers = getattr(args, 'encoder_layers', '[(512, 3)] * 3') args.decoder_embed_dim = g...
@register_model_architecture('fconv_self_att', 'fconv_self_att_wp') def fconv_self_att_wp(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 256) args.encoder_layers = getattr(args, 'encoder_layers', '[(128, 3)] * 2 + [(512,3)] * 1') args.decoder_embed_dim = getattr(args, 'decoder_embed_di...
@register_model('lightconv_lm') class LightConvLanguageModel(FairseqLanguageModel): def __init__(self, decoder): super().__init__(decoder) @staticmethod def add_args(parser): 'Add model-specific arguments to the parser.' parser.add_argument('--dropout', default=0.1, type=float, m...
@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('lstm_lm') class LSTMLanguageModel(FairseqLanguageModel): def __init__(self, decoder): super().__init__(decoder) @staticmethod def add_args(parser): 'Add model-specific arguments to the parser.' parser.add_argument('--dropout', type=float, metavar='D', help='dropo...
@register_model_architecture('lstm_lm', 'lstm_lm') def base_architecture(args): args.dropout = getattr(args, 'dropout', 0.1) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.decoder_embed_path = getattr(args, 'decoder_embed_path', None) args.decoder_hidden_size = getattr(args, 'de...
@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_...
@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 _skeptical_unmasking(output_scores, output_masks, p): sorted_index = output_scores.sort((- 1))[1] boundary_len = ((output_masks.sum(1, keepdim=True).type_as(output_scores) - 2) * p).long() skeptical_mask = (new_arange(output_masks) < boundary_len) return skeptical_mask.scatter(1, sorted_index, ske...
@register_model('cmlm_transformer') class CMLMNATransformerModel(NATransformerModel): @staticmethod def add_args(parser): NATransformerModel.add_args(parser) def forward(self, src_tokens, src_lengths, prev_output_tokens, tgt_tokens, **kwargs): assert (not self.decoder.src_embedding_copy)...
@register_model_architecture('cmlm_transformer', 'cmlm_transformer') def cmlm_base_architecture(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 20...
@register_model_architecture('cmlm_transformer', 'cmlm_transformer_wmt_en_de') def cmlm_wmt_en_de(args): cmlm_base_architecture(args)
@register_model('nacrf_transformer') class NACRFTransformerModel(NATransformerModel): def __init__(self, args, encoder, decoder): super().__init__(args, encoder, decoder) self.crf_layer = DynamicCRF(num_embedding=len(self.tgt_dict), low_rank=args.crf_lowrank_approx, beam_size=args.crf_beam_approx...
@register_model_architecture('nacrf_transformer', 'nacrf_transformer') def nacrf_base_architecture(args): args.crf_lowrank_approx = getattr(args, 'crf_lowrank_approx', 32) args.crf_beam_approx = getattr(args, 'crf_beam_approx', 64) args.word_ins_loss_factor = getattr(args, 'word_ins_loss_factor', 0.5) ...
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('camembert') class CamembertModel(RobertaModel): @classmethod def hub_models(cls): return {'camembert.v0': 'http://dl.fbaipublicfiles.com/fairseq/models/camembert.v0.tar.gz'} @classmethod def from_pretrained(cls, model_name_or_path, checkpoint_file='model.pt', data_name_or_pa...
@register_model('xlmr') class XLMRModel(RobertaModel): @classmethod def hub_models(cls): return {'xlmr.base': 'http://dl.fbaipublicfiles.com/fairseq/models/xlmr.base.tar.gz', 'xlmr.large': 'http://dl.fbaipublicfiles.com/fairseq/models/xlmr.large.tar.gz'} @classmethod def from_pretrained(cls,...
@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): def moses_fastbpe(path): return {'path': path, 'tokenizer': 'moses', 'bpe': 'fastbpe'} return {'transformer_lm.gbw.adaptive_huge': 'https://dl.fbaipublicfiles...
@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], no_scale_emb: bool=False): super().__init__() if (vocab_size > cutoff[(- 1)]): cutoff = (cutoff + [vocab_size]) else: ...
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 DeLighTTransformerEncoderLayer(nn.Module): 'DeLight Encoder layer\n ' def __init__(self, args, embed_dim, width_multiplier=DEFAULT_WIDTH_MULTIPLIER, dextra_depth=DEFAULT_MIN_DEXTRA_LAYERS, dextra_proj=2): super().__init__() self.embed_dim = embed_dim assert ((embed_dim % dext...
class DeLighTTransformerDecoderLayer(nn.Module): 'Delight Decoder layer\n ' def __init__(self, args, embed_dim, width_multiplier=DEFAULT_WIDTH_MULTIPLIER, dextra_depth=DEFAULT_MIN_DEXTRA_LAYERS, no_encoder_attn=False, dextra_proj=2, *unused_args, **unused_kwargs): super().__init__() self.e...
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,...
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...
@with_incremental_state 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_de...
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)
@with_incremental_state class SingleHeadAttention(nn.Module): 'Single head attention as defined in DeLighT paper\n ' def __init__(self, q_in_dim, kv_in_dim, proj_dim, out_dim, dropout=0.0, bias=True, self_attention=False, encoder_decoder_attention=False): "\n :param embed_dim: Input dimensi...
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: int=768, ffn_embedding_dim: int=3072, num_attention_heads: int=8, dropout: float=0.1, attention_dropout: f...
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: int=768, ffn_embedding_dim: int=3072, num_attention_heads: int=8, dropout: float=0.1, attention_dropout: float=0.1, activati...
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.' ...