nn

transformer

Transformer modules.

class mindnlp.common.nn.transformer.MultiheadAttention(embed_dim, num_heads, dropout=0.0, bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None, batch_first=False)[source]

Bases: Cell

Allows the model to jointly attend to information from different representation subspaces as described in the paper: Attention Is All You Need.

Multi-Head Attention is defined as:

\[\text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O\]

where \(head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)\).

forward() will use a special optimized implementation if all of the following conditions are met:

  • self attention is being computed (i.e., query, key, and value are the same tensor. This restriction will be loosened in the future.)

  • Either autograd is disabled (using torch.inference_mode or torch.no_grad) or no tensor argument requires_grad

  • training is disabled (using .eval())

  • dropout is 0

  • add_bias_kv is False

  • add_zero_attn is False

  • batch_first is True and the input is batched

  • kdim and vdim are equal to embed_dim

  • at most one of key_padding_mask or attn_mask is passed

  • if a NestedTensor is passed, neither key_padding_mask nor attn_mask is passed

If the optimized implementation is in use, a NestedTensor can be passed for query/key/value to represent padding more efficiently than using a padding mask. In this case, a NestedTensor will be returned, and an additional speedup proportional to the fraction of the input that is padding can be expected.

Parameters
  • embed_dim – Total dimension of the model.

  • num_heads – Number of parallel attention heads. Note that embed_dim will be split across num_heads (i.e. each head will have dimension embed_dim // num_heads).

  • dropout – Dropout probability on attn_output_weights. Default: 0.0 (no dropout).

  • bias – If specified, adds bias to input / output projection layers. Default: True.

  • add_bias_kv – If specified, adds bias to the key and value sequences at dim=0. Default: False.

  • add_zero_attn – If specified, adds a new batch of zeros to the key and value sequences at dim=1. Default: False.

  • kdim – Total number of features for keys. Default: None (uses kdim=embed_dim).

  • vdim – Total number of features for values. Default: None (uses vdim=embed_dim).

  • batch_first – If True, then the input and output tensors are provided as (batch, seq, feature). Default: False (seq, batch, feature).

Examples:

>>> # xdoctest: +SKIP
>>> multihead_attn = nn.MultiheadAttention(embed_dim, num_heads)
>>> attn_output, attn_output_weights = multihead_attn(query, key, value)
construct(query: Tensor, key: Tensor, value: Tensor, key_padding_mask=None, need_weights: bool = True, attn_mask=None, average_attn_weights: bool = True)[source]

Defines the computation to be performed. This method must be overridden by all subclasses.

Note

It is not supported currently that inputs contain both tuple and non-tuple types at same time.

Parameters
  • inputs (tuple) – Tuple of variable parameters.

  • kwargs (dict) – Dictionary of variable keyword parameters.

Returns

Tensor, returns the computed result.

class mindnlp.common.nn.transformer.Transformer(d_model: int = 512, nhead: int = 8, num_encoder_layers: int = 6, num_decoder_layers: int = 6, dim_feedforward: int = 2048, dropout: float = 0.1, activation='relu', custom_encoder=None, custom_decoder=None, layer_norm_eps: float = 1e-05, batch_first: bool = False, norm_first: bool = False)[source]

Bases: Cell

A transformer model. User is able to modify the attributes as needed. The architecture is based on the paper “Attention Is All You Need”. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural Information Processing Systems, pages 6000-6010.

Parameters
  • d_model – the number of expected features in the encoder/decoder inputs (default=512).

  • nhead – the number of heads in the multiheadattention models (default=8).

  • num_encoder_layers – the number of sub-encoder-layers in the encoder (default=6).

  • num_decoder_layers – the number of sub-decoder-layers in the decoder (default=6).

  • dim_feedforward – the dimension of the feedforward network model (default=2048).

  • dropout – the dropout value (default=0.1).

  • activation – the activation function of encoder/decoder intermediate layer, can be a string (“relu” or “gelu”) or a unary callable. Default: relu

  • custom_encoder – custom encoder (default=None).

  • custom_decoder – custom decoder (default=None).

  • layer_norm_eps – the eps value in layer normalization components (default=1e-5).

  • batch_first – If True, then the input and output tensors are provided as (batch, seq, feature). Default: False (seq, batch, feature).

  • norm_first – if True, encoder and decoder layers will perform LayerNorms before other attention and feedforward operations, otherwise after. Default: False (after).

Examples::
>>> transformer_model = nn.Transformer(nhead=16, num_encoder_layers=12)
>>> src = torch.rand((10, 32, 512))
>>> tgt = torch.rand((20, 32, 512))
>>> out = transformer_model(src, tgt)

Note: A full example to apply nn.Transformer module for the word language model is available in https://github.com/pytorch/examples/tree/master/word_language_model

construct(src, tgt, src_mask=None, tgt_mask=None, memory_mask=None, src_key_padding_mask=None, tgt_key_padding_mask=None, memory_key_padding_mask=None)[source]

Take in and process masked source/target sequences.

Parameters
  • src – the sequence to the encoder (required).

  • tgt – the sequence to the decoder (required).

  • src_mask – the additive mask for the src sequence (optional).

  • tgt_mask – the additive mask for the tgt sequence (optional).

  • memory_mask – the additive mask for the encoder output (optional).

  • src_key_padding_mask – the ByteTensor mask for src keys per batch (optional).

  • tgt_key_padding_mask – the ByteTensor mask for tgt keys per batch (optional).

  • memory_key_padding_mask – the ByteTensor mask for memory keys per batch (optional).

Shape:
  • src: \((S, E)\) for unbatched input, \((S, N, E)\) if batch_first=False or (N, S, E) if batch_first=True.

  • tgt: \((T, E)\) for unbatched input, \((T, N, E)\) if batch_first=False or (N, T, E) if batch_first=True.

  • src_mask: \((S, S)\) or \((N\cdot\text{num\_heads}, S, S)\).

  • tgt_mask: \((T, T)\) or \((N\cdot\text{num\_heads}, T, T)\).

  • memory_mask: \((T, S)\).

  • src_key_padding_mask: \((S)\) for unbatched input otherwise \((N, S)\).

  • tgt_key_padding_mask: \((T)\) for unbatched input otherwise \((N, T)\).

  • memory_key_padding_mask: \((S)\) for unbatched input otherwise \((N, S)\).

Note: [src/tgt/memory]_mask ensures that position i is allowed to attend the unmasked positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend while the zero positions will be unchanged. If a BoolTensor is provided, positions with True are not allowed to attend while False values will be unchanged. If a FloatTensor is provided, it will be added to the attention weight. [src/tgt/memory]_key_padding_mask provides specified elements in the key to be ignored by the attention. If a ByteTensor is provided, the non-zero positions will be ignored while the zero positions will be unchanged. If a BoolTensor is provided, the positions with the value of True will be ignored while the position with the value of False will be unchanged.

  • output: \((T, E)\) for unbatched input, \((T, N, E)\) if batch_first=False or (N, T, E) if batch_first=True.

Note: Due to the multi-head attention architecture in the transformer model, the output sequence length of a transformer is same as the input sequence (i.e. target) length of the decoder.

where S is the source sequence length, T is the target sequence length, N is the batch size, E is the feature number

Examples

>>> # xdoctest: +SKIP
>>> output = transformer_model(src, tgt, src_mask=src_mask, tgt_mask=tgt_mask)
class mindnlp.common.nn.transformer.TransformerDecoder(decoder_layer, num_layers, norm=None)[source]

Bases: Cell

TransformerDecoder is a stack of N decoder layers

Parameters
  • decoder_layer – an instance of the TransformerDecoderLayer() class (required).

  • num_layers – the number of sub-decoder-layers in the decoder (required).

  • norm – the layer normalization component (optional).

Examples::
>>> decoder_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8)
>>> transformer_decoder = nn.TransformerDecoder(decoder_layer, num_layers=6)
>>> memory = torch.rand(10, 32, 512)
>>> tgt = torch.rand(20, 32, 512)
>>> out = transformer_decoder(tgt, memory)
construct(tgt, memory, tgt_mask=None, memory_mask=None, tgt_key_padding_mask=None, memory_key_padding_mask=None)[source]

