o
    Tiߥ                     @   s   d dl Z d dlZG 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G dd deZdS )    Nc                   @   s*   e Zd ZdZdddZdd Zdd	 Zd
S )SparsityConfiga   Abstract Configuration class to store `sparsity configuration of a self attention layer`.
    It contains shared property of different block-sparse sparsity patterns. However, each class needs to extend it based on required property and functionality.
       Fc                 C   s*   || _ || _|| _|r|| _dS d| _dS )a  Initialize the Sparsity Pattern Config.

        For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial

        Arguments:
             num_heads: required: an integer determining number of attention heads of the layer.
             block: optional: an integer determining the block size. Current implementation of sparse self-attention is based on blocked sparse matrices. In which this parameter defines size of such blocks, `Block X Block`.
             different_layout_per_head: optional: a boolean determining if each head should be assigned a different sparsity layout; default is false and this will be satisfied based on availability.
           N)	num_headsblockdifferent_layout_per_headnum_layout_headsselfr   r   r    r   b/home/ubuntu/.local/lib/python3.10/site-packages/deepspeed/ops/sparse_attention/sparsity_config.py__init__   s   zSparsityConfig.__init__c                 C   sL   || j  dkrtd| d| j  d|| j  }tj| j||ftjd}|S )aE  Create layout tensor for the given sequence length

        Arguments:
             seq_len: required: an integer determining number of attention heads of the layer.

        Return:
             layout: a tensor of dimension (num_heads, num_blocks, num_blocks) for sparsity layout of all head; initialized with zero
        r   zSequence Length, z&, needs to be dividable by Block size !)dtype)r   
ValueErrortorchzerosr   int64)r
   seq_len
num_blockslayoutr   r   r   setup_layout   s
   

zSparsityConfig.setup_layoutc                 C   s8   | j s|dddddf |d| jddddf< |S )a  If all heads require same sparsity layout, it propagate first head layout to all heads

        Arguments:
             layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head; may not be completely set at this step

        Return:
             layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head
        r   Nr   )r   r   )r
   r   r   r   r   %check_and_propagate_first_head_layout0   s   
.z4SparsityConfig.check_and_propagate_first_head_layoutNr   F)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   
   s
    
r   c                       s*   e Zd ZdZd fdd	Zdd Z  ZS )	DenseSparsityConfigzConfiguration class to store `Dense` configuration.
    In reality, this is not sparse and all blocks are used. We keep it for the sake of comparison and comprehension.
    r   Fc                    s   t  ||| dS )a!  Initialize the Dense Sparsity Pattern Config.
        In reality, this is not sparse and all blocks are used. We keep it for the sake of comparison and comprehension.

        Arguments:
             num_heads: required: an integer determining number of attention heads of the layer.
             seq_len: required: an integer determining number of attention heads of the layer.
             different_layout_per_head: optional: this is just for the sake of consistency with other sparsity formats; can ignore it for DenseSparsityConfig
        N)superr   r	   	__class__r   r   r   D   s   
zDenseSparsityConfig.__init__c                 C   s(   |  |}d|ddddddf< |S )a  Set 1 to all blocks of the layout meaning the pattern is dense; not sparse.

        Arguments:
             seq_len: required: an integer determining the underling sequence length; must be <= max sequence length

        Return:
             layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head; for dense everything is 1
        r   N)r   )r
   r   r   r   r   r   make_layoutP   s   

zDenseSparsityConfig.make_layoutr   )r   r   r   r   r   r"   __classcell__r   r   r    r   r   ?   s    r   c                       sH   e Zd ZdZ							d fdd	Zd	d
 Zdd Zdd Z  ZS )FixedSparsityConfigaI  Configuration class to store `Fixed` sparsity configuration.
    For more details about this sparsity config, please see `Generative Modeling with Sparse Transformers`: https://arxiv.org/abs/1904.10509; this has been customized.
    This class extends parent class of `SparsityConfig` and customizes it for `Fixed` sparsity.
    r   F   r   bidirectionalc	           	   
      s   t  ||| || _|| dkrtd| d| d|| _|dkr+|dkr+td|| _|dkr8|r8td|| _|d	krE|sEtd
