§
     ’ÞjS0  ã                   ó‚  — d Z ddlZddlZddlmc mZ ddlmZm	Z	 	 ddl
Z
ddlmZ ddlmZmZ n# e$ r dZ
Y nw xY wdZdZej        j        ej        ej        j        ej        ej        j        ej        iZej        d„ ¦   «         Zd	efd
„Zd„ Zd	e fd„Z!d„ Z"d	efd„Z#d„ Z$d„ Z%d„ Z&d"d„Zd#d„Z'd„ Z(d„ Z)e
�ˆe
j*        d„ ¦   «         Z+e
j*        d„ ¦   «         Z, e
j*        g d¢¬¦  «        dej-        dej-        fd„¦   «         Z. e
j*        g d¢¬¦  «        dej-        dej-        fd „¦   «         Z/dd!l0m1Z1  e1¦   «          dS dS )$a¼  BF16 convolutions on FP16 tensor cores, for GPUs with FP16 but no BF16 tensor cores (validated on Turing, compute capability 7.5),
where PyTorch has no fast BF16 convolution (cuDNN has no BF16 kernels there: `slow_conv_dilated3d`, i.e. vol2col and a CUDA-core GEMM).

A BF16 value converts exactly to FP16 (8 significant bits into 11) while its magnitude stays in FP16's normal range. The weight is scaled
by a power of two (largest |w| in [0.5, 1)); the input by the power of two that keeps every input below 2^15 and every possible output
below 2^15 (largest |x| times the largest L1 norm of an output channel's weights), so nothing overflows; cuDNN accumulates in FP32; the
FP16 result is scaled back, the bias added in FP32 and rounded once to BF16, in place. Precision: values that end up below FP16's normal
range lose bits, and the result rounds to FP16 (11 bits) before BF16 (8 bits): LTX-2.5's VAE decoder, encoder and spatial upsampler
measured within +-3% of the PyTorch BF16 route's error against FP32, 4.8-6.8x faster. Used with every kernel precision (user decision,
2026-10-21: a few % more error than PyTorch's route is worth it where PyTorch has no fast BF16 convolution), an exception to the strict rule.

install_globally(device), called once by wgp.py: on an eligible GPU the stock _conv_forward of Conv1d / Conv2d / Conv3d (which
subclasses with causal paddings and caches call through super()) computes every BF16 CUDA call of the process this way; other dtypes,
devices, autograd, compilation and graph capture keep PyTorch's route. install(module, device) does the same for the layers of one
module (tests, standalone use); conv2d() is the functional entry for a layer computing a convolution itself.é    Né   )ÚchooseÚcuda_inference)Úbf16_bits_to_fp32Úfp32_to_bf16_bitsi   éx   c                 óH   — t           j                             | ¦  «        dk    S )N©é   é   )ÚtorchÚcudaÚget_device_capability)Úindexs    úBC:\Users\johnn\OneDrive\Documents\AI\shared\kernels\scaled_fp16.pyÚ
_supportedr   $   s   € åŒ:×+Ò+¨EÑ2Ô2°fÒ<Ð<ó    Úreturnc                 óÜ   — t          j        | ¦  «        } t          duoO| j        dk    oDt           j        j        du o1t           j                             ¦   «         ot          | j	        ¦  «        S )z|Validated on compute capability 7.5 only (Volta has the same FP16 tensor cores, untested); needs Triton for the conversions.Nr   )
r   ÚdeviceÚtritonÚtypeÚversionÚhipr   Úis_availabler   r   )r   s    r   Ú	supportedr   )   s‚   € åŒ\˜&Ñ!Ô!€FÝ˜Ðð  Q &¤+°Ò"7ð  Q½E¼MÔ<MÐQUÐ<Uð  QÕZ_ÔZd×ZqÒZqÑZsÔZsð  Qõ  yCð  DJô  DPñ  yQô  yQð  Qr   c                 ó¢   — t                                ¦   «         D ]4\  }}t          | |¦  «        rt          | ¦  «        j        |j        u r|c S Œ5dS )z|F.convNd of a Conv1d/2d/3d layer or of a subclass that keeps the stock _conv_forward (causal paddings and caches around it).N)Ú_CONVOLUTIONSÚitemsÚ
isinstancer   Ú_conv_forward)ÚlayerÚclsÚfns      r   Ú_functionalr%   /   sX   € å ×&Ò&Ñ(Ô(ð ð ‰ˆˆRÝ�e˜SÑ!Ô!ð 	¥d¨5¡k¤kÔ&?À3ÔCTÐ&TÐ&TØˆIˆIˆIøØˆ4r   c                 óÞ   — t          |¦  «        sdS d}|                      ¦   «         D ]D}t          |¦  «        �3d|j        vr*t	          j        t          ||j        ¦  «        |_        |dz  }ŒE|S )z¬Route the BF16 calls of module's Conv1d/2d/3d layers (and subclasses with the stock _conv_forward) on an eligible GPU
    (supported(device)); returns the number of layers.r   Nr!   r   )r   Úmodulesr%   Ú__dict__Ú	functoolsÚpartialr!   )Úmoduler   Úcountr"   s       r   Úinstallr-   7   sz   € õ �VÑÔð ØˆqØ€EØ—’Ñ!Ô!ð ð ˆÝ�uÑÔÐ)¨oÀUÄ^Ð.SÐ.SÝ"+Ô"3µMÀ5È%ÔJ]Ñ"^Ô"^ˆEÔØ�Q‰JˆEøØ€Lr   c                 óˆ  — | j         rt          | j        j        ¦  «        sdS | j        t
          j        k    rq|j        t
          j        k    r\| j         rUt          j        d¦  «        rAt          j	        d¦  «        t
          j        k    r|  
                    t
          j        ¦  «        } t          | d¬¦  «        r†|j        t
          j        k    sqt          |¦  «        t
          j        t
          j        j        fvsE|j        | j        k    s5|�|j        t
          j        k    st
          j                             ¦   «         rdS | S )a  The input to route (a BF16 autocast's FP32 input cast first, as autocast would), or None: BF16 CUDA input, weight and bias,
    inference, no compilation or capture, on a GPU of the route (also for the functional entries, which are not installed per device).Nr   r
   )Úcapability_floor)Úis_cudar   r   r   Údtyper   Úfloat32Úbfloat16Úis_autocast_enabledÚget_autocast_dtypeÚtor   r   ÚTensorÚnnÚ	Parameterr   Úis_current_stream_capturing)ÚinputÚweightÚbiass      r   Ú	_eligibler>   D   s	  € ð Œ=ð ¥
