§
     ’Þj¥)  ã                  óâ   — d dl mZ d dlmZ d dlmZmZ d dlZe G d„ d¦  «        ¦   «         Ze G d„ d¦  «        ¦   «         Z	 G d	„ d
¦  «        Z
ddd„Z G d„ d¦  «        Z G d„ d¦  «        ZdS )é    )Úannotations)Ú	dataclass)ÚCallableÚIterableNc                  ó   — e Zd ZdZdd
„ZdS )ÚGraphKVIndexWriterzNWrites decode K/V values at the absolute token position provided by input_pos.Úk_cacheútorch.TensorÚv_cacheÚk_valÚv_valÚ	input_posÚreturnÚNonec                ó¨  — |                      d¦  «        d d…         }|j        t          j        k    r |                     t          j        ¬¦  «        }|j        |j        k    r|                     |j        ¬¦  «        }|d |j        d         …                              d||¦  «         |d |j        d         …                              d||¦  «         d S )Néÿÿÿÿé   )Údtype)Údevicer   )Úreshaper   ÚtorchÚlongÚtor   ÚshapeÚindex_copy_)Úselfr	   r   r   r   r   Úindexs          úHC:\Users\johnn\OneDrive\Documents\AI\shared\llm_engines\cudagraph_kit.pyÚwritezGraphKVIndexWriter.write   s¾   € Ø×!Ò! "Ñ%Ô% b q bÔ)ˆØŒ;�%œ*Ò$Ð$Ø—H’H¥5¤:�HÑ.Ô.ˆEØŒ<˜7œ>Ò)Ð)Ø—H’H G¤N�HÑ3Ô3ˆEØÐ �%”+˜a”.Ð Ô!×-Ò-¨a°¸Ñ>Ô>Ð>ØÐ �%”+˜a”.Ð Ô!×-Ò-¨a°¸Ñ>Ô>Ð>Ð>Ð>ó    N)r	   r
   r   r
   r   r
   r   r
   r   r
   r   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   © r    r   r   r   
   s.   € € € € € àXÐXð?ð ?ð ?ð ?ð ?ð ?r    r   c                  ó"   — e Zd ZU dZdZded<   dS )ÚGraphKVFlashStatezGMarks a cache as using flash_attn_with_kvcache-compatible graph decode.TÚboolÚflash_kvcacheN)r!   r"   r#   r$   r)   Ú__annotations__r%   r    r   r'   r'      s)   € € € € € € àQÐQà€MÐÐÐÑÐÐr    r'   c                  ó:   — e Zd ZdZdd„Zdd„Zdd„Zdd„Zdd„ZdS )ÚCUDAGraphRunnerz1Captures and replays a fixed-shape CUDA callable.ÚnameÚstrÚfnúCallable[..., object]r   r   c                óL   — || _         || _        d | _        g | _        d | _        d S ©N)Ú_nameÚ_fnÚ_graphÚ_static_inputsÚ_output)r   r-   r/   s      r   Ú__init__zCUDAGraphRunner.__init__"   s*   € ØˆŒ
ØˆŒØ37ˆŒØ24ˆÔØ#ˆŒˆˆr    Úinputsr
   Úobjectc                ó*  — |st          d| j        › d�¦  «        ‚|D ]V}t          j        |¦  «        st	          d| j        › d�¦  «        ‚|j        j        dk    rt          d| j        › d�¦  «        ‚ŒWd„ |D ¦   «         | _        t          j         	                    ¦   «         | _
        	 t          j        ¦   «         5  t          j                             | j
        d¬¦  «        5   | j        | j        Ž | _        d d d ¦  «         n# 1 swxY w Y   d d d ¦  «         n# 1 swxY w Y   t          j        ¦   «         5  | j
                             ¦   «          d d d ¦  «         n# 1 swxY w Y   n## t           $ r |                      ¦   «          ‚ w xY w| j        S )	Nú[z5] CUDAGraphRunner requires at least one tensor input.z-] CUDAGraphRunner accepts tensor inputs only.Úcudaz(] CUDAGraphRunner requires CUDA tensors.c                óZ   — g | ](}|                      ¦   «                              ¦   «         ‘Œ)S r%   )ÚdetachÚclone)Ú.0Útensors     r   ú