||| kr^td| d| d| d||  d	|| _dS )a	  Initialize `Fixed` Sparsity Pattern Config.

        For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial

        Arguments:
             num_heads: required: an integer determining number of attention heads of the layer.
             block: optional: an integer determining the block size. Current implementation of sparse self-attention is based on blocked sparse matrices. In which this parameter defines size of such blocks, `Block X Block`.
             different_layout_per_head: optional: a boolean determining if each head should be assigned a different sparsity layout; default is false and this will be satisfied based on availability.
             num_local_blocks: optional: an integer determining the number of blocks in local attention window.
             num_global_blocks: optional: an integer determining how many consecutive blocks in a local window is used as the representative of the window for global attention.
             attention: optional: a string determining attention type. Attention can be `unidirectional`, such as autoregressive models, in which tokens attend only to tokens appear before them in the context. Considering that, the upper triangular of attention matrix is empty as above figure. Or it can be `bidirectional`, such as BERT, in which tokens can attend to any other tokens before or after them. Then, the upper triangular part of the attention matrix is mirror of the lower triangular in the above figure.
             horizontal_global_attention: optional: a boolean determining if blocks that are global representative of a local window, also attend to all other blocks. This is valid only if attention type is `bidirectional`. Looking at the attention matrix, that means global attention not only includes the vertical blocks, but also horizontal blocks.
             num_different_global_patterns: optional: an integer determining number of different global attentions layouts. While global attention can be fixed by which block/s are representative of any local window, since there are multi-heads, each head can use a different global representative. For example, with 4 blocks local window and global attention size of 1 block, we can have 4 different versions in which the first, Second, third, or forth block of each local window can be global representative of that window. This parameter determines how many of such patterns we want. Of course, there is a limitation based on num_local_blocks and num_global_blocks.
        r   z$Number of blocks in a local window, z0, must be dividable by number of global blocks, r   unidirectionalr&   ;only "uni/bi-directional" attentions are supported for now!Ionly "bi-directional" attentions can support horizontal global attention!r   zNumber of different layouts cannot be more than one when you have set a single layout for all heads! Set different_layout_per_head to True.z;Number of layout versions (num_different_global_patterns), zZ, cannot be larger than number of local window blocks divided by number of global blocks, z / z = N)	r   r   num_local_blocksr   num_global_blocksNotImplementedError	attentionhorizontal_global_attentionnum_different_global_patterns)	r
   r   r   r   r*   r+   r-   r.   r/   r    r   r   r   e   s,    
zFixedSparsityConfig.__init__c                 C   sr   |j d }td|| jD ]*}t|| j |}t||D ]}t|| jdkr(|d n|D ]	}d||||f< q+qq|S )a  Sets local attention layout used by the given head in the sparse attention.

        Arguments:
             h: required: an integer determining head index
             layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head; may not be completely set at this step

        Return:
             layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head in which local layout is set
        r   r   r'   )shaperanger*   minr-   )r
   hr   r   iendrowcolr   r   r   set_local_layout   s   
 z$FixedSparsityConfig.set_local_layoutc           	      C   s  |j d }| jd|| j  | j  }||| j  }t||| jD ]*}| jdkr)dn|}d|||d||| j f< | jrJd||||| j ddf< q ||k rt|| || j }|| j }| jdkredn|}d|||d||f< | jrd||||ddf< |S )a-  Sets global attention layout used by the given head in the sparse attention.

        Currently we set global blocks starting from the last block of a local window to the first one. That means if a local window consists of 4 blocks and global attention size is one block, we use block #4 in each local window as global. If we have different layout per head, then other heads will get #3, #2, and #1. And if we have more heads (and different layout has set) than num of global attentions, multiple head may have same global attentions.
        Note) if horizontal_global_attention is set, global blocks will be set both horizontally and vertically.

        Arguments:
             h: required: an integer determining head index
             layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head; may not be completely set at this step

        Return:
             layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head in which global layout is set
        r   r&   r   N)r0   r*   r/   r+   r1   r-   r.   r2   )	r
   r3   r   r   first_global_block_idxr5   r4   	first_rowstartr   r   r   set_global_layout   s&   