¨5¬<Ô+=Ñ >Ô >ð ØˆtØŒ•u”}Ò$Ð$¨¬½¼Ò)GÐ)GÈEÌMÐ)GÕ^cÔ^wÐx~Ñ^Ô^Ð)GÝÔ(¨Ñ0Ô0µE´NÒBÐBØ—’�œÑ(Ô(ˆÝ˜5°6Ð:Ñ:Ô:ð ¸f¼lÍeÌnÒ>\Ð>\Ý�F‰|Œ|¥E¤Lµ%´(Ô2DÐ#EÐEÐEÈÌÐZ_ÔZfÒIfÐIfØÐ  T¤Zµ5´>Ò%AÐ%AÅeÄj×FlÒFlÑFnÔFnÐ%AØˆtØ€Lr   c                 ó~   — t          | ¦  «        sdS t          D ]#}d|j        vr|j        |_        t
          |_        Œ$dS )zöRoute the BF16 calls of every Conv1d / Conv2d / Conv3d of the process (their stock _conv_forward, which subclasses call through
    super()) on an eligible GPU (supported(device)); once per process, from wgp.py. False (nothing patched) elsewhere.FÚ_scaled_fp16_stockT)r   r   r(   r!   r@   Ú_global_conv_forward)r   r#   s     r   Úinstall_globallyrB   S   sN   € õ �VÑÔð ØˆuÝð 5ð 5ˆØ s¤|Ð3Ð3Ø%(Ô%6ˆCÔ"Ý 4ˆCÔøØˆ4r   c                 ó$  ‡ — t          |||¦  «        }|€dS t          dd¬¦  «         t          ˆ fd„t                               ¦   «         D ¦   «         ¦  «        }t          ||||‰ j        ‰ j        ‰ j        ‰ j	        ‰ j
        ‰ j        ‰ d¦  «        S )zAlayer's convolution on the route for an eligible call, else None.NúBF16 ConvolutionT©Úowned_tritonc              3   óB   •K  — | ]\  }}t          ‰|¦  «        ¯|V — Œd S ©N)r    )Ú.0r#   r$   r"   s      €r   ú	<genexpr>z_route.<locals>.<genexpr>e   s6   øè è € ÐPÐP‘W�S˜"½ÀEÈ3Ñ9OÔ9OÐPˆbÐPÐPÐPÐPÐPÐPr   Ú_scaled_fp16_stats)r>   r   Únextr   r   Ú_scaledÚstrideÚpaddingÚdilationÚgroupsÚpadding_modeÚ _reversed_padding_repeated_twice)r"   r;   r<   r=   Úroutedr$   s   `     r   Ú_routerU   _   s    ø€ å�u˜f dÑ+Ô+€FØ€~ØˆtÝ
Ð¨DÐ1Ñ1Ô1Ð1Ý	ÐPÐPÐPÐP¥× 3Ò 3Ñ 5Ô 5ÐPÑPÔPÑ	PÔ	P€BÝ�2�v˜v t¨U¬\¸5¼=È%Ì.ÐZ_ÔZfÐhmÔhzØÔ9¸5ÐBVñXô Xð Xr   c                 óx   — t          | |||¦  «        }|€%t          | ¦  «                             | |||¦  «        n|S rH   )rU   r   r@   )r"   r;   r<   r=   Úouts        r   rA   rA   j   s?   € Ý
�˜˜v tÑ
,Ô
,€CØILÈ�4�‰;Œ;×)Ò)¨%°¸ÀÑEÔEÐEÐZ]Ð]r   c                 óH   — t          | |||¦  «        }|€ ||||¦  «        n|S rH   )rU   )r"   Úoriginalr;   r<   r=   rW   s         r   r!   r!   o   s2   € Ý
�˜˜v tÑ
,Ô
,€CØ,/¨Kˆ8ˆ8�E˜6 4Ñ(Ô(Ð(¸SÐ@r   c                óÆ   — t          | ||¦  «        }	|	€t          j        | ||||||¦  «        S t          dd¬¦  «         t	          t          j        |	||||||dd||¦  «        S )z÷F.conv2d, on the scaled-FP16 route where _conv_forward would take it (a layer computing a 2-D convolution itself, for example
    with a slice of a 3-D weight); owner.__dict__[key] caches the bound of that weight (one measurement, as for a layer).NrD   TrE   Úzeros)r>   ÚFÚconv2dr   rM   )