Pass the inputs (and mask) through the decoder layer in turn.

Parameters
  • tgt – the sequence to the decoder (required).

  • memory – the sequence from the last layer of the encoder (required).

  • tgt_mask – the mask for the tgt sequence (optional).

  • memory_mask – the mask for the memory sequence (optional).

  • tgt_key_padding_mask – the mask for the tgt keys per batch (optional).

  • memory_key_padding_mask – the mask for the memory keys per batch (optional).

Shape:

see the docs in Transformer class.

class mindnlp.common.nn.transformer.TransformerDecoderLayer(d_model: int, nhead: int, dim_feedforward: int = 2048, dropout: float = 0.1, activation='relu', layer_norm_eps: float = 1e-05, batch_first: bool = False, norm_first: bool = False)[source]

Bases: Cell

TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. This standard decoder layer is based on the paper “Attention Is All You Need”. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural Information Processing Systems, pages 6000-6010. Users may modify or implement in a different way during application.

Parameters
  • d_model – the number of expected features in the input (required).

  • nhead – the number of heads in the multiheadattention models (required).

  • dim_feedforward – the dimension of the feedforward network model (default=2048).

  • dropout – the dropout value (default=0.1).

  • activation – the activation function of the intermediate layer, can be a string (“relu” or “gelu”) or a unary callable. Default: relu

  • layer_norm_eps – the eps value in layer normalization components (default=1e-5).

  • batch_first – If True, then the input and output tensors are provided as (batch, seq, feature). Default: False (seq, batch, feature).

  • norm_first – if True, layer norm is done prior to self attention, multihead attention and feedforward operations, respectively. Otherwise it’s done after. Default: False (after).