z%FixedSparsityConfig.set_global_layoutc                 C   B   |  |}td| jD ]}| ||}| ||}q| |}|S )aW  Generates `Fixed` sparsity layout used by each head in the sparse attention.

        Arguments:
             seq_len: required: an integer determining number of attention heads of the layer.

        Return:
             layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing `Fixed` sparsity layout of all head
        r   )r   r1   r   r8   r<   r   r
   r   r   r3   r   r   r   r"         


zFixedSparsityConfig.make_layout)r   Fr%   r   r&   Fr   )	r   r   r   r   r   r8   r<   r"   r#   r   r   r    r   r$   _   s    40r$   c                       sV   e Zd ZdZddddgdgdddf fdd		Zd
d Zdd Zdd Zdd Z  Z	S )VariableSparsityConfigaO  Configuration class to store `Variable` sparsity configuration.
    This layout is an extension of FixedSparsityConfig in which:
      - user can set random layout; default value is zero means no random block
      - user can provide a list of local block sizes
      - user can provide a list of global block indices.

    For more details about `Fixed` sparsity config, please see `Generative Modeling with Sparse Transformers`: https://arxiv.org/abs/1904.10509; this has been customized.
    This class extends parent class of `SparsityConfig` and customizes it for `Fixed` sparsity.
    r   Fr   r%   Nr&   c
                    s   t  ||| || _|| _|| _|durIt|t|kr,tdt| dt| dtt||D ]\}
\}}||krHtd| d| dq3|| _	|dkrX|dkrXt
d	|| _|dkre|	retd
|	| _dS )a  Initialize `Variable` Sparsity Pattern Config.

        For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial

        Arguments:
             num_heads: required: an integer determining number of attention heads of the layer.
             block: optional: an integer determining the block size. Current implementation of sparse self-attention is based on blocked sparse matrices. In which this parameter defines size of such blocks, `Block X Block`.
             different_layout_per_head: optional: a boolean determining if each head should be assigned a different sparsity layout; default is false and this will be satisfied based on availability. Currently this sparsity config can only assign single layout to all heads; needs to be extended for different layout per head.
             num_random_blocks: optional: an integer determining the number of random blocks in each block row.
             local_window_blocks: optional: a list of integers determining the number of blocks in each local attention window. It assumes first number determines # of blocks in the first local window, second the second window, ..., and the last number determines the number of blocks in the remaining local windows.
             global_block_indices: optional: a list of integers determining which blocks are considered as global attention. Given indices, determine the blocks that all other token blocks attend to and they attend to all other token blocks. Default value is only index 0. Notice that if global_block_end_indices parameter is set, this parameter is used as starting index of each global window.
             global_block_end_indices: optional: a list of integers determining end indices of global window blocks. By default this is not used. But if it is set, it must have the same size of global_block_indices parameter, and combining this two parameters, for each index i, blocks from global_block_indices[i] to global_block_end_indices[i] (exclusive) are considered as global attention.
             num_global_blocks: optional: an integer determining how many consecutive blocks in a local window is used as the representative of the window for global attention.
             attention: optional: a string determining attention type. Attention can be `unidirectional`, such as autoregressive models, in which tokens attend only to tokens appear before them in the context. Considering that, the upper triangular of attention matrix is empty as above figure. Or it can be `bidirectional`, such as BERT, in which tokens can attend to any other tokens before or after them. Then, the upper triangular part of the attention matrix is mirror of the lower triangular in the above figure.
             horizontal_global_attention: optional: a boolean determining if blocks that are global representative of a local window, also attend to all other blocks. This is valid only if attention type is `bidirectional`. Looking at the attention matrix, that means global attention not only includes the vertical blocks, but also horizontal blocks.
        N#Global block start indices length, 3, must be same as global block end indices length, r   Global block start index, /, must be smaller than global block end index, r'   r&   r(   r)   )r   r   num_random_blockslocal_window_blocksglobal_block_indiceslenr   	enumeratezipglobal_block_end_indicesr,   r-   r.   )r
   r   r   r   rE   rF   rG   rK   r-   r.   _	start_idxend_idxr    r   r   r      s,   