r;   r<   r=   rN   rO   rP   rQ   ÚownerÚkeyrT   s
             r   r]   r]   t   st   € õ �u˜f dÑ+Ô+€FØ€~ÝŒx˜˜v t¨V°W¸hÈÑOÔOÐOÝ
Ð¨DÐ1Ñ1Ô1Ð1Ý•1”8˜V V¨T°6¸7ÀHÈfÐV]Ð_cÐejÐloÑpÔpÐpr   rK   c           
      ót  — | j                              |¦  «        }|�€|                     ¦   «         }t          j        |                     ¦   «                              ¦   «         ¦  «        \  }}|                     ¦   «                              d¦  «                             d¦  «                             ¦   «         }t          t           t          t          t          |                     ¦   «         ¦  «         ¦  «        ¦  «        }|t          |                     ¦   «         ¦  «        d|z  z  dz  f}|| j         |<   |S )zÄ(power of two applied to the weight, largest L1 norm of an output channel's scaled weights): measured once per layer (or per
    owner and key), at its first call on the GPU (one synchronization).Nr   g       @g     ð?)r(   ÚgetÚabsr   ÚfrexpÚamaxÚfloatÚflattenÚsumÚmaxÚ_SHIFT_LIMITÚminÚintÚitem)	r^   r<   r_   ÚstatsÚ	magnitudeÚ_ÚexponentÚl1Úshifts	            r   Ú_weight_shiftrs   ~   sò   € ð ŒN×Ò˜sÑ#Ô#€EØ�}Ø—J’J‘L”Lˆ	Ý”k )§.¢.Ñ"2Ô"2×"8Ò"8Ñ":Ô":Ñ;Ô;‰ˆˆ8Ø�_Š_ÑÔ×&Ò& qÑ)Ô)×-Ò-¨aÑ0Ô0×5Ò5Ñ7Ô7ˆÝ•\�M¥3¥|µc¸(¿-º-¹/¼/Ñ6JÔ6JÐ5JÑ#KÔ#KÑLÔLˆØ�˜bŸgšg™iœiÑ(Ô(¨3°%©<Ñ7¸>ÑJÐKˆØ#ˆŒ�sÑØ€Lr   c                 óŒ   — t          t          | ¦  «        |||| j        | j        | j        | j        | j        | j        | d¦  «        S )zƒlayer's convolution (its stride, padding, padding mode, dilation, groups) of BF16 CUDA input, weight and bias on FP16 tensor cores.rK   )rM   r%   rN   rO   rP   rQ   rR   rS   )r"   r;   r<   r=   s       r   Úconvolutionru   Œ   sP   € å•;˜uÑ%Ô% u¨f°d¸E¼LÈ%Ì-ÐY^ÔYgÐinÔiuÐw|ô  xJØÔ9¸5ÐBVñXô Xð Xr   c                 óÀ  — t          |
