U
    *-e                     @   s  d dl Z d dlmZmZmZmZ d dl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 dddddgZeej e feejej edddZ!ee"ee ddd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&ee ee" ee e"d#d$d%Z,dS )'    N)OptionalAnyUnionCallable)Tensor   )
functional   )Module)MultiheadAttention)
ModuleList)xavier_uniform_)Dropout)Linear)	LayerNormTransformerTransformerEncoderTransformerDecoderTransformerEncoderLayerTransformerDecoderLayerszdevicedtypereturnc                 C   s$   t jt j| | ftd||dddS )zGenerate a square causal mask for the sequence. The masked positions are filled with float('-inf').
        Unmasked positions are filled with float(0.0).
    z-infr   r   r	   )Zdiagonal)torchZtriufullfloatr   r   r    r    ]/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/torch/nn/modules/transformer.py _generate_square_subsequent_mask   s    r"   )srcbatch_firstr   c                 C   s>   | j r
d S |  }t|dkr&|d S |r.dnd}|| S d S )Nr   r   r	   )	is_nestedsizelen)r#   r$   Zsrc_sizeZseq_len_posr    r    r!   _get_seq_len    s    r(   c                       s   e Zd ZdZddddddejd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edd fddZdeeee ee ee ee ee ee ee ee eedddZeeej e feejejedddZdd Z  ZS )r   a_  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.

    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).
        bias: If set to ``False``, ``Linear`` and ``LayerNorm`` layers will not learn an additive
            bias. Default: ``True``.

    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㈵>FT)d_modelnheadnum_encoder_layersnum_decoder_layersdim_feedforwarddropout
activationcustom_encodercustom_decoderlayer_norm_epsr$   
norm_firstbiasr   c              
      s   ||d}t    tjd| jj  |d k	r:|| _n@t||||||
|||f	|}t	|f|
|d|}t
|||| _|	d k	r|	| _n@t||||||
|||f	|}t	|f|
|d|}t|||| _|   || _|| _|| _d S )Nr   r   torch.nn.modules.epsr9   )super__init__r   _C_log_api_usage_once	__class____name__encoderr   r   r   decoderr   r   _reset_parametersr.   r/   r$   )selfr.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r$   r8   r9   r   r   factory_kwargsencoder_layerZencoder_normdecoder_layerZdecoder_normrB   r    r!   r?   V   sB    


   
   zTransformer.__init__)r#   tgtsrc_masktgt_maskmemory_masksrc_key_padding_masktgt_key_padding_maskmemory_key_padding_masksrc_is_causaltgt_is_causalmemory_is_causalr   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 Tensor mask for src keys per batch (optional).
            tgt_key_padding_mask: the Tensor mask for tgt keys per batch (optional).
            memory_key_padding_mask: the Tensor mask for memory keys per batch (optional).
            src_is_causal: If specified, applies a causal mask as ``src_mask``.
                Default: ``None``; try to detect a causal mask.
                Warning:
                ``src_is_causal`` provides a hint that ``src_mask`` is
                the causal mask. Providing incorrect hints can result in
                incorrect execution, including forward and backward
                compatibility.
            tgt_is_causal: If specified, applies a causal mask as ``tgt_mask``.
                Default: ``None``; try to detect a causal mask.
                Warning:
                ``tgt_is_causal`` provides a hint that ``tgt_mask`` is
                the causal mask. Providing incorrect hints can result in
                incorrect execution, including forward and backward
                compatibility.
            memory_is_causal: If specified, applies a causal mask as
                ``memory_mask``.
                Default: ``False``.
                Warning:
                ``memory_is_causal`` provides a hint that
                ``memory_mask`` is the causal mask. Providing incorrect
                hints can result in incorrect execution, including
                forward and backward compatibility.

        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 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 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 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)
           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)maskrP   	is_causalrN   rO   rQ   rR   rT   rU   )dimr$   r&   RuntimeErrorr.   rD   rE   )rG   r#   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   Z
is_batchedmemoryoutputr    r    r!   forwardy   s"    J
 
 zTransformer.forwardr   c                 C   s   t | ||dS )zGenerate a square causal mask for the sequence. The masked positions are filled with float('-inf').
            Unmasked positions are filled with float(0.0).
        r   )r"   r   r    r    r!   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)