zVariableSparsityConfig.__init__c                 C   sb   |j d }|| jk rtd| j d| dtd|D ]}ttd|| j}d||||f< q|S )  Sets random attention layout used by the given head in the sparse attention.
        Note) By default, it assumes there will be a unique random block layout for all heads; unless `different_layout_per_head` parameter is set in which each head can have a different random layout.

        Arguments:
             h: required: an integer determining head index
             layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head; may not be completely set at this step

        Return:
             layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head in which random layout is set
        r   Number of random blocks, :, must be smaller than overall number of blocks in a row, r   r   )r0   rE   r   r1   randomsample)r
   r3   r   r   r6   rnd_colsr   r   r   set_random_layout/  s   

z(VariableSparsityConfig.set_random_layoutc           
      C   s   |j d }d}d}| jD ]/}||7 }t||}t||D ]}t|| jdkr)|d n|D ]	}d||||f< q,q||7 }qt|||D ])}	t|	| |}t|	|D ]}t|	| jdkr]|d n|D ]	}d||||f< q`qPqB|S )a  Sets local attention layout used by the given head in the sparse attention.
        Arguments:
             h: required: an integer determining head index
             layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head; may not be completely set at this step

        Return:
             layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head in which local layout is set
        r   r   r'   )r0   rF   r2   r1   r-   )
r
   r3   r   r   start_block_idxend_block_idx
block_sizer6   r7   r4   r   r   r   r8   E  s&   



 
 z'VariableSparsityConfig.set_local_layoutc           	      C   s   |j d }| jdu r4| jD ]$}||k r1| jrd|||ddf< | jdkr&dn|}d|||d|f< q|S tt| j| jD ]1\}\}}||k rnt||}| jrZd||||ddf< | jdkradn|}d|||d||f< q=|S )  Sets global attention layout used by the given head in the sparse attention.

        Arguments:
             h: required: an integer determining head index
             layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head; may not be completely set at this step

        Return:
             layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head in which global layout is set
        r   Nr&   r   )r0   rK   rG   r.   r-   rI   rJ   r2   )	r
   r3   r   r   idxr:   rL   rM   rN   r   r   r   r<   b  s&   



z(VariableSparsityConfig.set_global_layoutc                 C   N   |  |}td| jD ]}| ||}| ||}| ||}q| |}|S )a]  Generates `Variable` sparsity layout used by each head in the sparse attention.

        Arguments:
             seq_len: required: an integer determining number of attention heads of the layer.

        Return:
             layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing `Variable` sparsity layout of all head
        r   )r   r1   r   rU   r8   r<   r   r>   r   r   r   r"        


z"VariableSparsityConfig.make_layout)
r   r   r   r   r   rU   r8   r<   r"   r#   r   r   r    r   r@      s    5%r@   c                       sN   e Zd ZdZ						d fdd	Zd	d
 Zdd Zdd Zdd Z  Z	S )BigBirdSparsityConfiga5  Configuration class to store `BigBird` sparsity configuration.
    For more details about this sparsity config, please see `Big Bird: Transformers for Longer Sequences`: https://arxiv.org/pdf/2007.14062.pdf
    This class extends parent class of `SparsityConfig` and customizes it for `BigBird` sparsity.
    r   Fr      r&   c                    sD   t  ||| || _|| _|| _|dkr|dkrtd|| _dS )a  Initialize the BigBird Sparsity Pattern Config.

        For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial

        Arguments:
             num_heads: required: an integer determining number of attention heads of the layer.
             block: optional: an integer determining the block size. Current implementation of sparse self-attention is based on blocked sparse matrices. In which this parameter defines size of such blocks, `Block X Block`.
             different_layout_per_head: optional: a boolean determining if each head should be assigned a different sparsity layout; default is false and this will be satisfied based on availability.
             num_random_blocks: optional: an integer determining the number of random blocks in each block row.
             num_sliding_window_blocks: optional: an integer determining the number of blocks in sliding local attention window.
             num_global_blocks: optional: an integer determining how many consecutive blocks, starting from index 0, are considered as global attention. Global block tokens will be attended by all other block tokens and will attend to all other block tokens as well.
             attention: optional: a string determining attention type. Attention can be `unidirectional`, such as autoregressive models, in which tokens attend only to tokens appear before them in the context. Considering that, the upper triangular of attention matrix is empty as above figure. Or it can be `bidirectional`, such as BERT, in which tokens can attend to any other tokens before or after them. Then, the upper triangular part of the attention matrix is mirror of the lower triangular in the above figure.
        r'   r&   r(   N)r   r   rE   num_sliding_window_blocksr+   r,   r-   )r
   r   r   r   rE   r_   r+   r-   r    r   r   r     s   
zBigBirdSparsityConfig.__init__c                 C   s~   |j d }|| jk rtd| j d| dtd|D ]!}| jdkr'td|ntd|d }t|| j}d||||f< q|S )rO   r   rP   rQ   r   r   r&   )r0   rE   r   r1   r-   rR   rS   )r
   r3   r   r   r6   sample_rangerT   r   r   r   rU     s   

"z'BigBirdSparsityConfig.set_random_layoutc                 C   |   |j d }|| jk rtd| j d| d| jd }td|D ]}td|| }t|| d |}d|||||f< q |S a  Sets sliding local attention layout used by the given head in the sparse attention.

        Arguments:
             h: required: an integer determining head index
             layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head; may not be completely set at this step

        Return:
             layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head in which local sliding window layout is set
        r   !Number of sliding window blocks, rQ   r      r   r0   r_   r   r1   maxr2   r
   r3   r   r   wr6   r;   r5   r   r   r   set_sliding_window_layout     


z/BigBirdSparsityConfig.set_sliding_window_layoutc                 C   st   |j d }|| jk rtd| j d| dd||d| jddf< d||ddd| jf< | jdkr8t|}|S )rY   r   zNumber of global blocks, rQ   r   r   Nr'   )r0   r+   r   r-   r   tril)r
   r3   r   r   r   r   r   set_global_layout_itc  s   



z+BigBirdSparsityConfig.set_global_layout_itcc                 C   r[   )a[  Generates `BigBird` sparsity layout used by each head in the sparse attention.

        Arguments:
             seq_len: required: an integer determining number of attention heads of the layer.

        Return:
             layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing `BigBird` sparsity layout of all head
        r   )r   r1   r   rU   ri   rl   r   r>   r   r   r   r"     r\   z!BigBirdSparsityConfig.make_layout)r   Fr   r^   r   r&   )
r   r   r   r   r   rU   ri   rl   r"   r#   r   r   r    r   r]     s     r]   c                       sH   e Zd ZdZddddgddf fdd		Zd
d Zdd Zdd Z  ZS )BSLongformerSparsityConfiga  Configuration class to store edited `Longformer` sparsity configuration.

    Note) this is a block-sparse version of the Longformer which is slightly different than original Longformer; which is element-wise sparsity.

    For more details about this sparsity config, please see `Longformer: The Long-Document Transformer`: https://arxiv.org/pdf/2004.05150.pdf
    This class extends parent class of `SparsityConfig` and customizes it for `Longformer` sparsity.
    r   Fr^   r   Nr&   c                    s   t  ||| || _|| _|| _|durIt|t|kr,tdt| dt| dtt||D ]\}\}	}
|	|
krHtd|	 d|
 dq3|| _	dS )aQ  Initialize the edited `Longformer` Sparsity Pattern Config.

        For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial

        Arguments:
             num_heads: required: an integer determining number of attention heads of the layer.
             block: optional: an integer determining the block size. Current implementation of sparse self-attention is based on blocked sparse matrices. In which this parameter defines size of such blocks, `Block X Block`.
             different_layout_per_head: optional: a boolean determining if each head should be assigned a different sparsity layout; default is false and this will be satisfied based on availability.

             num_sliding_window_blocks: optional: an integer determining the number of blocks in sliding local attention window.
             global_block_indices: optional: a list of integers determining which blocks are considered as global attention. Given indices, determine the blocks that all other token blocks attend to and they attend to all other token blocks. Default value is only index 0. Notice that if global_block_end_indices parameter is set, this parameter is used as starting index of each global window.
             global_block_end_indices: optional: a list of integers determining end indices of global window blocks. By default this is not used. But if it is set, it must have the same size of global_block_indices parameter, and combining this two parameters, for each index i, blocks from global_block_indices[i] to global_block_end_indices[i] (exclusive) are considered as global attention.
             attention: optional: a string determining attention type. Attention can be `unidirectional`, such as autoregressive models, in which tokens attend only to tokens appear before them in the context. Considering that, the upper triangular of attention matrix is empty as above figure. Or it can be `bidirectional`, such as BERT, in which tokens can attend to any other tokens before or after them. Then, the upper triangular part of the attention matrix is mirror of the lower triangular in the above figure.
        NrA   rB   r   rC   rD   )
r   r   r_   rG   r-   rH   r   rI   rJ   rK   )r
   r   r   r   r_   rG   rK   r-   rL   rM   rN   r    r   r   r   +  s    
z#BSLongformerSparsityConfig.__init__c                 C   ra   rb   re   rg   r   r   r   ri   T  rj   z4BSLongformerSparsityConfig.set_sliding_window_layoutc                 C   s   |j d }| jdu r'| jD ]}||k r%d|||ddf< d||dd|f< qn/tt| j| jD ]%\}\}}||k rUt||}d||||ddf< d||dd||f< q0| jdkr`t|}|S )rY   r   Nr'   )	r0   rK   rG   rI   rJ   r2   r-   r   rk   )r
   r3   r   r   rZ   rL   rM   rN   r   r   r   r<   l  s"   


	


z,BSLongformerSparsityConfig.set_global_layoutc                 C   r=   )aj  Generates edited `Longformer` sparsity layout used by each head in the sparse attention.

        Arguments:
             seq_len: required: an integer determining number of attention heads of the layer.

        Return:
             layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing `BSLongformer` sparsity layout of all head
        r   )r   r1   r   ri   r<   r   r>   r   r   r   r"     r?   z&BSLongformerSparsityConfig.make_layout)	r   r   r   r   r   ri   r<   r"   r#   r   r   r    r   rm   "  s    
)#rm   c                       s2   e Zd ZdZd fdd	Zdd Zd	d
 Z  ZS ) LocalSlidingWindowSparsityConfigzConfiguration class to store `Local Sliding Window` sparsity configuration - a purely-local sliding window attention.
    This class extends parent class of `SparsityConfig` and customizes it for `Local` sparsity.
    r   r^   r'   c                    s   t  || || _|| _dS )ak  Initialize the Local Sliding Window Sparsity Pattern Config.
        For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial
        Arguments:
             num_heads: required: an integer determining number of attention heads of the layer.
             block: optional: an integer determining the block size. Current implementation of sparse self-attention is based on blocked sparse matrices. In which this parameter defines size of such blocks, `Block X Block`.
             num_sliding_window_blocks: optional: an integer determining the number of blocks in sliding local attention window.
	     attention: optional: a string determining attention type. Attention can be `unidirectional`, such as autoregressive models, in which tokens attend only to tokens appear before them in the context. Considering that, the upper triangular of attention matrix is empty as above figure. Or it can be `bidirectional`, such as BERT, in which tokens can attend to any other tokens before or after them. Then, the upper triangular part of the attention matrix is mirror of the lower triangular in the above figure.
        N)r   r   r_   r-   )r
   r   r   r_   r-   r    r   r   r     s   

