
    il'              	       l   S r SSKrSSKJr  SSKJrJr  SSKrSSKr	SSK
Jr  Sr\R                  \R                  \R                  \R                   \R"                  \R$                  \R&                  \R(                  \R*                  4	r " S S\5      rS	\R0                  S
\4S jrS r " S S5      rg)zProvide PyTorch-to-TOSA mapping helpers.

Use these utilities to translate PyTorch dtypes and FX node metadata into the
TOSA serializer types and shapes used during initial compilation.

    N)Enum)AnySequence)TosaSpecificationtosa_tensor_namec                       \ rS rSrSr\R                  R                  r\R                  R                  r\R                  R                  r	S\R                  4S jr
\S\4S j5       rS rS rSrg	)
TosaSpecialDtype#   z6Special TOSA dtypes not natively expressed in PyTorch.returnc                     U R                   $ )zxReturn the underlying ``ts.DType`` enumerant.

Returns:
    ts.DType: Serializer dtype associated with the enum entry.

)valueselfs    c/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/executorch/backends/arm/tosa/mapping.pyget_tosa_dtypeTosaSpecialDtype.get_tosa_dtype*   s     zz    c                      g)zReturn the FX ``meta`` key that stores special dtypes.

Returns:
    str: Metadata key used to encode :class:`TosaSpecialDtype`.

