
    ^j:6                       d dl mZ d dlmZmZmZ d dlmZ d dlm	c m
c mc mZ d dlmZmZ d dlmZmZ erd dlmZ d dlmZ g d	Z ed
       G d dej.                               Ze G d dej2                               Ze	 d	 	 	 	 	 	 	 dd       Ze	 d	 	 	 dd       Ze	 d	 	 	 dd       Zeddd       Ze	 d	 	 	 d d       Ze	 d	 	 	 d!d       Z e	 	 d"	 	 	 d#d       Z!e	 	 d"	 	 	 d$d       Z"y)%    )annotations)ListTupleTYPE_CHECKING)	dataclassN)PaddedSharedLayoutSwizzledSharedLayout)builtin_unwrap_if_constexpr)ir)shared_memory_descriptor)
async_load
async_waitmake_tensor_descriptortensor_descriptortensor_descriptor_typeprefetchasync_scatterT)eqc                  b    e Zd ZU dZded<   ded<   ded<   ded<   dd	Zdd
ZddZddZddZ	y)r   z!The type for a tensor descriptor.zttgl.block_type
block_typezttgl.tuple_type
shape_typestrides_type)PaddedSharedLayout | SwizzledSharedLayoutlayoutc                <    d| j                    d| j                   dS )Nztensor_descriptor<z, >)r   r   selfs    }/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/triton/experimental/gluon/language/amd/gfx1250/tdm.py__str__ztensor_descriptor_type.__str__   s     #DOO#4Bt{{m1EE    c                    ||   }|dz  }| j                   j                  ||      \  }}| j                  j                  ||      \  }}t        ||||       }||fS )N   )r   _unflatten_irr   r   )r   handlescursorhandleshapestridesvalues          r    r%   z$tensor_descriptor_type._unflatten_ir   sd    !55gvFv++99'6J!&%$?f}r"   c                    | j                   j                  j                         }|j                  | j                   j	                  |      || j
                  j                  |            S N)r   
element_tyis_int_signed!get_tensor_descriptor_layout_typeto_irr   _to_ir)r   builder	is_signeds      r    r2   ztensor_descriptor_type._to_ir'   sT    OO..<<>	88OO!!'*KKw'
 	
r"   c                    |j                  | j                  |             | j                  j                  ||       | j                  j                  ||       y r-   )appendr2   r   _flatten_ir_typesr   )r   r3   outs      r    r7   z(tensor_descriptor_type._flatten_ir_types/   sA    

4;;w'())'37++GS9r"   c           	         d| j                   j                          d| j                  j                          d| j                  j                          d| j                  j                          d	S )NTD_)r   mangler   r   r   r   s    r    r<   ztensor_descriptor_type.mangle4   sb    DOO**,-Qt/E/E/G.H$J[J[JbJbJdIeefgkgrgrgygyg{f||~r"   N)returnstr)r&   List[ir.value]r'   intr=   zTuple[tensor_descriptor, int])r3   
ir.builderr=   zir.type)r3   rA   r8   zList[ir.type]r=   None)
__name__
__module____qualname____doc____annotations__r!   r%   r2   r7   r<    r"   r    r   r      s8    +!!55F
:
@r"   r   c                      e Zd ZU dZded<   ded<   ded<   ded<   dd	Zed
        Zed        Zed        Z	ed        Z
y)r   z4A descriptor representing a tensor in global memory.zir.valuer(   z
ttgl.tupler)   r*   r   typec                    |j                  | j                         | j                  j                  |       | j                  j                  |       y r-   )r6   r(   r)   _flatten_irr*   )r   r&   s     r    rL   ztensor_descriptor._flatten_irA   s6    t{{#

w'  )r"   c                .    | j                   j                  S r-   )rJ   r   r   s    r    r   ztensor_descriptor.block_typeF   s    yy###r"   c                B    | j                   j                  j                  S r-   )rJ   r   r)   r   s    r    block_shapeztensor_descriptor.block_shapeJ   s    yy##)))r"   c                B    | j                   j                  j                  S r-   )rJ   r   r.   r   s    r    dtypeztensor_descriptor.dtypeN   s    yy##...r"   c                .    | j                   j                  S r-   )rJ   r   r   s    r    r   ztensor_descriptor.layoutR   s    yyr"   N)r&   r?   r=   rB   )rC   rD   rE   rF   rG   rL   propertyr   rO   rQ   r   rH   r"   r    r   r   8   sr    >
  *
 $ $ * * / /    r"   r   c                   t        |      }d|cxk  rdk  sn J d| d       t        |      |k(  sJ d| dt        |              t        |      |k(  sJ d| dt        |              t        | j                  t        j                        sJ d	       t        |      }t        |t        t        f      sJ d
       t        |t              r|j                  dk(  sJ d       | j                  }|j                  |d      }|j                  |d      }	t        j                  |      }t        j                  |      }t        j                  | j                  j                  |      }
t        |
|j                  |j                  |      }|j!                  d      }|j"                  j%                  |j'                  |j"                        |||	|      }t)        ||||      S )a  Make a tensor descriptor object.

    Args:
        base (tensor): base pointer of the tensor in global memory.
        shape (List[int]): shape of the tensor.
        strides (List[int]): strides of the tensor.
        block_shape (List[int]): block shape of the tensor.
        layout (PaddedSharedLayout | SwizzledSharedLayout): the layout of the tensor in shared memory.

    Returns:
        tensor_descriptor: the created tensor descriptor object
    r$      z Expected 1 <= ndim <= 5 but got z dimensionsz	Expected z strides but got zExpected block_shape to have z dimensions but got zExpected base to be a pointerzBExpected layout to be a PaddedSharedLayout or SwizzledSharedLayoutz3Expected max_phase to be 1 for SwizzledSharedLayoutFrequire_i64Tzero)len
isinstancerQ   ttglpointer_typer   r   r	   	max_phaser(   _convert_to_ir_valuestupler   rJ   r.   r   _str_to_padding_optionr3   create_make_tensor_descriptorr2   r   )baser)   r*   rO   r   	_semanticndimbase_handleshape_handlesstride_handlesr   rJ   paddingr(   s                 r    r   r   W   s     u:D>>O=dV;OO>w<4R9TF2CCL>!RR{t#m'DTFJ^_bcj_k^l%mm#djj$"3"34U6UU4!&)Ff13GHI MLMI&./1$[&[[$++K33Eu3MM44W$4ONJJuEjj!G!5!5{CJ!*ejj',,OD..v6G<<T[[IZIZ=[]hjw=KWVF VUGT::r"   c                8   |j                  |d      }|j                  |      }|j                  }t        |      }||j                  nt        j
                  j                         }|j                  j                  | j                  ||j                  ||       y)a)  Load a block of tensor specified in tensor descriptor from global memory to shared memory asynchronously.

    Args:
        src (tensor_descriptor): the source tensor descriptor.
        offsets (List[int]): the offsets from the base pointer in the tensor descriptor.
        dest (shared_memory_descriptor): the shared memory destination to store the loaded data.
        pred (int, optional): Predicate to enable or disable the load. Defaults to 1.
        mbarrier (shared_memory_descriptor, optional): The barrier object to signal "arrive" on.
    FrV   N)	r^   	to_tensorr(   r   r[   r   r+   r3   %create_async_tdm_copy_global_to_local)	srcoffsetsdestpredmbarrierrc   offset_handlespred_handlembarrier_handles	            r    r   r      s     44W%4PNt$D++K#H-H)1)=hoo477==?O;;CJJX\XcXcep<KMr"   c                    |j                  |d      }t        |      }||j                  nt        j                  j                         }|j                  j                  | j                  ||j                  |       y)a  Store a block of tensor specified in tensor descriptor from shared memory to global memory asynchronously.

    Args:
        dest (tensor_descriptor): the destination tensor descriptor.
        offsets (List[int]): the offsets from the base pointer in the tensor descriptor.
        src (shared_memory_descriptor): the shared memory source to load the data.
        mbarrier (shared_memory_descriptor, optional): The barrier object to signal "arrive" on.
    FrV   N)r^   r   r(   r[   r   r+   r3   %create_async_tdm_copy_local_to_global)rn   rm   rl   rp   rc   rq   rs   s          r    async_storerv      sc     44W%4PN#H-H)1)=hoo477==?O;;DKKY\YcYcetur"   c                P    t        |       } |j                  j                  |        y)zWait for the outstanding asynchronous tensor operations to complete.

    Args:
        num_outstanding (int): number of outstanding async tensor operations to wait for.
    N)r   r3   create_async_tdm_wait)num_outstandingrc   s     r    r   r      s"     +?;O++O<r"   c                   t        | j                        }|dk(  sJ d| d       t        |j                        }|dk(  sJ d| d       |j                  |gd      d   }t	        |      }||j
                  nt        j                  j                         }	|j                  j                  | j
                  |j
                  ||j
                  |	       y)	a  Scatter data from shared memory to non-contiguous rows in global memory asynchronously.

    This operation uses TDM scatter mode to write data to non-contiguous rows in global memory.
    Unlike async_store which writes to contiguous rows, scatter allows writing to arbitrary
    rows specified by the dst_row_indices tensor.

    The dtype of dst_row_indices determines the index size:
    - int16: up to 16 rows can be scattered per TDM instruction
    - int32: up to 8 rows can be scattered per TDM instruction
    If more rows are needed, multiple TDM instructions will be automatically issued.

    Args:
        desc (tensor_descriptor): the destination tensor descriptor. Must be 2D.
        dst_row_indices (tensor): 1D tensor of row indices (int16 or int32) in the destination tensor.
        dst_col_offset (int or tensor): the starting column offset in the destination tensor
                                        for all scattered rows.
        src (shared_memory_descriptor): the shared memory source containing data to scatter. Must be 2D.
        mbarrier (shared_memory_descriptor, optional): The barrier object to signal "arrive" on.
       z*TDM scatter only supports 2D tensors, got Dz TDM scatter src must be 2D, got FrV   r   N)rY   rO   r)   r^   r   r(   r[   r   r+   r3   create_async_tdm_scatter)
descdst_row_indicesdst_col_offsetrl   rp   rc   rd   src_ndimdst_col_offset_handlers   s
             r    r   r      s    , t D19JB4&JJ9399~Hq=H<XJaHH= &;;^<LZ_;`abc#H-H)1)=hoo477==?O..t{{O<R<RTiknkuku/>@r"   c                   t        | j                        }|dk(  sJ d| d       t        |j                        }|dk(  sJ d| d       |j                  |gd      d   }t	        |      }||j
                  nt        j                  j                         }	|j                  j                  | j
                  |j
                  ||j
                  |	       y)	au  Gather data from non-contiguous rows in global memory to shared memory asynchronously.

    This operation uses TDM gather mode to read data from non-contiguous rows in global memory.
    Unlike async_load which reads from contiguous rows, gather allows reading from arbitrary
    rows specified by the src_row_indices tensor.

    The dtype of src_row_indices determines the index size:
    - int16: up to 16 rows can be gathered per TDM instruction
    - int32: up to 8 rows can be gathered per TDM instruction
    If more rows are needed, multiple TDM instructions will be automatically issued.

    Args:
        desc (tensor_descriptor): the source tensor descriptor. Must be 2D.
        src_row_indices (tensor): 1D tensor of row indices (int16 or int32) in the source tensor.
        src_col_offset (int or tensor): the starting column offset in the source tensor
                                        for all gathered rows.
        dst (shared_memory_descriptor): the shared memory destination to store gathered data. Must be 2D.
        mbarrier (shared_memory_descriptor, optional): The barrier object to signal "arrive" on.
    r{   z)TDM gather only supports 2D tensors, got r|   zTDM gather dst must be 2D, got FrV   r   N)rY   rO   r)   r^   r   r(   r[   r   r+   r3   create_async_tdm_gather)
r~   src_row_indicessrc_col_offsetdstrp   rc   rd   dst_ndimsrc_col_offset_handlers   s
             r    async_gatherr      s    , t D19IA$qII9399~Hq=G;H:QGG= &;;^<LZ_;`abc#H-H)1)=hoo477==?O--dkk?;Q;QShjmjtjt.=?r"   c                    |j                  |d      }|j                  |      }|j                  }t        |      }|j                  j                  | j                  |||d       y)a  Prefetches a block of tensor specified in tensor descriptor from global memory into L2. Speculative prefetches can generate more
    efficient assembly because they do not require out of bounds checks. However, they are dropped by the hardware if their virtual address translation is not cached.
    So speculative should only be set if previous iterations have accessed the same virtual page (e.g. column major)
    Args:
        src (tensor_descriptor): the source tensor descriptor.
        offsets (List[int]): the offsets from the base pointer in the tensor descriptor.
        pred (bool, optional): Predicate to enable or disable the prefetch. Defaults to True.
        speculative (bool, optional): Whether the prefetch is speculative. Defaults to False.
    FrV   N)r^   rj   r(   r   r3   create_tdm_prefetch)rl   rm   ro   speculativerc   rq   rr   s          r    r   r      s^     44W%4PNt$D++K&{3K))#**nkS^`efr"   c                   |j                  |d      }|j                  |      }|j                  }t        |      }|j                  j                  | j                  |||d      }|j                  j                  |      }|j                  j                  |      }	t        j                  t        j                  ||	      }
t        j                  ||
      }|S )z?Test-only prefetch variant that returns offsets for validation.FrV   T)r^   rj   r(   r   r3   r   get_shape_from_tensorget_gluon_layout_from_tensorr[   distributed_typeint64tensor)rl   rm   ro   r   rc   rq   rr   r(   r)   r   ret_tyr   s               r    _test_prefetch_with_offsetsr     s     44W%4PNt$D++K&{3K223::~{\gimnF33F;E;;FCF""4::uf=F[[(FMr"   r-   )rb   ttgl.tensorr)   "List[ttgl.constexpr | ttgl.tensor]r*   r   rO   zList[ttgl.constexpr]r   r   r=   r   )r$   NN)
rl   r   rm   r   rn   r   rp   r   r=   rB   )NN)
rn   r   rm   r   rl   r   rp   r   r=   rB   )r   N)r=   rB   )
r~   r   r   r   rl   r   rp   r   r=   rB   )
r~   r   r   r   r   r   rp   r   r=   rB   )TFN)
rl   r   rm   r   ro   boolr   r   r=   rB   )
rl   r   rm   r   ro   r   r   r   r=   r   )#
__future__r   typingr   r   r   dataclassesr   (triton.experimental.gluon.language._coreexperimentalgluonlanguage_corer[   +triton.experimental.gluon.language._layoutsr   r	   r
   r   	triton._Cr   r   __all__	base_typer   
base_valuer   r   r   rv   r   r   r   r   r   rH   r"   r    <module>r      s   " - - ! 7 7 ` RQ d!@T^^ !@ !@H      < 	 Y](;$F(;Ui(;#L(;ar(; 	(;V 	LPM!9MUYM 	M( 	EIv2vNRv 	v  	= 	= 	GK"@4"@PT"@ 	"@J 	FJ"?3"?OS"? 	"?J 	_c26gg;?g 	g$ 	rvEI-1NY 	r"   