
    ^j+                        d dl Z ddlmZ ddlmZ  ej
                  e      ZdZdZ	dZ
dadefd	Ze j                  j                  d
d      de j                   de j                   de j                   de j                   de j                   de j                   dedededededededede j                   fd       Zej(                  d        Zde j                   deddfd Zd! Z	 	 	 	 d(d"e j0                  j2                  de j                   d#e j                   d$e j                   d%e j                   dz  dededz  d&e j                   dz  dee j                   df   fd'Zy))    N   )logging   )sdpa_attention_forward)                attn_implementationc                    t         t         S ddlm} | j                  d      d   }|j	                  d      \  }}} |||xs d|rdndd	      }d
D ]*  }t        t        ||d            rt        d| d| d       |a t         S )aw  Load the MSA hub kernel once and verify the expected callables are present.

    The ``attn_implementation`` string may carry a ``paged|`` prefix and/or an ``@<revision>`` pin
    (e.g. ``kernels-staging/msa@v0``); the build currently lives on the repo's ``v0`` branch. The
    loaded module is cached in a module-level global so registration happens once, not per call.
    Nr   )
get_kernel|@r   T)revisionversionallow_all_kernels)sparse_atten_funcbuild_k2q_csrzThe MSA kernel loaded from `z` does not expose a callable `zK`. Make sure you request a compatible build, e.g. `kernels-staging/msa@v0`.)_MSA_KERNELhub_kernelsr   split	partitioncallablegetattrImportError)r   r   repo_id_revkernelfn_names          r/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/integrations/msa_attention.pyload_and_register_msa_kernelr$       s     '!'',R0G'',OGQ#+stPQeijF9 67.wi7UV]U^ _[ [  K    ztransformers_msa::sparse_atten )mutates_argsqkvq2kcu_seqlens_qcu_seqlens_ktopk
block_sizetotal_kmax_seqlen_qmax_seqlen_kqheads_per_kvscalingimplreturnc                 F   t        |      }t        j                  j                  | j                        5  |j	                  ||||||
|	|      \  }}|j                  | ||||||||	|
|d|      }ddd       |j                         S # 1 sw Y   j                         S xY w)a$  Opaque wrapper around the CuTe-DSL CSR build + block-sparse kernel.

    Registered as a ``torch.library`` custom op so ``torch.compile(fullgraph=True)`` treats the
    whole CSR-build + attention as a single opaque node (no graph break) and ``reduce-overhead``
    CUDA graphs can capture it. The internal ``build_k2q_csr`` output is data-dependent in shape,
    but it never escapes this op (only the fixed-shape ``[total_q, Hq, D]`` attention output does),
    so the fake/meta impl below is exact. The op is functional (no input mutation).
    )r0   r2   r1   qhead_per_kvT)r,   r-   r1   r2   blk_kvcausalsoftmax_scaleN)r$   torchcudadevicer   r   
contiguous)r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   msak2q_row_ptrk2q_q_indicesattn_outputs                     r#   _msa_sparse_atten_oprD   <   s    2 't
,C 
		188	$ 
%(%6%6%%& &7 	&
"] ++%%%%! , 

4 !!##5
4 !!##s   ;BB c                 ,    t        j                  |       S N)r<   
empty_like)r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   s                 r#   _msa_sparse_atten_fakerH   u   s    $ Ar%   querydropoutc                    |j                   j                  dk7  s/t        j                  j	                  |j                         d   dk7  rt        d      |j                  d   t        k7  rt        dt         d      | j                  j                  t        k7  rt        dt         d      |d	k7  rt        d
      | j                  j                  }|t        vrt        dt         d| d      y)a  Validate kernel capability, dropout and configured topk once per attention module.

    Mirrors the flash-attention integration, which checks capability/dropout at model init rather
    than on every forward. The check is cached on the module so the hot path never re-runs it.

    There is no SDPA fallback: a sparse layer either runs the MSA kernel or this raises. Serves both
    prefill (q_len > 1) and single-token decode (q_len == 1) -- decode is just a varlen call with one
    query slot, so there is no context-length threshold.
    r=   r   
   zMSA block-sparse attention requires an SM100 / Blackwell CUDA device. Select a different `attn_implementation` on unsupported hardware.r   z2MSA block-sparse attention only supports head_dim .z4MSA block-sparse attention only supports block_size         zYMSA block-sparse attention does not support attention dropout; set `attention_dropout=0`.z1MSA block-sparse attention only supports topk in z, got `z0`. Set `index_topk_blocks` to a supported value.N)r>   typer<   r=   get_device_capabilityRuntimeErrorshapeMSA_SUPPORTED_HEAD_DIM