||¦  «        \  }}|                     ¦   «         }t          j        |¦  «        \  }}t          j        |j        t          j        |j        ¬¦  «        }t          j        dt          j        |j        ¬¦  «        }t          t          j        |                     ¦   «         t          ¦  «        f         |                     t          j        ¦  «        ||                     ¦   «         d|                     t          j        ¦  «        |                     t          j        ¦  «        ||dt          ¦
  «
         d}|                     ¦   «         }t          j        |j        t          j        |j        ¬¦  «        }t          t          j        |                     ¦   «         t          ¦  «        f         |                     t          j        ¦  «        ||                     ¦   «         |dddddt          ¦
  «
         |dk    rt!          j        ||	|¬	¦  «        d}}t          j        d
d¬¦  «        5   | ||d||||¦  «                             ¦   «         }ddd¦  «         n# 1 swxY w Y   dx}}|j        d         |d                              ¦   «         }}t'          t          j        |                     ¦   «         t          ¦  «        f         ||                     t          j        ¦  «        |€dn|                     t          j        ¦  «        |||                     ¦   «         |||dut          ¦
  «
         |                     t          j        ¦  «        S )z}fn (F.conv1d/2d/3d) of BF16 CUDA input, weight and bias on FP16 tensor cores; owner.__dict__[key] caches the bound of weight.)r1   r   r   r   TNg        Fr[   )Úmoder   )Údevice_typeÚenabled)r   r   )rs   Ú
