o
     i                     @   sv   d Z 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dS )z
The code has been adopted from DeepSpeed
(https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/ops/sparse_attention/sparsity_config.py)
    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.
        Arguments:
             num_heads: required: an integer determining number of attention heads of the layer.
             block_size: 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_sizedifferent_layout_per_headnum_layout_headsselfr   r   r    r   a/home/ubuntu/.local/lib/python3.10/site-packages/xformers/components/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 )aS  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_layout:   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.
             block_size: 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: this is just for the sake of consistency with
             other sparsity formats; can ignore it for DenseSparsityConfig
        N)superr   r	   	__class__r   r   r   O   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 meanins 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_layout^   s   

zDenseSparsityConfig.make_layoutr   )r   r   r   r   r   r"   __classcell__r   r   r    r   r   I   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 )FixedSparsityConfigaM  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_size: 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, zD,
                    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   t   sD   ,
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 )ar  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)r1   r*   r/   r+   r2   r-   r.   r3   )	r
   r4   r   r   first_global_block_idxr6   r5   	first_rowstartr   r   r   set_global_layout   s,   

z%FixedSparsityConfig.set_global_layoutc                 C   B   |  |}td| jD ]}| ||}| ||}q| |}|S )ae  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   r2   r   r9   r=   r   r
   r   r   r4   r   r   r   r"        
	
zFixedSparsityConfig.make_layout)r   Fr%   r   r&   Fr   )	r   r   r   r   r   r9   r=   r"   r#   r   r   r    r   r$   m   s    	P8r$   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 )VariableSparsityConfigaR  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_size: 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.
             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, G, must be same as
                    global block end indices length, r   Global block start index, G, 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   rF   rG   rH   rL   r-   r.   _	start_idxend_idxr    r   r   r   .  s@   2
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 )a  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, J, must be smaller than overall number
                of blocks in a row, r   r   )r1   rF   r   r2   randomsample)r
   r4   r   r   r7   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 r0   )r1   rG   r3   r2   r-   )
r
   r4   r   r   start_block_idxend_block_idxr   r7   r8   r5   r   r   r   r9     s2   



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   )r1   rL   rH   r.   r-   rJ   rK   r3   )	r
   r4   r   r   idxr;   rM   rN   rO   r   r   r   r=     s*   



z(VariableSparsityConfig.set_global_layoutc                 C   N   |  |}td| jD ]}| ||}| ||}| ||}q| |}|S )ak  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   r2   r   rU   r9   r=   r   r?   r   r   r   r"        
	
z"VariableSparsityConfig.make_layout)
r   r   r   r   r   rU   r9   r=   r"   r#   r   r   r    r   rA   #  s    T%'rA   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 )BigBirdSparsityConfiga9  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_size: 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   rF   num_sliding_window_blocksr+   r,   r-   )r
   r   r   r   rF   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 )a  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   rP   rQ   r   r   r&   )r1   rF   r   r2   r-   rR   rS   )r
   r4   r   r   r7   sample_rangerT   r   r   r   rU   0  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, zJ, must be smaller than
                overall number of blocks in a row, r      r   r1   r^   r   r2   maxr3   r
   r4   r   r   wr7   r<   r6   r   r   r   set_sliding_window_layoutN     



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 )a  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   zNumber of global blocks, rQ   r   r   Nr'   )r1   r+   r   r-   r   tril)r
   r4   r   r   r   r   r   set_global_layout_itcg  s   




z+BigBirdSparsityConfig.set_global_layout_itcc                 C   rZ   )af  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   r2   r   rU   rg   rj   r   r?   r   r   r   r"     r[   z!BigBirdSparsityConfig.make_layout)r   Fr   r]   r   r&   )
r   r   r   r   r   rU   rg   rj   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 )as	  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_size: 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.
        NrB   rC   r   rD   rE   )
r   r   r^   rH   r-   rI   r   rJ   rK   rL   )r
   r   r   r   r^   rH   rL   r-   rM   rN   rO   r    r   r   r     s,   (
z#BSLongformerSparsityConfig.__init__c                 C   r`   )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   ra   zJ, must be smaller
                than overall number of blocks in a row, r   rb   r   rc   re   r   r   r   rg     rh   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 )rX   r   Nr'   )	r1   rL   rH   rJ   rK   r3   r-   r   ri   )r
   r4   r   r   rY   rM   rN   rO   r   r   r   r=     s&   


	


z,BSLongformerSparsityConfig.set_global_layoutc                 C   r>   )ax  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   r2   r   rg   r=   r   r?   r   r   r   r"     r@   z&BSLongformerSparsityConfig.make_layout)	r   r   r   r   r   rg   r=   r"   r#   r   r   r    r   rk     s    >%rk   )	r   rR   r   r   r   r$   rA   r\   rk   r   r   r   r   <module>   s   :$ 7 X 