ValueErrorindexerr/   MSA_SUPPORTED_BLOCK_SIZEtopk_blocksMSA_SUPPORTED_TOPK)modulerI   rJ   r.   s       r#   _validate_msa_initrZ      s     ||F"ejj&F&Fu||&TUV&W[]&]P
 	
 {{200MNdMeefghh~~  $<<OPhOiijkll#~tuu>>%%D%%?@R?SSZ[_Z` a< <
 	
 &r%   c                    |j                   \  }}	}
}|j                   d   |j                   d   }}|	|z  }|j                   d   t        fdt        D              }|k7  rB|j                  g |j                   d d |z
  d      }t	        j
                  ||gd      }||j                  dd      j                  ||
z  |	|      j                         }|j                  dd      j                  ||z  ||      j                         }|j                  dd      j                  ||z  ||      j                         }t	        j                  d|dz   |
z  |
|j                  t        j                        }|dk(  r||z|d   dz   j                  t        j                        j                  d      }t	        j
                  t	        j                  d|j                  t        j                        |g      }n8t	        j                  d|dz   |z  ||j                  t        j                        }|j                  t        j                        }|j                  dddd      j                  |||
z        j                         }t        |||||||||z  |
|||| j                   j"                        }|j                  ||
|	|      S )	Nr   r   r   c              3   .   K   | ]  }|k\  s	|  y wrF   r&   ).0tr.   s     r#   	<genexpr>z$_sparse_attention.<locals>.<genexpr>   s     BQT	qBs   
)dimr   )r>   dtype   )rR   nextrX   new_fullr<   cat	transposereshaper?   aranger>   int32tozerospermuterD   config_attn_implementation)rY   rI   keyvaluer4   block_indicesr/   cache_positionbsznum_q_headsq_lenhead_dimnum_kv_headsk_lenr3   padded_topkpadr(   r)   r*   r,   valid_kr-   r+   rC   r.   s                            @r#   _sparse_attentionr|      s   (-%CeX))A,		!%L</Mr"D B"4BBKd$$%T}':':3B'?%TtAS%TVXY		=#"6B?
 	1%%cEk;ITTVAa##C%KxHSSUA1%%cEk<JUUWA<<C!Gu#4eAHHTYT_T_`L axN.!"%)--ekk:BB1Eyy%++a"TV]!^_||Aa5'8%X]XcXcd
 

5;;
'C
++aAq
!
)
),eT
J
U
U
WC '			e**K  sE;AAr%   rY   ro   rp   attention_maskrq   c           
         ||j                   d   dz  }|t        | ||||f||d|S t        | dd      st        | ||       d| _        | j
                  j                  }	|j                  d      }
t        | ||||||	|
      }|dfS )	zn
    TODO: this opens a door to per-layer attn implementation which is something we might want lalter on.
    Nr   g      )rJ   r4   _msa_validatedFTrr   )	rR   r   r   rZ   r   rU   r/   getr|   )rY   rI   ro   rp   r}   rJ   r4   rq   kwargsr/   rr   rC   s               r#   msa_attention_forwardr      s     ++b/T) %E3~
?FPW
[a
 	
 6+U365'2 $**JZZ 01N#FE3wWacqrKr%   )NrN   NN)r<   utilsr   sdpa_attentionr   
get_logger__name__loggerrX   rV   rS   r   strr$   library	custom_opTensorintfloatrD   register_fakerH   rZ   r|   nnModuletupler   r&   r%   r#   <module>r      s     2 
		H	% $   c 8 9K5$||5$||5$ ||5$ 
	5$
 ,,5$ ,,5$ 5$ 5$ 5$ 5$ 5$ 5$ 5$ 5$ \\5$ L5$p ## $(
ell 
U 
t 
:<BH +/ )- HHOO <<  
  <<	 
 LL4'    T\  <<$&  5<< r%   