parametersr[   r   )rG   pr    r    r!   rF      s    zTransformer._reset_parameters)	NNNNNNNNF)rC   
__module____qualname____doc__Freluintr   r   strr   r   r   r   boolr?   r_   staticmethodr   r   r@   _get_default_deviceget_default_dtyper   r`   rF   __classcell__r    r    rK   r!   r   2   sn   #             #               [
c                       sL   e Zd ZdZdgZd
 fdd	Zdeee ee ee eddd	Z	  Z
S )r   a  TransformerEncoder is a stack of N encoder layers. Users can build the
    BERT(https://arxiv.org/abs/1810.04805) model with corresponding parameters.

    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: ``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)
    normNTc                    s  t    tjd| jj  t||| _|| _	|| _
|| _|| _|| _d}d}t|tjjsl| d}n|jr~| d}nz|jjs| dd }nb|jjs| d}nN|js| d	}n<|jj|jjks| d
| d}n|jjd dkr| d}|r|rtd|  d| _d S )Nr;   rI    z  was not TransformerEncoderLayerz.norm_first was Truez#.self_attn.batch_first was not Truez2(use batch_first for better inference performance)z+.self_attn._qkv_same_embed_dim was not Truez%.activation_relu_or_gelu was not Truez.norm1.eps was not equal to z
.norm2.epsr   r	   z.self_attn.num_heads is oddzJenable_nested_tensor is True, but self.use_nested_tensor is False because F)r>   r?   r   r@   rA   rB   rC   _get_cloneslayers
num_layersro   enable_nested_tensoruse_nested_tensor
mask_check
isinstancennr   r8   	self_attnr$   _qkv_same_embed_dimactivation_relu_or_gelunorm1r=   norm2	num_headswarningswarn)rG   rI   rs   ro   rt   rv   Z	enc_layerwhy_not_sparsity_fast_pathrK   r    r!   r?      s:    

zTransformerEncoder.__init__)r#   rX   rP   rY   r   c                 C   sF  t j|dt |d|jd}t j|ddd|jdd}|}d}| jd }|}d}	d	}
|jj}t| d
sjd}	n| jsvd}	n|j	r|
 d}	nv|
 dksd|
  }	nZ|dkrd}	nLt| dr| jrt|| sd}	n&|jrd}	n|dk	rd}	nt rd}	|	s||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}ddtjjjg}tj|rzd}	n<|jj |krd| }	n"t! rt"dd |D rd}	|	s|dk	rd}tj#|| dd}d}t$||}t%|||}| jD ]}|||||d}q|r,|&d |' }| j(dk	rB| (|}|S )!a  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).
            is_causal: If specified, applies a causal mask as ``mask``.
                Default: ``None``; try to detect a causal mask.
                Warning:
                ``is_causal`` provides a hint that ``mask`` is the
                causal mask. Providing incorrect hints can result in
                incorrect execution, including forward and backward
                compatibility.

        Shape:
            see the docs in Transformer class.
        rP   rX   rX   	mask_name
other_type
other_nametarget_typeNrp   FrX   r   r   r   r   Zcheck_otherr   zself.layers[0]ru   z'use_nested_tensor attribute not presentz1self.use_nested_tensor (set in init) was not Truez was in training moderV   3input not batched; expected src.dim() of 3 but got zsrc_key_padding_mask was Nonerv   zImask_check enabled, and src and src_key_padding_mask was not left alignedz#NestedTensor input is not supportedz0src_key_padding_mask and mask were both suppliedautocast is enabledcpucuda'some Tensor argument has_torch_functionzsrc device is neither one of c                 s   s   | ]}|j V  qd S NZrequires_grad.0xr    r    r!   	<genexpr>v  s     z-TransformerEncoder.forward.<locals>.<genexpr>hgrad is enabled and at least one of query or the input/output projection weights or biases requires_gradT)rv   )rM   rY   rP   g        ))rf   _canonical_mask_none_or_dtyper   rr   ry   r$   hasattrru   trainingr[   rv   r   Z%_nested_tensor_from_mask_left_alignedZlogical_notr%   is_autocast_enabledin_proj_weightin_proj_biasout_projweightr9   r|   r}   linear1linear2utilsbackend_registration_privateuse1_backend_name	overrideshas_torch_functionr   typeis_grad_enabledanyZ_nested_tensor_from_maskr(   _detect_is_causal_maskZto_padded_tensorr&   ro   )rG   r#   rX   rP   rY   r^   Zconvert_to_nestedZfirst_layerZsrc_key_padding_mask_for_layersr   Zstr_first_layerr$   tensor_args_supported_device_typeseq_lenmodr    r    r!   r_     s    	




zTransformerEncoder.forward)NTT)NNNrC   rc   rd   re   __constants__r?   r   r   rj   r_   rn   r    r    rK   r!   r      s   &    c                       s\   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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)
    ro   Nc                    s<   t    tjd| jj  t||| _|| _	|| _
d S )Nr;   )r>   r?   r   r@   rA   rB   rC   rq   rr   rs   ro   )rG   rJ   rs   ro   rK   r    r!   r?     s
    
zTransformerDecoder.__init__F	rL   r]   rN   rO   rQ   rR   rT   rU   r   c	                 C   s`   |}	t || jd jj}
t|||
}| jD ]}||	|||||||d}	q*| jdk	r\| |	}	|	S )a  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).
            tgt_is_causal: If specified, applies a causal mask as ``tgt mask``.
                Default: ``None``; try to detect a causal mask.
                Warning:
                ``tgt_is_causal`` provides a hint that ``tgt_mask`` is
                the causal mask. Providing incorrect hints can result in
                incorrect execution, including forward and backward
                compatibility.
            memory_is_causal: If specified, applies a causal mask as
                ``memory mask``.
                Default: ``False``.
                Warning:
                ``memory_is_causal`` provides a hint that
                ``memory_mask`` is the causal mask. Providing incorrect
                hints can result in incorrect execution, including
                forward and backward compatibility.

        Shape:
            see the docs in Transformer class.
        r   rZ   N)r(   rr   ry   r$   r   ro   )rG   rL   r]   rN   rO   rQ   rR   rT   rU   r^   r   r   r    r    r!   r_     s     