z)LocalSlidingWindowSparsityConfig.__init__c                 C   s   |j d }|| jk rtd| j d| d| jd }td|D ]$}td|| }| jdkr7t|| d |n|d }d|||||f< q |S )a  Sets sliding local attention layout used by the given head in the sparse attention.
        Arguments:
             h: required: an integer determining head index
             layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head; may not be completely set at this step
        Return:
             layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head in which local sliding window layout is set
        r   rc   rQ   r   rd   r   r&   )r0   r_   r   r1   rf   r-   r2   rg   r   r   r   ri     s   
	

$z:LocalSlidingWindowSparsityConfig.set_sliding_window_layoutc                 C   s6   |  |}td| jD ]}| ||}q| |}|S )af  Generates `Local Sliding Window` sparsity layout used by each head in the sparse attention.
        Arguments:
             seq_len: required: an integer determining number of attention heads of the layer.
        Return:
             layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing `BigBird` sparsity layout of all head
        r   )r   r1   r   ri   r   r>   r   r   r   r"     s
   

z,LocalSlidingWindowSparsityConfig.make_layout)r   r^   r'   )r   r   r   r   r   ri   r"   r#   r   r   r    r   rn     s
    rn   )	r   rR   r   r   r$   r@   r]   rm   rn   r   r   r   r   <module>   s   5   -  