tosa_special_dtype r   r   r   meta_keyTosaSpecialDtype.meta_key3   s     $r   c                 h    U =U R                   :X  a    gU R                  :X  a  g [        SU  S35      e)N   l    Unrecognized TosaSpecialDtype .INT4INT48
ValueErrorr   s    r   maxTosaSpecialDtype.max=   s3      #A$q!IJJr   c                 h    U =U R                   :X  a    gU R                  :X  a  g [        SU  S35      e)Nil       r   r   r   r   s    r   minTosaSpecialDtype.minF   s3     #A$q!IJJr   r   N)__name__
__module____qualname____firstlineno____doc__tsDTyper   r   SHAPEr   staticmethodstrr   r!   r$   __static_attributes__r   r   r   r	   r	   #   sc    @HHNNE88==DHHNNE  $c $ $KKr   r	   	data_typer   c                    U [         ;   a  [        SU  35      e[        R                  [        R
                  R                  [        R                  [        R
                  R                  [        R                  [        R
                  R                  [        R                  [        R
                  R                  [        R                  [        R
                  R                  [        R                  [        R
                  R                  [        R                  [        R
                  R                   [        R"                  [        R
                  R                   [        R$                  [        R
                  R&                  [        R(                  [        R
                  R&                  [        R*                  [        R
                  R,                  0nX;  a  [        SU  35      eX   $ )zMap a ``torch.dtype`` to a ``ts.DType``.

Args:
    data_type (torch.dtype): PyTorch dtype to convert.

Returns:
    ts.DType: Matching serializer dtype.

Raises:
    ValueError: If the dtype is unsupported or unknown.

zUnsupported type: zUnknown type: )UNSUPPORTED_DTYPESr    torchfloat32r+   r,   FP32floatfloat16FP16halfbfloat16BF16int8INT8int16INT16shortint32INT32intboolBOOL)r1   	dtype_maps     r   	map_dtyperH   P   s    &&-i[9:: 	rxx}}RXX]]rxx}}

BHHMM

BHHMMRXX^^RXX^^RXX^^		288>>

BHHMMI !>)566r   c                    U R                  [        R                  5       5      nU[        R                  :X  a/  [	        U S   5      n[
        R                  R                  U4U S   4$ U R                  S5      c  [        S5      eU S   n[        U5      [        L a  US   n[        U[        R                  R                  R                  5      (       d  [        SUR                   35      e[!        UR"                  5      n[        UR%                  5       5      nU R                  S5      b  U S   nO[        ['        [	        U5      5      5      nXEU4$ )aW  Extract dtype, shape, and dimension order from FX metadata.

Args:
    meta (dict): FX node ``meta`` containing a ``val`` FakeTensor (or tuple).

Returns:
    tuple[ts.DType, tuple[int, ...], tuple[int, ...]]: Tuple containing
    tensor dtype, shape, and dimension order.

Raises:
    ValueError: If ``meta['val']`` is not a ``FakeTensor``.

valtosa_dim_orderz3Expected node.meta['val'] to be set to a FakeTensorr   z?Expected first value in node.meta['val'] to be FakeTensor, got )getr	   r   r-   lenr+   r,   r    typetuple
isinstancer4   _subclassesfake_tensor
FakeTensor	__class__rH   dtypesizerange)metaspecial_dtype	shape_lenrJ   rU   shape	dim_orders          r   extract_tensor_metar]   u   s!    HH-6689M(...U$	d3C.DEExxNOO
u+CCyE!fc5,,88CCDDMcmm_]
 	
 cii E#((*Exx !-)*	%E
+,	)$$r   c                       \ rS rSrSrS\R                  R                  4S jrS r	S\
\-  4S jrS\S\4S	 jrS\S\SS
4S jrS rSrg
)TosaArg   a  Capture and normalize TOSA operator arguments.

Use this to convert FX nodes, sequences, and numeric literals into a
consistent structure suitable for TOSA serialization.

Attributes:
    name (str): Node name when argument is a ``torch.fx.Node``; empty
        otherwise.
    dtype (ts.DType | None): Inferred dtype when available.
    shape (tuple[int, ...] | None): Inferred shape when available.
    dim_order (tuple[int, ...] | None): Dimension order, defaulting to
        ``range(len(shape))``.
    special (list | None): Captured list when the argument is a sequence.
    number (float | int | None): Captured numeric value when provided.
    multiple_output_name (list[str]): Output node names when node has multiple outputs; empty otherwise.

argumentc                 f   UR                   R                  [        S5      nUR                  U-   U l        SUR                   ;   am  [	        UR                   5      u  o0l        U l        UR                   R                  [        R                  5       S5      =n(       a  UR                  5       nX0l
        [        UR                  5      n[        U5      S:  aP  [        S U 5       5      (       a9  U Vs/ s H  ofR                  U-   PM     snU l        U R                  S   U l        g/ U l        gs  snf )ztParse a ``torch.fx.Node`` and populate tensor attributes.

Args:
    argument (torch.fx.Node): FX node to inspect.

 rJ   Nr   c              3   Z   #    U  H!  oR                   [        R                  :H  v   M#     g 7f)N)targetoperatorgetitem).0users     r   	<genexpr>)TosaArg.__process_node.<locals>.<genexpr>   s     !Ted++1A1A"Aes   )+)rX   rL   TOSA_TENSOR_NAME_METAnamer]   r[   r\   r	   r   r   rU   listusersrM   allmultiple_output_names)r   ra   suffixoutput_dtypespecial_typero   ri   s          r   __process_nodeTosaArg.__process_node   s     ""#8"=MMF*	HMM!7J84L*dn  (}}001A1J1J1LdSS|S+::<%J
 X^^$u:>c!Te!TTTOT/Uut		F0Bu/UD&2215DI)+D& 0Vs   1D.c                 $    [        U5      U l        g)zeCapture a sequence argument as ``special``.

Args:
    argument (Sequence[Any]): Sequence to store.

N)rn   specialr   ra   s     r   __process_listTosaArg.__process_list   s     "(^r   c                     Xl         g)z]Capture a numeric argument as ``number``.

Args:
    argument (float | int): Numeric value.

N)numberry   s     r   __process_numberTosaArg.__process_number   s	     $,r   	tosa_specr   c                 f   [        U SS 5      =[        R                  R                  :X  a    UR	                  5       (       d  g g=[        R                  R
                  :X  a    UR                  S5      (       d  g g[        R                  R                  :X  a  UR                  S5      (       d  g gg)NrU   Fint4bf16T)getattrr+   r,   r6   support_floatr   support_extensionr<   )r   r   s     r   
__validateTosaArg.__validate   s    dGT* ..00  1   226::  ; 	  226::  ; r   Nc                 <   [        U[        R                  R                  5      (       aF  U R	                  U5        U R                  U5      (       d  [        U SU R                  5        35      eg[        U[        5      (       a  U R                  U5        g[        U[        [        45      (       a  U R                  U5        g[        U[        R                  5      (       a  gUc  SU l        SU l        SU l        SU l        g[#        SU S[%        U5       35      e)af  Initialize the argument wrapper and populate fields.

Args:
    argument (Any): One of ``torch.fx.Node``, ``Sequence``, ``int``,
        ``float``, ``torch.dtype``, or ``None``.
    tosa_spec (Optional[TosaSpecification]): Active specification;
        required for metadata extraction.

Raises:
    RuntimeError: If ``argument`` is of an unsupported type.

z doesn't support tensor Nrc   zUnhandled node input argument: z
, of type )rP   r4   fxNode_TosaArg__process_node_TosaArg__validater    __repr__r   _TosaArg__process_listrD   r7   _TosaArg__process_numberrU   rm   r[   r\   RuntimeErrorrN   )r   ra   r   s      r   __init__TosaArg.__init__   s     h..)??9--  k!9$--/9JK  h)))he--!!(+h,,DIDJDJ!DN-hZz$x.AQR
 	
r   c                    / n[        U S5      (       a  U R                  b  UR                  SU R                  < 35        U R                  b/  UR                  S[        R
                  U R                      35        U R                  b  UR                  SU R                  < 35        U R                  b  UR                  SU R                  < 35        [        U S5      (       a,  U R                  b  UR                  SU R                  < 35        [        U S5      (       a,  U R                  b  UR                  S	U R                  < 35        [        U S
5      (       a8  [        U R                  5      S:  a  UR                  SU R                  < 35        U R                  R                   SSR                  U5       S3$ )znReturn a compact representation of populated attributes.

Returns:
    str: Readable list of set attributes.

rm   zname=zdtype=zshape=z
dim_order=rx   zspecial=r}   znumber=rq   r   znames=(z, ))hasattrrm   appendrU   r+   
DTypeNamesr[   r\   rx   r}   rM   rq   rT   r&   join)r   attrss     r   r   TosaArg.__repr__  sc    4  yy$uTYYM23zz%vbmmDJJ&?%@ABzz%vdjj^45~~)z$..);<=4##(@LL8DLL#3454""t{{'>LL74;;/2340114--.2vd&@&@%CDE..))*!DIIe,<+=Q??r   )r\   rU   rq   rm   r}   r[   rx   )r&   r'   r(   r)   r*   r4   r   r   r   r   r7   rD   r   r   rE   r   r   r   r   r0   r   r   r   r_   r_      sf    $,uxx}} ,:,, ,$5 $ )
 )
1B )
t )
V@r   r_   )r*   rf   enumr   typingr   r   r4   tosa_serializerr+   *executorch.backends.arm.tosa.specificationr   rl   float64double	complex64cfloat
complex128cdoubleuint8int64longr3   r	   rU   rH   r]   r_   r   r   r   <module>r      s   
       H*  
MM	LL	OO	LL		MM	KK	KK	JJ
 *Kt *KZ     J%%PS@ S@r   