zTransformerDecoder.forward)N)NNNNNFr   r    r    rK   r!   r     s"              c                       s   e Zd ZdZdgZddejddddddf	eeeee	e
eegef f eeeedd	
 fd
dZ fddZdeee ee eedddZdeee ee eedddZeedddZ  ZS )r   ax  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.

    TransformerEncoderLayer can handle either traditional torch.tensor inputs,
    or Nested Tensor inputs.  Derived classes are expected to similarly accept
    both input formats.  (Not all combinations of inputs are currently
    supported by TransformerEncoderLayer while Nested Tensor is in prototype
    state.)

    If you are implementing a custom layer, you may derive it either from
    the Module or TransformerEncoderLayer class.  If your custom layer
    supports both torch.Tensors and Nested Tensors inputs, make its
    implementation a derived class of TransformerEncoderLayer. If your custom
    Layer supports only torch.Tensor inputs, derive its implementation from
    Module.

    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, respectively. Otherwise it's done after. Default: ``False`` (after).
        bias: If set to ``False``, ``Linear`` and ``LayerNorm`` layers will not learn an additive
            bias. Default: ``True``.

    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 described in
        `FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness`_ 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 <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.

        .. _`FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness`:
         https://arxiv.org/abs/2205.14135

    r8   r+   r,   r-   FTN
r.   r/   r2   r3   r4   r7   r$   r8   r9   r   c                    s  |
|d}t    t||f||	|d|| _t||fd|	i|| _t|| _t||fd|	i|| _|| _	t
|f||	d|| _t
|f||	d|| _t|| _t|| _t|trt|}|tjkst|tjjrd| _n*|tjkst|tjjr
d| _nd| _|| _d S )Nr:   )r3   r9   r$   r9   r<   r	   r   r   )r>   r?   r   ry   r   r   r   r3   r   r8   r   r|   r}   dropout1dropout2rw   ri   _get_activation_fnrf   rg   r   rx   ZReLUr{   geluZGELUr4   rG   r.   r/   r2   r3   r4   r7   r$   r8   r9   r   r   rH   rK   r    r!   r?   #  s0    


 



z TransformerEncoderLayer.__init__c                    s"   t  | t| dstj| _d S Nr4   )r>   __setstate__r   rf   rg   r4   rG   staterK   r    r!   r   E  s    
z$TransformerEncoderLayer.__setstate__)r#   rM   rP   rY   r   c           
         s  t j|dt |d|jd}t j|ddd|jdd}d}| dksTd	|  }n| jr`d
}n|| jjsnd}nn| jjs|d}n`| j	sd}nT| j
j| jjksd}n>|jr|dk	s|dk	rd}n"| jjd dkrd}nt rd}|s0|| 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}ddtjjjg tj|rXd}nFt fdd|D s|d  }n"t rtdd |D rd}|s0| j |||\}}t!|| jj"| jj| jj| jj| jjj| jjj| j	dk| j#| j
j| j
j| j
j| jj| jj| jj| jj| jj| jj||S |}	| j#rn|	| j$| 
|	|||d }	|	| %| |	 }	n0| 
|	| j$|	|||d }	| |	| %|	 }	|	S )a  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).
            is_causal: If specified, applies a causal mask as ``src mask``.
                Default: ``False``.
                Warning:
                ``is_causal`` provides a hint that ``src_mask`` is the
                causal mask. Providing incorrect hints can result in
                incorrect execution, including forward and backward
                compatibility.

        Shape:
            see the docs in Transformer class.
        rP   rM   r   Nrp   Fr   rV   r   ztraining is enabledz"self_attn.batch_first was not Truez*self_attn._qkv_same_embed_dim was not Truez$activation_relu_or_gelu was not Truez#norm1.eps is not equal to norm2.epszSneither src_key_padding_mask nor src_mask are not supported with NestedTensor inputr   r	   znum_head is oddr   r   r   r   c                 3   s   | ]}|j j kV  qd S r   )r   r   r   r   r    r!   r     s     z2TransformerEncoderLayer.forward.<locals>.<genexpr>z0some Tensor argument's device is neither one of c                 s   s   | ]}|j V  qd S r   r   r   r    r    r!   r     s     r   )rY   )&rf   r   r   r   r[   r   ry   r$   rz   r{   r|   r=   r}   r%   r~   r   r   r   r   r   r   r9   r   r   r   r   r   r   r   allr   r   Zmerge_masksZ_transformer_encoder_layer_fwdZ	embed_dimr8   	_sa_block	_ff_block)
rG   r#   rM   rP   rY   r   r   Zmerged_maskZ	mask_typer   r    r   r!   r_   K  s    
zTransformerEncoderLayer.forwardr   	attn_maskkey_padding_maskrY   r   c              	   C   s&   | j |||||d|dd }| |S )NF)r   r   need_weightsrY   r   ry   r   rG   r   r   r   rY   r    r    r!   r     s    
 z!TransformerEncoderLayer._sa_blockr   r   c              	   C   s&   |  | | | |}| |S r   )r   r3   r4   r   r   rG   r   r    r    r!   r     s    z!TransformerEncoderLayer._ff_block)NNF)F)rC   rc   rd   re   r   rf   rg   rh   r   r   ri   r   r   rj   r?   r   r   r_   r   r   rn   r    r    rK   r!   r     sJ   H    
   "	        	c                       s   e Zd ZdZdgZddejddddddf	eeeee	e
eegef f e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eed	ddZdeee ee eedddZde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, respectively. Otherwise it's done after.
            Default: ``False`` (after).
        bias: If set to ``False``, ``Linear`` and ``LayerNorm`` layers will not learn an additive
            bias. Default: ``True``.

    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)
    r8   r+   r,   r-   FTNr   c                    s  |
|d}t    t||f|||	d|| _t||f|||	d|| _t||fd|	i|| _t|| _t||fd|	i|| _	|| _
t|f||	d|| _t|f||	d|| _t|f||	d|| _t|| _t|| _t|| _t|tr
t|| _n|| _d S )Nr:   )r3   r$   r9   r9   r<   )r>   r?   r   ry   multihead_attnr   r   r   r3   r   r8   r   r|   r}   norm3r   r   dropout3rw   ri   r   r4   r   rK   r    r!   r?     s2    