contiguousr   ÚaminmaxÚemptyÚshapeÚfloat16r   Úint32Ú_to_fp16_kernelr   ÚcdivÚnumelÚ_BLOCKÚviewÚint16r\   ÚpadÚautocastÚ_to_bf16_kernelr3   )r$   r;   r<   r=   rN   rO   rP   rQ   rR   Úreversed_paddingr^   r_   Úweight_shiftrq   ÚxÚlowÚhighÚx16rr   Úw16ÚyÚchannelsÚspatials                          r   rM   rM   ’   s8  € å$ U¨F°CÑ8Ô8Ñ€L�"Ø×ÒÑÔ€AÝ”˜aÑ Ô �I€CˆÝ
Œ+�a”g¥U¤]¸1¼8Ð
DÑ
DÔ
D€CÝŒK˜¥¤°Q´XÐ>Ñ>Ô>€EÝ•V”[ §¢¡¤­FÑ3Ô3Ð5Ô6°q·v²v½e¼kÑ7JÔ7JÈCÐQR×QXÒQXÑQZÔQZÐ\]Ð_b×_gÒ_gÕhmÔhsÑ_tÔ_tÐvz×vÒvõ  AFô  ALñ  wMô  wMð  OQØ8=¸tÅVñMô Mð Mà€AØ×ÒÑ Ô €FÝ
Œ+�f”l­%¬-ÀÄÐ
NÑ
NÔ
N€CÝ•V”[ §¢¡¤µÑ8Ô8Ð:Ô;¸F¿KºKÍÌÑ<TÔ<TÐVYÐ[a×[gÒ[gÑ[iÔ[iÐkwÐy}ð  @Dð  FIØ=AÀ5Í&ñRô Rð Rà�wÒÐÝ”u˜SÐ"2¸ÐFÑFÔFÈˆWˆÝ	Œ F°EÐ	:Ñ	:Ô	:ð Oð OØˆBˆs�C˜˜v w°¸&ÑAÔA×LÒLÑNÔNˆðOð Oð Oñ Oô Oð Oð Oð Oð Oð Oð Oøøøð Oð Oð Oð OàÐ€Cˆ#Øœ œ
 A d¤G§M¢M¡O¤Oˆg€HÝ•V”[ §¢¡¤­FÑ3Ô3Ð5Ô6°q¸!¿&º&ÅÄÑ:MÔ:MÐW[ÐWcÈtÈtÐim×irÒirÕsxÔs~ÑiÔið  BGØ8DÀaÇgÂgÁiÄiÐQYÐ[bÐdhÐptÐdtÕv|ñ~ô ~ð ~à�6Š6•%”.Ñ!Ô!Ð!s   È;$I+É+I/É2I/c                 óP   — | dz   dz                        t          j        d¬¦  «        S )Né   é   T©Úbitcast)r6   Útlr2   )rr   s    r   Ú_power_of_twor™   ¬   s&   € à˜‘ Ñ#×'Ò'­¬
¸DÐ'ÑAÔAÐAr   c                 ó�   — |                       t          j        d¬¦  «        dz	  dz                        t          j        ¦  «        dz
  S )NTr–   r•   éÿ   r”   )r6   r˜   Úuint32r   )r‹   s    r   Ú	_exponentr�   °   s9   € à—’•b”i¨�Ñ.Ô.°"Ñ4¸Ñ<×@Ò@ÅÄÑJÔJÈSÑPÐPr   )ÚnÚfixed_shiftrq   )Údo_not_specializeÚDYNAMICÚBLOCKc
           
      óè  — t          j        d¦  «                             t           j        ¦  «        |	z  t          j        d|	¦  «        z   }
|
|k     }|�r0t          j        t          j        t          t          j        |¦  «        ¦  «        ¦  «        t          j        t          t          j        |¦  «        ¦  «        ¦  «        ¦  «        }||z  }dt          j        t          |¦  «        t          |¦  «        ¦  «        z
  }t          j
        |dk    |t          d¦  «        k     z  t          j        t          j        |d¦  «        d¦  «        d¦  «        }t          j        ||t          j        d¦  «        dk    ¬¦  «         n|}t          t          j        | |
z   |d¦  «        ¦  «        t          |¦  «        z  }t          j        ||
z   |                     t           j        ¦  «        |¦  «         d S )Nr   é   Úinfiˆÿÿÿr   )Úmask)r˜   Ú
program_idr6   Úint64ÚarangeÚmaximumrb   r   Úloadr�   Úwherere   ÚminimumÚstorer™   r~   )ÚXÚYrž   rŸ   ÚLOWÚHIGHrq   ÚSHIFTr¡   r¢   Úoffsetsr¦   ÚlargestÚboundrr   r‹   s                   r   r€   r€   ´   s�  € õ ”- Ñ"Ô"×%Ò%¥b¤hÑ/Ô/°%Ñ7½"¼)ÀAÀuÑ:MÔ:MÑMˆØ˜Š{ˆØñ 	 Ý”j¥¤Õ(9½"¼'À#¹,¼,Ñ(GÔ(GÑ!HÔ!HÍ"Ì&ÕQbÕceÔcjÐkoÑcpÔcpÑQqÔQqÑJrÔJrÑsÔsˆGØ˜b‘LˆEà�œ¥I¨eÑ$4Ô$4µiÀÑ6HÔ6HÑIÔIÑIˆEÝ”H˜g¨šk¨eµe¸E±l´lÒ.BÑCÅRÄZÕPRÔPZÐ[`ÐbfÑPgÔPgÐilÑEmÔEmÐopÑqÔqˆEÝŒH�U˜E­¬°aÑ(8Ô(8¸AÒ(=Ð>Ñ>Ô>Ð>Ð>àˆEÝ�bœg a¨'¡k°4¸Ñ;Ô;Ñ<Ô<½}ÈUÑ?SÔ?SÑSˆÝ
Œ��W‘˜aŸdšd¥2¤:Ñ.Ô.°Ñ5Ô5Ð5Ð5Ð5r   )rŠ   rž   r‘   r’   ÚHAS_BIASc
                 ó@  — t          j        d¦  «                             t           j        ¦  «        |	z  t          j        d|	¦  «        z   }