<listcomp>z,CUDAGraphRunner._capture.<locals>.<listcomp>1   s,   € ÐLÐLÐL¸6˜vŸ}š}™œ×4Ò4Ñ6Ô6ÐLÐLÐLr    Úthread_local)Úcapture_error_mode)Ú
ValueErrorr3   r   Ú	is_tensorÚ	TypeErrorr   Útyper6   r=   Ú	CUDAGraphr5   Úinference_modeÚgraphr4   r7   ÚreplayÚ	ExceptionÚrelease)r   r9   rB   s      r   Ú_capturezCUDAGraphRunner._capture)   sƒ  € Øð 	dÝÐb ¤ÐbÐbÐbÑcÔcÐcØð 	[ð 	[ˆFÝ”? 6Ñ*Ô*ð _ÝÐ ] D¤JÐ ]Ð ]Ð ]Ñ^Ô^Ð^ØŒ}Ô! VÒ+Ð+Ý Ð!Y T¤ZÐ!YÐ!YÐ!YÑZÔZÐZð ,àLÐLÀVÐLÑLÔLˆÔÝ”j×*Ò*Ñ,Ô,ˆŒð
	ÝÔ%Ñ'Ô'ð Bð BÝ”Z×%Ò% d¤kÀnÐ%ÑUÔUð Bð BØ#+ 4¤8¨TÔ-@Ð#A�D”LðBð Bð Bñ Bô Bð Bð Bð Bð Bð Bð Bøøøð Bð Bð Bð BðBð Bð Bñ Bô Bð Bð Bð Bð Bð Bð Bøøøð Bð Bð Bð Bõ
 Ô%Ñ'Ô'ð %ð %Ø”×"Ò"Ñ$Ô$Ð$ð%ð %ð %ñ %ô %ð %ð %ð %ð %ð %ð %øøøð %ð %ð %ð %øøåð 	ð 	ð 	Ø�LŠL‰NŒNˆNØð	øøøð Œ|Ðsx   Â)E+ Â<'DÃ#DÃ8DÄD	ÄDÄD	ÄDÄE+ ÄDÄE+ Ä"DÄ#E+ Ä9EÅE+ ÅE#Å#E+ Å&E#Å'E+ Å+ Fc                óN  — t          |¦  «        t          | j        ¦  «        k    r=t          d| j        › dt          | j        ¦  «        › dt          |¦  «        › d�¦  «        ‚t	          | j        |¦  «        D ]¬\  }}|j        |j        k    s |j        |j        k    s|j        |j        k    rbt          d| j        › dt          |j        ¦  «        › d|j        › d|j        › dt          |j        ¦  «        › d|j        › d|j        › d�¦  «        ‚| 	                    |¦  «         Œ­d S )	Nr<   z] Expected z inputs, got ú.z"] Static shape mismatch: expected ú z on z, got )
Úlenr6   rF   r3   Úzipr   r   r   ÚtupleÚcopy_)r   r9   Ústatic_tensorrB   s       r   Ú_copy_inputszCUDAGraphRunner._copy_inputs@   sŽ  € Ýˆv‰;Œ;�#˜dÔ1Ñ2Ô2Ò2Ð2ÝÐm ¤ÐmÐm½¸DÔ<OÑ8PÔ8PÐmÐmÕ_bÐciÑ_jÔ_jÐmÐmÐmÑnÔnÐnÝ%(¨Ô)<¸fÑ%EÔ%Eð 	(ð 	(Ñ!ˆM˜6ØŒ|˜}Ô2Ò2Ð2°f´lÀmÔFYÒ6YÐ6YÐ]cÔ]jÐn{ô  oCò  ^Cð  ^CÝ ðT˜œ
ð Tð TÅeÈMÔL_ÑF`ÔF`ð Tð TÐcpÔcvð Tð Tð  }Jô  }Qð Tð TÝ  ¤Ñ.Ô.ðTð TØ17´ðTð TØCIÄ=ðTð Tð Tñô ð ð ×Ò Ñ'Ô'Ð'Ð'ð	(ð 	(r    c                óÎ   — | j         €
 | j        |Ž S  | j        |Ž  t          j        ¦   «         5  | j                              ¦   «          d d d ¦  «         n# 1 swxY w Y   | j        S r2   )r5   rP   rY   r   rK   rM   r7   )r   r9   s     r   ÚrunzCUDAGraphRunner.runK   s©   € ØŒ;ÐØ �4”= &Ð)Ð)ØˆÔ˜6Ð"Ð"ÝÔ!Ñ#Ô#ð 	!ð 	!ØŒK×ÒÑ Ô Ð ð	!ð 	!ð 	!ñ 	!ô 	!ð 	!ð 	!ð 	!ð 	!ð 	!ð 	!øøøð 	!ð 	!ð 	!ð 	!àŒ|Ðs   ¯AÁAÁAc                ó0   — d | _         g | _        d | _        d S r2   )r5   r6   r7   )r   s    r   rO   zCUDAGraphRunner.releaseS   s   € ØˆŒØ ˆÔØˆŒˆˆr    N)r-   r.   r/   r0   r   r   ©r9   r
   r   r:   )r9   r
   r   r   ©r   r   )	r!   r"   r#   r$   r8   rP   rY   r[   rO   r%   r    r   r,   r,      s~   € € € € € Ø;Ð;ð$ð $ð $ð $ðð ð ð ð.	(ð 	(ð 	(ð 	(ðð ð ð ðð ð ð ð ð r    r,   ÚdepthÚintr   úlist[torch.Tensor]c                ó¶  ‡— t          | ¦  «        t          j        u r| j        r| gng S ‰dk    st	          | t          j        j        ¦  «        rg S t	          | t          t          f¦  «        r| }n^t	          | t          ¦  «        r|  
                    ¦   «         }n4t          | d¦  «        r"t          | ¦  «         
                    ¦   «         }ng S ˆfd„|D ¦   «         S )zfThe plain CUDA tensors held by a cache or state object (in lists, tuples, dicts or object attributes).é   Ú__dict__c                ó@   •— g | ]}t          |‰d z   ¦  «        D ]}|‘ŒŒS )r   ©Ú_cuda_tensors)rA   ÚitemrB   r_   s      €r   rC   z!_cuda_tensors.<locals>.<listcomp>g   s4   ø€ ÐRÐRÐR�tµ=ÀÀuÈqÁyÑ3QÔ3QÐRÐR¨ˆFÐRÐRÐRÐRr    )rI   r   ÚTensorÚis_cudaÚ
isinstanceÚnnÚModuleÚlistrV   ÚdictÚvaluesÚhasattrÚvars)Úvaluer_   Úitemss    ` r   rg   rg   Y   sÑ   ø€ åˆE�{„{•e”lÐ"Ð"Øœ-Ð/�ˆwˆw¨RÐ/Øˆq‚y€y•J˜u¥e¤h¤oÑ6Ô6€yØˆ	Ý�%�$¥˜Ñ'Ô'ð ØˆˆÝ	�E�4Ñ	 Ô	 ð Ø—’‘”ˆˆÝ	�˜
Ñ	#Ô	#ð Ý�U‘”×"Ò"Ñ$Ô$ˆˆàˆ	ØRÐRÐRÐR˜uÐRÑRÔRÐRr    c                  ó   — e Zd ZdZdd„ZdS )	Ú_Stagea-  A decoding step of the kit as an MMGP graph stage of its owner's model. MMGP keys a stage's graphs by the module (the owner, or the
    part of it that the steps run: the weights the step reads) and the method: one function per runner name, kept as an attribute of that
    module while the kit lives.Ú	attributer.   r   r   c                óD   ‡ — d ‰ _         |‰ _        dˆ fd„}||j        |<   d S )Nr9   r
   r   r:   c                 ó   •—  ‰j         | Ž S r2   )r/   )r9   r   s    €r   Ústepz_Stage.__init__.<locals>.steps   s   ø€ Ø�4”7˜FÐ#Ð#r    r]   )r/   rw   rd   )r   Úownerrw   rz   s   `   r   r8   z_Stage.__init__o   sA   ø€ Ø04ˆŒØ"ˆŒð	$ð 	$ð 	$ð 	$ð 	$ð 	$à$(ˆŒ�yÑ!Ð!Ð!r    N)rw   r.   r   r   )r!   r"   r#   r$   r8   r%   r    r   rv   rv   j   s2   € € € € € ð#ð #ð)ð )ð )ð )ð )ð )r    rv   c                  ó>   — e Zd ZdZddd„Zdd
