
    i )                        S r SSKrSSKJr  SSKrSSKrSSKrSSKr	SSK
Jr  SSKJr  SSKJr  \R                   " \5      rS\\   S\\\\   4   4S	 jrS
\\   S\\   4S jr SS jrS rS\\R6                  -  S\\R6                  -  S\S\4S jrS\\\R6                  -  \\R6                  -  4   S\\\R6                  -  \\R6                  -  4   S\S\S\\R:                  S4   4
S jrg)z<Utility helpers for building TOSA graphs in the Arm backend.    N)Any)extract_tensor_meta)
FakeTensor)Nodefake_tensorsreturnc                    [        U 5      S:  a  [        S[        U 5       35      eU  Vs/ s H!  n[        [        UR                  5      5      PM#     nn[        U[         SS9n/ n[        [        US   5      5       Hf  nSnU HJ  nU[        U5      :  a  M  US:X  a  Xu   S:w  a  Xu   nM(  Xu   S:X  a  M2  US:w  d  M:  Xu   U:w  d  MD  S/ 4s  s  $    UR                  U5        Mh     S[        [        U5      5      4$ s  snf )a  Determine whether the fake tensors share a broadcastable shape.

Args:
    fake_tensors (list[FakeTensor]): Fake tensors whose shapes should
        be validated for broadcasting.

Returns:
    tuple[bool, list[int]]: Tuple where the first element indicates
        whether broadcasting is possible and the second element contains
        the broadcast shape. The shape list is empty when broadcasting
        fails.

Raises:
    RuntimeError: Raised when fewer than two tensors are supplied.

   zExpected 2 or more tensors got T)keyreverser   F)lenRuntimeErrorlistreversedshapesortedrangeappend)r   ftreversed_shapessorted_shapesbroadcast_shapedimcurr_dimr   s           a/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/executorch/backends/arm/tosa/utils.pyare_fake_tensors_broadcastabler      s    & <1<S=N<OPQQ:FG,BtHRXX./,OG?TBMOSq)*+"Ec%j 1}q :qQ5:#9r{" # 	x( , $x0122! Hs   (C=nodesc                    U Vs/ s H  o"R                   S   PM     nn[        U5      u  pEU(       d  [        S5      e/ nU GH  n[        UR                   5      u  pxn	[	        U5      n
X:X  a  UR                  U5        M?  [        U5      [        U5      -
  nS/U-  U
-   nU R                  UU5      n[        XR                  XR                  5        U R                  XW5      n[        X\5       VVs/ s H  u  nnUS:X  a  UOSPM     nnnU R                  [        U5      4[        R                  R                  UUR                   S3S9n[        R                  " 5       nUR!                  5         U R#                  [        R$                  R&                  UR                  UR                  /UR                  /U5        UR                  U5        GM     U$ s  snf s  snnf )a  Broadcast the FX nodes to a shared shape inside the TOSA graph.

This mirrors ``reshape_for_broadcast`` but also emits the tile operators
needed to materialize the broadcast and supports any number of inputs.

Args:
    tosa_fb (Any): TOSA graph builder that receives the broadcast
        operators.
    nodes (list[Node]): FX nodes whose tensor metadata should be
        broadcast.
    tosa_spec (TosaSpecification): Active TOSA specification used to
        decode tensor metadata.

Returns:
    list[Any]: Broadcast versions of the inputs. Each element is either
        the original FX node or a TOSA serializer tensor, ordered to match
        ``nodes``.

Raises:
    RuntimeError: If the supplied nodes are not broadcastable.

valz!FakeTensors are not broadcastabler
   
_multiplesname)metar   r   r   r   r   r   addIntermediatebuild_reshape_tosar"   zipaddConsttsDTypeSHAPETosaSerializerAttributeTileAttributeaddOperatorOpTILE)tosa_fbr   nodeindex_fake_tensorsbroadcastablecommon_shapebroadcast_tensors
tens_dtype
tens_shape_list_tens_shape	rank_diff	new_shapereshapedtiledcommcurrmultipliersmultiple_shapesattrs                       r   r5   r5   B   s   . 8==ut))E*u="@AS"TM>??$7		$B!
z**$$T*%J7	C)Oo5	**

 	7IIy--H''A7:<7S
7StDAID1$7S 	 
 "**HHNNII;j)	 + 
 ))+EEJJ]]O001ZZL		
 	  'K N [ >0