|
|k     }t          j        |¦  «        |z    }|dz  }t          j        | |
z   |d¦  «                             t           j        ¦  «        t          |¦  «        z  t          ||z
  ¦  «        z  }|r/|t          t          j        ||
|z  |z  z   |d¦  «        ¦  «        z  }t          j	        ||
z   t          |¦  «        |¦  «         d S )Nr   é   )r˜   r§   r6   r¨   r©   r«   r2   r™   r   r®   r   )ÚY16ÚY_BITSÚBIASr³   rŠ   rž   r‘   r’   r·   r¢   r´   r¦   ÚtotalÚhalfr�   s                  r   rˆ   rˆ   Å   s  € õ ”- Ñ"Ô"×%Ò%¥b¤hÑ/Ô/°%Ñ7½"¼)ÀAÀuÑ:MÔ:MÑMˆØ˜Š{ˆÝ”'˜%‘.”. <Ñ/Ð0ˆØ˜‰zˆÝŒG�C˜'‘M 4¨Ñ+Ô+×.Ò.­r¬zÑ:Ô:½]È4Ñ=PÔ=PÑPÕS`ÐafÐimÑamÑSnÔSnÑnˆØð 	]ØÕ"¥2¤7¨4°7¸gÑ3EÈÑ2QÑ+QÐSWÐYZÑ#[Ô#[Ñ\Ô\Ñ\ˆAÝ
Œ�˜'Ñ!Õ#4°QÑ#7Ô#7¸Ñ>Ô>Ð>Ð>Ð>r   )Ú!install_triton_compilation_logger)Nr   r   r   r   )rK   )2Ú__doc__r)   r   Útorch.nn.functionalr8   Ú
functionalr\   Údispatchr   r   r   Útriton.languageÚlanguager˜   Ú	bf16_bitsr   r   ÚImportErrorrƒ   ri   ÚConv1dÚconv1dÚConv2dr]   ÚConv3dÚconv3dr   Úcacher   Úboolr   r%   rk   r-   r>   rB   rU   rA   r!   rs   ru   rM   Újitr™   r�   Ú	constexprr€   rˆ   Ú%shared.kernels.triton_compilation_logr¿   © r   r   ú<module>rÓ      s  ððpð pð Ð Ð Ð à €€€Ø Ð Ð Ð Ð Ð Ð Ð Ð à ,Ð ,Ð ,Ð ,Ð ,Ð ,Ð ,Ð ,ðØ€M€M€MØ Ð Ð Ð Ð Ð Ø?Ð?Ð?Ð?Ð?Ð?Ð?Ð?Ð?øØð ð ð Ø€F€F€Fðøøøð 
€Ø€Ø”” !¤(¨E¬H¬O¸Q¼XÀuÄxÄÐXYÔX`Ða€ð „ð=ð =ñ „ð=ðQ˜ð Qð Qð Qð Qðð ð ð
˜sð 
ð 
ð 
ð 
ðð ð ð	 ð 	ð 	ð 	ð 	ðXð Xð Xð^ð ^ð ^ð
Að Að Að
qð qð qð qðð ð ð ðXð Xð Xð"ð "ð "ð2 
ÐØ„ZðBð Bñ „ZðBð „ZðQð Qñ „ZðQð €V„ZÐ"<Ð"<Ð"<Ð=Ñ=Ô=ð6ÈRÌ\ð 6ÐbdÔbnð 6ð 6ð 6ñ >Ô=ð6ð  €V„ZÐ"NÐ"NÐ"NÐOÑOÔOð	?Ð`bÔ`lð 	?Ðuwô  vBð 	?ð 	?ð 	?ñ PÔOð	?ð XÐWÐWÐWÐWÐWØ%Ð%Ñ'Ô'Ð'Ð'Ð'ðQ Ðs   �0 °:¹: