U
    d x                     @   s
  d dl Z d dlmZmZmZmZ d dlZd dlmZ ddlm	Z
 ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ G dd deZG dd deZG dd deZG dd deZG dd deZdd Zeeegef dddZ dS )    N)OptionalAnyUnionCallable)Tensor   )
functional   )Module)MultiheadAttention)
ModuleList)xavier_uniform_)Dropout)Linear)	LayerNormc                       s   e Zd ZdZddddddejdddd	d	ddfeeeeeeee	e
egef f ee ee eeedd
 fddZdeeee ee ee ee ee ee ed	ddZeeedddZdd Z  ZS )Transformera<  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. Users can build the BERT(https://arxiv.org/abs/1810.04805)
    model with corresponding parameters.

    Args:
        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
    i            皙?Nh㈵>F)d_modelnheadnum_encoder_layersnum_decoder_layersdim_feedforwarddropout
activationcustom_encodercustom_decoderlayer_norm_epsbatch_first
norm_firstreturnc              	      s   ||d}t t|   |d k	r(|| _n<t||||||
||f|}t|fd|
i|}t|||| _|	d k	rt|	| _n<t||||||
||f|}t|fd|
i|}t	|||| _| 
  || _|| _|| _d S )Ndevicedtypeeps)superr   __init__encoderTransformerEncoderLayerr   TransformerEncoderdecoderTransformerDecoderLayerTransformerDecoder_reset_parametersr   r   r!   )selfr   r   r   r   r   r   r   r   r   r    r!   r"   r%   r&   factory_kwargsencoder_layerZencoder_normdecoder_layerZdecoder_norm	__class__ @/tmp/pip-unpacked-wheel-ua33x9lu/torch/nn/modules/transformer.pyr)   3   s<    

   
   zTransformer.__init__)	srctgtsrc_masktgt_maskmemory_masksrc_key_padding_masktgt_key_padding_maskmemory_key_padding_maskr#   c	                 C   s   |  dk}	| js4|d|dkr4|	r4tdn&| jrZ|d|dkrZ|	rZtd|d| jksz|d| jkrtd| j|||d}
| j||
||||d}|S )	a  Take in and process masked source/target sequences.

        Args:
            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: :math:`(S, E)` for unbatched input, :math:`(S, N, E)` if `batch_first=False` or
              `(N, S, E)` if `batch_first=True`.
            - tgt: :math:`(T, E)` for unbatched input, :math:`(T, N, E)` if `batch_first=False` or
              `(N, T, E)` if `batch_first=True`.
            - src_mask: :math:`(S, S)` or :math:`(N\cdot\text{num\_heads}, S, S)`.
            - tgt_mask: :math:`(T, T)` or :math:`(N\cdot\text{num\_heads}, T, T)`.
            - memory_mask: :math:`(T, S)`.
            - src_key_padding_mask: :math:`(S)` for unbatched input otherwise :math:`(N, S)`.
            - tgt_key_padding_mask: :math:`(T)` for unbatched input otherwise :math:`(N, T)`.
            - memory_key_padding_mask: :math:`(S)` for unbatched input otherwise :math:`(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: :math:`(T, E)` for unbatched input, :math:`(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 decode.

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

        Examples:
            >>> output = transformer_model(src, tgt, src_mask=src_mask, tgt_mask=tgt_mask)
           r	   z-the batch number of src and tgt must be equalr   z:the feature number of src and tgt must be equal to d_model)maskr>   r<   r=   r?   r@   )dimr!   sizeRuntimeErrorr   r*   r-   )r1   r9   r:   r;   r<   r=   r>   r?   r@   Z
is_batchedmemoryoutputr7   r7   r8   forwardU   s    3
 zTransformer.forward)szr#   c                 C   s   t jt | | ftdddS )zGenerate a square mask for the sequence. The masked positions are filled with float('-inf').
            Unmasked positions are filled with float(0.0).
        z-infr	   )Zdiagonal)torchZtriufullfloat)rK   r7   r7   r8   generate_square_subsequent_mask   s    z+Transformer.generate_square_subsequent_maskc                 C   s&   |   D ]}| dkrt| qdS )z-Initiate parameters in the transformer model.r	   N)
parametersrE   r   )r1   pr7   r7   r8   r0      s    zTransformer._reset_parameters)NNNNNN)__name__
__module____qualname____doc__FreluintrN   r   strr   r   r   r   boolr)   rJ   staticmethodrO   r0   __classcell__r7   r7   r5   r8   r      sP   "           "          Br   c                       sF   e Zd ZdZdgZd
 fdd	Zdeee ee eddd	Z  Z	S )r,   a3  TransformerEncoder is a stack of N encoder layers

    Args:
        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: ``False`` (disabled).

    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)
    normNFc                    s0   t t|   t||| _|| _|| _|| _d S N)r(   r,   r)   _get_cloneslayers
num_layersr]   enable_nested_tensor)r1   r3   ra   r]   rb   r5   r7   r8   r)      s
    zTransformerEncoder.__init__)r9   rC   r>   r#   c           	      C   s  |}d}| j d }t|tjjr<|js<|js<|jjr<|jj	r<|j
r<|jj|jjkr<| dkr<| jr<|dk	r<|js<|dkr<||jj|jj|jjj|jjj|jj|jj|jj|jj|jj|jj|jj|jjf}tj|s<t rtdd |D r<|js(dt|jkr<d}t||  }| j D ](}|rZ|||d	}n||||d
}qB|r||!d}| j"dk	r| "|}|S )aP  Pass the input through the encoder layers in turn.

        Args:
            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.
        Fr   rA   Nc                 S   s   g | ]}|j  qS r7   Zrequires_grad.0xr7   r7   r8   
<listcomp>   s     z.TransformerEncoder.forward.<locals>.<listcomp>cpuT)r;   )r;   r>   g        )#r`   
isinstancerL   nnr+   r"   training	self_attnr!   _qkv_same_embed_dimactivation_relu_or_gelunorm1r'   norm2rE   rb   	is_nestedin_proj_weightin_proj_biasout_projweightbiaslinear1linear2	overrideshas_torch_functionis_grad_enabledallis_cudarY   r%   Z_nested_tensor_from_maskZlogical_notZto_padded_tensorr]   )	r1   r9   rC   r>   rI   Zconvert_to_nestedZfirst_layertensor_argsmodr7   r7   r8   rJ      s\    




zTransformerEncoder.forward)NF)NN
rR   rS   rT   rU   __constants__r)   r   r   rJ   r\   r7   r7   r5   r8   r,      s   r,   c                	       sT   e Zd ZdZdgZd	 fdd	Zd
eeee ee ee ee edddZ  Z	S )r/   a_  TransformerDecoder is a stack of N decoder layers

    Args:
        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)
    r]   Nc                    s*   t t|   t||| _|| _|| _d S r^   )r(   r/   r)   r_   r`   ra   r]   )r1   r4   ra   r]   r5   r7   r8   r)   
  s    zTransformerDecoder.__init__r:   rH   r<   r=   r?   r@   r#   c           	   	   C   s<   |}| j D ]}|||||||d}q
| jdk	r8| |}|S )aM  Pass the inputs (and mask) through the decoder layer in turn.

        Args:
            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.
        rD   N)r`   r]   )	r1   r:   rH   r<   r=   r?   r@   rI   r   r7   r7   r8   rJ     s    


zTransformerDecoder.forward)N)NNNNr   r7   r7   r5   r8   r/      s          r/   c                       s   e Zd ZdZddgZddejdddddfeeeee	e
eegef f eeedd		 fd
dZ fddZdeee ee edddZeee ee edddZeedddZ  ZS )r+   a  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.

    Args:
        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, respectivaly. 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``)
        - norm_first is ``False`` (this restriction may be loosened in the future)
        - 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 <https://pytorch.org/docs/stable/nested.html>`_, 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 <https://pytorch.org/docs/stable/nested.html>`_ can be
        passed for ``src`` to represent padding more efficiently than using a padding
        mask. In this case, a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ will be
        returned, and an additional speedup proportional to the fraction of the input that
        is padding can be expected.
    r!   r"   r   r   r   FN	r   r   r   r   r   r    r!   r"   r#   c                    s   |	|
d}t t|   t||f||d|| _t||f|| _t|| _t||f|| _	|| _
t|fd|i|| _t|fd|i|| _t|| _t|| _t|trt|}|tjkrd| _n|tjkrd| _nd| _|| _d S )Nr$   r   r!   r'   r	   r   r   )r(   r+   r)   r   rl   r   rw   r   r   rx   r"   r   ro   rp   dropout1dropout2ri   rY   _get_activation_fnrV   rW   rn   gelur   r1   r   r   r   r   r   r    r!   r"   r%   r&   r2   r5   r7   r8   r)   e  s*    