z TransformerDecoderLayer.__init__c                    s"   d|krt j|d< t | d S r   )rf   rg   r>   r   r   rK   r    r!   r     s    
z$TransformerDecoderLayer.__setstate__r   c	           
   
   C   s   |}	| j rV|	| | |	||| }	|	| | |	|||| }	|	| | |	 }	nJ| |	| |	||| }	| |	| |	|||| }	| |	| |	 }	|	S )ag  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).
            tgt_is_causal: If specified, applies a causal mask as ``tgt mask``.
                Default: ``False``.
                Warning:
                ``tgt_is_causal`` provides a hint that ``tgt_mask`` is
                the causal mask. Providing incorrect hints can result in
                incorrect execution, including forward and backward
                compatibility.
            memory_is_causal: If specified, applies a causal mask as
                ``memory mask``.
                Default: ``False``.
                Warning:
                ``memory_is_causal`` provides a hint that
                ``memory_mask`` is the causal mask. Providing incorrect
                hints can result in incorrect execution, including
                forward and backward compatibility.

        Shape:
            see the docs in Transformer class.
        )r8   r   r|   
_mha_blockr}   r   r   )
rG   rL   r]   rN   rO   rQ   rR   rT   rU   r   r    r    r!   r_     s    )zTransformerDecoderLayer.forwardr   c              	   C   s&   | j ||||||ddd }| |S NF)r   r   rY   r   r   r   r   r    r    r!   r   U  s    
z!TransformerDecoderLayer._sa_block)r   memr   r   rY   r   c              	   C   s&   | j ||||||ddd }| |S r   )r   r   )rG   r   r   r   r   rY   r    r    r!   r   _  s    
z"TransformerDecoderLayer._mha_blockr   c              	   C   s&   |  | | | |}| |S r   )r   r3   r4   r   r   r   r    r    r!   r   i  s    z!TransformerDecoderLayer._ff_block)NNNNFF)F)F)rC   rc   rd   re   r   rf   rg   rh   r   r   ri   r   r   rj   r?   r   r   r_   r   r   r   rn   r    r    rK   r!   r     sf   #    
   	      7        
c                    s   t  fddt|D S )Nc                    s   g | ]}t  qS r    )copydeepcopy)r   imoduler    r!   
<listcomp>p  s     z_get_clones.<locals>.<listcomp>)r   range)r   Nr    r   r!   rq   n  s    rq   )r4   r   c                 C   s.   | dkrt jS | dkrt jS td|  d S )Nrg   r   z$activation should be relu/gelu, not )rf   rg   r   r\   )r4   r    r    r!   r   s  s
    r   )rX   rY   r&   r   c                 C   sj   |dk}|dkrf| dk	rf|dk	r$|n|  d}t|| j| jd}|   |  krbt| |k }nd}|S )a  Return whether the given attention mask is causal.

    Warning:
    If ``is_causal`` is not ``None``, its value will be returned as is.  If a
    user supplies an incorrect ``is_causal`` hint,

    ``is_causal=False`` when the mask is in fact a causal attention.mask
       may lead to reduced performance relative to what would be achievable
       with ``is_causal=True``;
    ``is_causal=True`` when the mask is in fact not a causal attention.mask
       may lead to incorrect and unpredictable execution - in some scenarios,
       a causal mask may be applied based on the hint, in other execution
       scenarios the specified mask may be used.  The choice may not appear
       to be deterministic, in that a number of factors like alignment,
       hardware SKU, etc influence the decision whether to use a mask or
       rely on the hint.
    ``size`` if not None, check whether the mask is a causal mask of the provided size
       Otherwise, checks for any causal mask.
    TNr:   F)r&   r"   r   r   rj   r   )rX   rY   r&   Zmake_causalr   Zcausal_comparisonr    r    r!   r   |  s      r   )NN)-r   typingr   r   r   r   r   r   r   rp   r   rf   r   r
   r4   r   	containerr   initr   r3   r   Zlinearr   Znormalizationr   __all__r   r@   rl   rm   rh   r   r"   rj   r(   r   r   r   r   r   rq   ri   r   r   r    r    r    r!   <module>   sZ    6 (J     