Examples::
>>> decoder_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8)
>>> memory = torch.rand(10, 32, 512)
>>> tgt = torch.rand(20, 32, 512)
>>> out = decoder_layer(tgt, memory)
Alternatively, when batch_first is True:
>>> decoder_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8, batch_first=True)
>>> memory = torch.rand(32, 10, 512)
>>> tgt = torch.rand(32, 20, 512)
>>> out = decoder_layer(tgt, memory)
construct(tgt, memory, tgt_mask=None, memory_mask=None, tgt_key_padding_mask=None, memory_key_padding_mask=None)[source]

Pass the inputs (and mask) through the decoder layer.

Parameters
  • tgt – the sequence to the decoder layer (required).

  • memory – the sequence from the last layer of the encoder (required).

  • tgt_mask – the mask for the tgt sequence (optional).

  • memory_mask – the mask for the memory sequence (optional).

  • tgt_key_padding_mask – the mask for the tgt keys per batch (optional).

  • memory_key_padding_mask – the mask for the memory keys per batch (optional).

Shape:

see the docs in Transformer class.

class mindnlp.common.nn.transformer.TransformerEncoder(encoder_layer, num_layers, norm=None)[source]

Bases: Cell

TransformerEncoder is a stack of N encoder layers. Users can build the BERT(https://arxiv.org/abs/1810.04805) model with corresponding parameters.

Parameters
  • encoder_layer – an instance of the TransformerEncoderLayer() class (required).

  • num_layers – the number of sub-encoder-layers in the encoder (required).

  • norm – the layer normalization component (optional).

  • enable_nested_tensor – if True, input will automatically convert to nested tensor (and convert back on output). This will improve the overall performance of TransformerEncoder when padding rate is high. Default: True (enabled).

Examples::
>>> encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8)
>>> transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=6)
>>> src = torch.rand(10, 32, 512)
>>> out = transformer_encoder(src)
construct(src: Tensor, mask=None, src_key_padding_mask=None)[source]

Pass the input through the encoder layers in turn.

Parameters
  • src – the sequence to the encoder (required).

  • mask – the mask for the src sequence (optional).

  • src_key_padding_mask – the mask for the src keys per batch (optional).

Shape:

see the docs in Transformer class.

class mindnlp.common.nn.transformer.TransformerEncoderLayer(d_model: int, nhead: int, dim_feedforward: int = 2048, dropout: float = 0.1, activation='relu', layer_norm_eps: float = 1e-05, batch_first: bool = False, norm_first: bool = False)[source]

Bases: Cell

TransformerEncoderLayer is made up of self-attn and feedforward network. This standard encoder layer is based on the paper “Attention Is All You Need”. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural Information Processing Systems, pages 6000-6010. Users may modify or implement in a different way during application.

Parameters
  • d_model – the number of expected features in the input (required).

  • nhead – the number of heads in the multiheadattention models (required).

  • dim_feedforward – the dimension of the feedforward network model (default=2048).

  • dropout – the dropout value (default=0.1).

  • activation – the activation function of the intermediate layer, can be a string (“relu” or “gelu”) or a unary callable. Default: relu

  • layer_norm_eps – the eps value in layer normalization components (default=1e-5).

  • batch_first – If True, then the input and output tensors are provided as (batch, seq, feature). Default: False (seq, batch, feature).

  • norm_first – if True, layer norm is done prior to attention and feedforward operations, respectively. Otherwise it’s done after. Default: False (after).

Examples::
>>> encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8)
>>> src = torch.rand(10, 32, 512)
>>> out = encoder_layer(src)
Alternatively, when batch_first is True:
>>> encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8, batch_first=True)
>>> src = torch.rand(32, 10, 512)
>>> out = encoder_layer(src)
Fast path:

forward() will use a special optimized implementation if all of the following conditions are met:

  • Either autograd is disabled (using torch.inference_mode or torch.no_grad) or no tensor argument requires_grad

  • training is disabled (using .eval())

  • batch_first is True and the input is batched (i.e., src.dim() == 3)

  • activation is one of: "relu", "gelu", torch.functional.relu, or torch.functional.gelu

  • at most one of src_mask and src_key_padding_mask is passed

  • if src is a NestedTensor, neither src_mask nor src_key_padding_mask is passed

  • the two LayerNorm instances have a consistent eps value (this will naturally be the case unless the caller has manually modified one without modifying the other)

If the optimized implementation is in use, a NestedTensor can be passed for src to represent padding more efficiently than using a padding mask. In this case, a NestedTensor will be returned, and an additional speedup proportional to the fraction of the input that is padding can be expected.

construct(src, src_mask=None, src_key_padding_mask=None)[source]

Pass the input through the encoder layer.

Parameters
  • src – the sequence to the encoder layer (required).

  • src_mask – the mask for the src sequence (optional).

  • src_key_padding_mask – the mask for the src keys per batch (optional).

Shape:

see the docs in Transformer class.