z TransformerEncoderLayer.__init__c                    s&   t t| | t| ds"tj| _d S Nr   )r(   r+   __setstate__hasattrrV   rW   r   r1   stater5   r7   r8   r     s    
z$TransformerEncoderLayer.__setstate__)r9   r;   r>   r#   c                 C   s  |  dkrx| jsx| jsx| jjrx| jjrx| jrx| jj| j	jkrx|dkrx|j
rf|dk	sx|| jj| jj| jjj| jjj| jj| jj| j	j| j	j| jj| jj| jj| jjf}tj|sxtdd |D rxt rtdd |D rxt|| jj| jj| jj| jj| jjj| jjj| jdkd| jj| jj| jj| j	j| j	j| jj| jj| jj| jj|dk	rr|n|S |}| jr|| | ||| }|| | 	| }n,| || ||| }| 	|| | }|S )aQ  Pass the input through the encoder layer.

        Args:
            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.
        rA   Nc                 S   s    g | ]}|j pd t|jkqS )rh   )r}   rY   r%   rd   r7   r7   r8   rg     s     z3TransformerEncoderLayer.forward.<locals>.<listcomp>c                 S   s   g | ]}|j  qS r7   rc   rd   r7   r7   r8   rg     s     r   F)rE   r"   rk   rl   r!   rm   rn   ro   r'   rp   rq   rr   rs   rt   ru   rv   rw   rx   rL   ry   rz   r|   r{   Z_transformer_encoder_layer_fwdZ	embed_dimZ	num_heads	_sa_block	_ff_block)r1   r9   r;   r>   r~   rf   r7   r7   r8   rJ     s    zTransformerEncoderLayer.forwardrf   	attn_maskkey_padding_maskr#   c                 C   s$   | j |||||ddd }| |S NF)r   r   Zneed_weightsr   rl   r   r1   rf   r   r   r7   r7   r8   r     s    
z!TransformerEncoderLayer._sa_blockrf   r#   c              	   C   s&   |  | | | |}| |S r^   )rx   r   r   rw   r   r1   rf   r7   r7   r8   r     s    z!TransformerEncoderLayer._ff_block)NN)rR   rS   rT   rU   r   rV   rW   rX   rN   r   rY   r   r   rZ   r)   r   r   rJ   r   r   r\   r7   r7   r5   r8   r+   -  s:   5   
  !  
 I  	r+   c                       s   e Zd ZdZddgZddejdddddfeeeee	e
eegef f eeedd		 fd
dZ fddZdeeee ee ee ee edddZeee ee edddZeeee ee edddZeedddZ  ZS )r.   a  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.

    Args:
        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, respectivaly. 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)
    r!   r"   r   r   r   FNr   c                    s   |	|
d}t t|   t||f||d|| _t||f||d|| _t||f|| _t|| _	t||f|| _
|| _t|fd|i|| _t|fd|i|| _t|fd|i|| _t|| _t|| _t|| _t|trt|| _n|| _d S )Nr$   r   r'   )r(   r.   r)   r   rl   multihead_attnr   rw   r   r   rx   r"   r   ro   rp   norm3r   r   dropout3ri   rY   r   r   r   r5   r7   r8   r)     s*    





z TransformerDecoderLayer.__init__c                    s&   d|krt j|d< tt| | d S r   )rV   rW   r(   r.   r   r   r5   r7   r8   r   $  s    
z$TransformerDecoderLayer.__setstate__r   c              	   C   s   |}| j rR|| | ||| }|| | |||| }|| | | }nF| || ||| }| || |||| }| || | }|S )aK  Pass the inputs (and mask) through the decoder layer.

        Args:
            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.
        )r"   r   ro   
_mha_blockrp   r   r   )r1   r:   rH   r<   r=   r?   r@   rf   r7   r7   r8   rJ   )  s    zTransformerDecoderLayer.forwardr   c                 C   s$   | j |||||ddd }| |S r   r   r   r7   r7   r8   r   G  s    
z!TransformerDecoderLayer._sa_block)rf   memr   r   r#   c                 C   s$   | j |||||ddd }| |S r   )r   r   )r1   rf   r   r   r   r7   r7   r8   r   P  s    
z"TransformerDecoderLayer._mha_blockr   c              	   C   s&   |  | | | |}| |S r^   )rx   r   r   rw   r   r   r7   r7   r8   r   Y  s    z!TransformerDecoderLayer._ff_block)NNNN)rR   rS   rT   rU   r   rV   rW   rX   rN   r   rY   r   r   rZ   r)   r   r   rJ   r   r   r   r\   r7   r7   r5   r8   r.     sH   !   
          	  	r.   c                    s   t  fddt|D S )Nc                    s   g | ]}t  qS r7   )copydeepcopy)re   imoduler7   r8   rg   _  s     z_get_clones.<locals>.<listcomp>)r   range)r   Nr7   r   r8   r_   ^  s    r_   )r   r#   c                 C   s.   | dkrt jS | dkrt jS td| d S )NrW   r   z&activation should be relu/gelu, not {})rV   rW   r   rG   format)r   r7   r7   r8   r   b  s
    r   )!r   typingr   r   r   r   rL   r    r   rV   r   r
   r   r   	containerr   initr   r   r   Zlinearr   Znormalizationr   r   r,   r/   r+   r.   r_   rY   r   r7   r7   r7   r8   <module>   s(    S4 7{