„Zddd„Zdd„Zdd„ZdS ) ÚAutoRegressiveCudaGraphKita  Reusable helper to attach graph-safe KV writers and replay decode callables.

    With an owner that MMGP manages with CUDA graphs (its handler lists it in cudaGraphs), a decoding step is an MMGP graph stage: one
    graph while the owner's weights are all in VRAM, otherwise the step runs with each layer replayed from its own MMGP graph, whether
    the layer is kept in VRAM or streamed. The caches the steps read go through register_state. Other owners keep the kit's own graphs,
    which need the weights in place. resident: the module the steps run when it is only a part of the owner (e.g. its language model):
    its weights alone key the graphs (the owner's other blocks may stream meanwhile) and its blocks in VRAM are enough for a single graph
    per step.Nr-   r.   r   r   c                ó²   — || _         || _        |€|n|| _        |�d| j        _        i | _        i | _        d| _        g | _        t          ¦   «         | _	        d S )NTF)
r3   Ú_ownerÚ	_residentÚ_mm_graph_placement_keyÚ_runnersÚ_stagesÚ_state_registeredÚ_attached_cachesÚsetÚ_attached_cache_ids)r   r-   r{   Úresidents       r   r8   z#AutoRegressiveCudaGraphKit.__init__‚   s`   € ØˆŒ
ØˆŒØ"*Ð"2˜˜¸ˆŒØÐØ59ˆDŒNÔ2Ø46ˆŒØ*,ˆŒØ!&ˆÔØ.0ˆÔÝ-0©U¬UˆÔ Ð Ð r    Úholdersr:   c                ó¤   — | j         €dS ddlm} d„ |D ¦   «         }|                     | j         | j        |d„ |D ¦   «         ¬¦  «         d| _        dS )aj  The CUDA tensors (KV caches, static buffers) that the steps read or update besides the owner's weights and the step inputs,
        at fixed addresses until release(): MMGP owners only (a no-op otherwise). Registering new tensors drops the graphs. The cache
        objects among the holders (e.g. a transformers StaticCache) may be passed to the owner's layers.Nr   ©Úcuda_graphsc                ó6   — g | ]}t          |¦  «        D ]}|‘ŒŒS r%   rf   )rA   ÚholderrB   s      r   rC   z=AutoRegressiveCudaGraphKit.register_state.<locals>.<listcomp>•   s-   € ÐTÐTÐT˜f½mÈFÑ>SÔ>SÐTÐT°F�6ÐTÐTÐTÐTr    c           	     ól   — g | ]1}t          |t          j        t          t          t
          f¦  «        °/|‘Œ2S r%   )rk   r   ri   rn   rV   ro   )rA   rŽ   s     r   rC   z=AutoRegressiveCudaGraphKit.register_state.<locals>.<listcomp>–   sz   € ð  Nið  Nið  NiÐY_Õr|ð  ~Dõ  GLô  GSõ  UYõ  [`õ  bfð  Fgñ  shô  shð  NiÈfð  Nið  Nið  Nir    )r‰   T)r   ÚmmgprŒ   Úregister_stater3   r„   )r   r‰   rŒ   Útensorss       r   r‘   z)AutoRegressiveCudaGraphKit.register_stateŽ   s’   € ð Œ;ÐØˆFØ$Ð$Ð$Ð$Ð$Ð$ØTÐT¨ÐTÑTÔTˆØ×"Ò" 4¤;°´
¸Gð  Nið  NiÐcjð  Niñ  Niô  NiÐ"ñ  	jô  	jð  	jØ!%ˆÔÐÐr    r   Úattention_modulesúIterable[object]Ú
max_tokensr`   Ú
graph_modec                ó  — |dk    rt          d¦  «        ‚|dvrt          d|› d�¦  «        ‚d}|D ]Ô}t          |dd ¦  «        }|€t          d¦  «        ‚|                     |¦  «         t	          |t          |j        ¦  «        ¦  «        }t          |¦  «        }|| j        vra|dk    rt          ¦   «         |_
        nt          ¦   «         |_
        | j                             |¦  «         | j                             |¦  «         ŒÕ|S )	Nr   zmax_tokens must be > 0.)r   r)   zUnsupported graph_mode 'z'.Úkv_cachez:KV cache must be initialized before CUDA graph attachment.r)   )rF   ÚgetattrÚRuntimeErrorÚensure_capacityÚmaxr`   ÚcapacityÚidr‡   r'   Úgraph_stater   Úaddr…   Úappend)r   r“   r•   r–   Úfinal_capacityÚmoduler˜   Úcache_ids           r   Úattach_attention_modulesz3AutoRegressiveCudaGraphKit.attach_attention_modules™   s   € Ø˜Š?ˆ?ÝÐ6Ñ7Ô7Ð7ØÐ7Ð7Ð7ÝÐF¸
ÐFÐFÐFÑGÔGÐGØˆØ'ð 	7ð 	7ˆFÝ˜v z°4Ñ8Ô8ˆHØÐÝ"Ð#_Ñ`Ô`Ð`Ø×$Ò$ ZÑ0Ô0Ð0Ý  µ°XÔ5FÑ1GÔ1GÑHÔHˆNÝ˜(‘|”|ˆHØ˜tÔ7Ð7Ð7Ø Ò0Ð0Ý+<Ñ+>Ô+>�HÔ(Ð(å+=Ñ+?Ô+?�HÔ(ØÔ(×,Ò,¨XÑ6Ô6Ð6ØÔ%×,Ò,¨XÑ6Ô6Ð6øØÐr    Úrunner_namer/   r0   r9   r
   c                ó2  — | j         ��Fddlm}m} |                     d¬¦  «        5  |                     | j         ¦  «        r�| j                             |¦  «        }|€*t          | j	        d| j
        › d|› �¦  «        x}| j        |<   ||_         |j        | j	        g|¢R |j        |                     | j	        ¦  «        dœŽcd d d ¦  «         S 	 d d d ¦  «         n# 1 swxY w Y   |                     | j         ¦  «        rN| j                             ¦   «         D ]}|                     ¦   «          Œ| j                             ¦   «           ||Ž S | j                             |¦  «        }|€$t)          | j
        › d|› �|¦  «        }|| j        |<    |j        |Ž S )	Nr   )rŒ   ÚruntimeF)ÚgatedÚ_mm_kit_Ú_)ÚmethodÚenabledú:)r   r�   rŒ   r¨   ÚscopeÚ
is_enabledrƒ   Úgetrv   r€   r3   r/   r[   rw   Úweights_residentÚrequires_layer_offloadr‚   rp   rO   Úclearr,   )r   r¦   r/   r9   rŒ   r¨   ÚstageÚrunners           r   r[   zAutoRegressiveCudaGraphKit.run¯   sZ  € ØŒ;Ñ"Ø1Ð1Ð1Ð1Ð1Ð1Ð1Ð1Ø×"Ò"¨Ð"Ñ/Ô/ð Nð NØ×)Ò)¨$¬+Ñ6Ô6ð NØ œL×,Ò,¨[Ñ9Ô9�EØ�}Ý<BÀ4Ä>ÐSxÐ^bÔ^hÐSxÐSxÐkvÐSxÐSxÑ<yÔ<yÐy˜ ¤¨[Ñ 9Ø!�E”HØ*˜;œ?¨4¬>ð  N¸Fð  Nð  NÈ5Ì?Ðdk×d|Òd|ð  ~Bô  ~Lñ  eMô  eMð  Nð  Nð  NðNð Nð Nð Nñ Nô Nð Nð NðNðNð Nð Nñ Nô Nð Nð Nð Nð Nð Nð Nøøøð Nð Nð Nð Nð ×-Ò-¨d¬kÑ:Ô:ð #à"œm×2Ò2Ñ4Ô4ð %ð %�FØ—N’NÑ$Ô$Ð$Ð$Ø”×#Ò#Ñ%Ô%Ð%Ø�r˜6�{Ð"Ø”×"Ò" ;Ñ/Ô/ˆØˆ>Ý$¨¬
Ð%BÐ%B°[Ð%BÐ%BÀBÑGÔGˆFØ)/ˆDŒM˜+Ñ&ØˆvŒz˜6Ð"Ð"s   §BCÃC Ã#C c                óZ  — | j                              ¦   «         D ]}|                     ¦   «          Œ| j                              ¦   «          | j                             ¦   «         D ]'}| j        j                             |j        d ¦  «         Œ(| j                             ¦   «          | j	        r-ddl
m} |                     | j        | j        ¦  «         d| _	        | j        D ]}t!          |d¦  «        rd |_        Œ| j                             ¦   «          | j                             ¦   «          d S )Nr   r‹   FrŸ   )r‚   rp   rO   r´   rƒ   r€   rd   Úpoprw   r„   r�   rŒ   Úrelease_stater   r3   r…   rq   rŸ   r‡   )r   r¶   rµ   rŒ   r˜   s        r   rO   z"AutoRegressiveCudaGraphKit.releaseÅ   s3  € Ø”m×*Ò*Ñ,Ô,ð 	ð 	ˆFØ�NŠNÑÔÐÐØŒ×ÒÑÔÐØ”\×(Ò(Ñ*Ô*ð 	?ð 	?ˆEØŒNÔ#×'Ò'¨¬¸Ñ>Ô>Ð>Ð>ØŒ×ÒÑÔÐØÔ!ð 	+Ø(Ð(Ð(Ð(Ð(Ð(Ø×%Ò% d¤k°4´:Ñ>Ô>Ð>Ø%*ˆDÔ"ØÔ-ð 	,ð 	,ˆHÝ�x Ñ/Ô/ð ,Ø'+�Ô$øØÔ×#Ò#Ñ%Ô%Ð%ØÔ ×&Ò&Ñ(Ô(Ð(Ð(Ð(r    )NN)r-   r.   r   r   )r‰   r:   r   r   )r   )r“   r”   r•   r`   r–   r.   r   r`   )r¦   r.   r/   r0   r9   r
   r   r:   r^   )	r!   r"   r#   r$   r8   r‘   r¥   r[   rO   r%   r    r   r}   r}   x   sŒ   € € € € € ðð ð
3ð 
3ð 
3ð 
3ð 
3ð	&ð 	&ð 	&ð 	&ðð ð ð ð ð,#ð #ð #ð #ð,)ð )ð )ð )ð )ð )r    r}   )r   )r_   r`   r   ra   )Ú
__future__r   Údataclassesr   Útypingr   r   r   r   r'   r,   rg   rv   r}   r%   r    r   ú<module>r½      s]  ðà "Ð "Ð "Ð "Ð "Ð "à !Ð !Ð !Ð !Ð !Ð !Ø %Ð %Ð %Ð %Ð %Ð %Ð %Ð %à €€€ð ð
?ð 
?ð 
?ð 
?ð 
?ñ 
?ô 
?ñ „ð
?ð ðð ð ð ð ñ ô ñ „ðð7ð 7ð 7ð 7ð 7ñ 7ô 7ð 7ðtSð Sð Sð Sð Sð")ð )ð )ð )ð )ñ )ô )ð )ð\)ð \)ð \)ð \)ð \)ñ \)ô \)ð \)ð \)ð \)r    