s   G2Gc                    U R                  [        R                  " U5      R                  [        R
                  R                  [        R                  " U5      U(       a  UOUS-   S9n[        R                  " 5       nUR                  5         U R                  [        R                  R                  XR                  /U/U5        g)a  Insert a TOSA reshape operator using the v1.0 semantics.

Args:
    tosa_graph (Any): Graph builder used to emit TOSA operators.
    input_name (str): Name of the tensor that should be reshaped.
    new_shape (list[int]): Target tensor shape.
    output_name (str): Name assigned to the reshaped tensor.
    shape_name_override (str): Optional override for the shape constant
        name.

_shaper!   N)r'   nparrayr   r(   r)   r*   r+   ReshapeAttributer-   r.   RESHAPEr"   )
tosa_graph
input_namer;   output_nameshape_name_overrider   rB   s          r   r%   r%      s     
!!

$7 [8=S	   E %%'D
	ZZ 		    c           	          [        U Vs/ s H  o U   PM	     sn5      n[        U Vs/ s H&  n[        U[        R                  5      (       a  SOUPM(     sn5      n[	        U5      $ s  snf s  snf )a{  Reorder a shape tuple into TOSA layout while resolving symints.

Args:
    shape (Sequence[int | torch.SymInt]): Original tensor shape,
        possibly containing ``torch.SymInt``.
    dim_order (Sequence[int]): Desired dimension order for the output
        shape.

Returns:
    list[int]: List containing the reordered dimensions where symbolic
        values become ``-1``.

)tuple
isinstancetorchSymIntr   )r   	dim_orderr   	reordereddremoved_symintss         r   
tosa_shaperX      sj     Y7YcSzY78I ;DE9az!U\\**	19EO    8 	Fs
   A'-A,
input_sizeoutput_sizeresize_modealign_cornersc                 6   U(       a5  [        U [        5      (       a  [        U[        5      (       d  [        S5      e[        U [        R                  5      (       a  U R
                  R                  OU n [        U[        R                  5      (       a  UR
                  R                  OUnU(       a  U S:  a  US:  a  US-
  nOUnU(       a  U S:  a  US:  a  U S-
  nOU nXE-  n[        R                  " U5      R                  5       (       d  [        S[        U5      -   S-   5      e[        R                  " XE5      nSU-  U-  nSU-  U-  n[        UR                  5       5      n[        UR                  5       5      nU(       a  SnOUS-  US-  -
  nXQS-
  -  X@S-
  -  -
  U-   n	[        R                  " U	5      R                  5       (       d  [        S[        U	5      -   S-   5      e[        [        R                  " U	5      R                  5       5      n	XEX4$ )a  Compute resize coefficients for a single spatial dimension.

Args:
    input_size (int | torch.SymInt): Input size for the axis, possibly
        symbolic.
    output_size (int | torch.SymInt): Output size for the axis, possibly
        symbolic.
    resize_mode (int): Target resize mode defined by TOSA.
    align_corners (bool): Whether the resize should align the corner
        pixels.

Returns:
    tuple[int, int, int, int]: Numerator, denominator, offset, and border
        terms encoded as integers.

Raises:
    RuntimeError: If symbolic shapes are used with ``align_corners`` or if
        the computed ratio or border is not constant.

z9We do not support align_corners=True for symbolic shapes.r
   z"Resize requires a constant ratio: z is not constant!   r   z#Resize requires a constant border: )rQ   intr   rR   rS   r1   _exprsympysympifyis_constantstrgcdevalf)
rY   rZ   r[   r\   scale_nscale_dratiore   offsetborders
             r   get_resize_parameters_1drl      s   6 :s++ZS5Q5QK  ",J!E!E
:  #-[%,,"G"G[  aK!O/aK!Oq.E==++--03u:=@SS
 	
 ))G
%C'kS G'kS G'--/"G'--/"G A1, a(71n+EENF== ,,..1CK?BUU
 	
 v&,,./FV++rM   input_size_xyoutput_size_xy.c           	          [        U S   US   X#5      n[        U S   US   X#5      n[        [        [        R                  [        XE5      5      5      $ )ay  Calculate 2D resize parameters for TOSA emission.

Args:
    input_size_xy (tuple[int | torch.SymInt, int | torch.SymInt]): Height
        and width of the input tensor.
    output_size_xy (tuple[int | torch.SymInt, int | torch.SymInt]): Height
        and width of the output tensor.
    resize_mode (int): TOSA resize mode used for coefficient generation.
    align_corners (bool): Whether to align corner pixels between input and
        output.

Returns:
    tuple[torch.IntTensor, ...]: Four-element tuple of tensors describing
        the scale numerator, scale denominator, offset, and border for Y
        and X dimensions.

r   r
   )rl   rP   maprR   	IntTensorr&   )rm   rn   r[   r\   y_paramsx_paramss         r   get_resize_parametersrt     sY    0 (a.+[H (a.+[H U__c(&=>??rM   ) )__doc__loggingtypingr   numpyrE   ra   rR   tosa_serializerr(   $executorch.backends.arm.tosa.mappingr   torch._subclasses.fake_tensorr   torch.fxr   	getLogger__name__loggerr   rP   boolr_   r   r5   r%   rX   rS   rl   rq   rt    rM   r   <module>r      sN  
 C       D 4 			8	$&3z"&3
4c?&3RDd4j DT#Y DP IK>!.L,ell"L,u||#L, L, 	L,^@u||+S5<<-??@@#,cELL.@@A@ @ 	@
 5??C @rM   