
    iFD                        S r SSKrSSKrSSKJrJrJrJrJr  SSK	J
r
  SSKJr  \" S5      r " S S\\   5      r " S	 S
5      r " S S\5      r " S S\5      r " S S5      rS\4S jrS\4S jrS\S\\   S\4S jrg)zProvide TOSA specification parsing and context utilities.

Use these helpers to parse and validate TOSA profile/extension strings and to
manage a lowering-time context for the active specification.

    N)DictGenericListSetTypeVarVersion)ShapeEnvTc                   j    \ rS rSrS rSSS\SS4S jr\SSS\S   4S	 j5       r	SSS\\   4S
 jr
Srg)TosaSpecMapping   c                     0 U l         g N_mappingselfs    i/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/executorch/backends/arm/tosa/specification.py__init__TosaSpecMapping.__init__   s	    :<    specTosaSpecificationvaluereturnNc                 t   UR                   (       d  UR                  (       a  [        SU 35      e[        U[        5      (       a'  [        UR                  5      S:  a  [        SU 35      eUR                  5       nX0R                  ;  a  / U R                  U'   U R                  U   R                  U5        g)a;  Adds a value to the mapping for the given TOSA specification.

The specification is normalized to its canonical form, which means that
only the version and profiles are considered, without extensions. This
allows for grouping of values under the same TOSA specification
regardless of the extensions they may have.

z2TosaSpecMapping does not support extensions, got:    z9TosaSpecMapping does not support multiple profiles, got: N)
is_U55_subset
extensions
ValueError
isinstance	Tosa_1_00lenprofiles_canonical_keyr   append)r   r   r   	norm_specs       r   addTosaSpecMapping.add   s     DTFK  dI&&3t}}+=+AKD6R  '')	MM)')DMM)$i ''.r   c                     [        U [        5      (       a[  [        U R                  5      nUSS1:X  a>  U R                  n[
        R                  SU S35      [
        R                  SU S35      /$ U /$ )NFPINTTOSA-z+FPz+INT)r"   r#   setr%   versionr   create_from_string)r   r%   r0   s      r   _get_base_specsTosaSpecMapping._get_base_specs3   su     dI&&!$T]]!3HD%=(,,%885	9MN%885	9NO  vr   c                     U R                  U5      n/ nU H>  nUR                  5       nUR                  U R                  R	                  U/ 5      5        M@     [        U5      S:X  a  [        SU 35      eU$ )zReturns a list of values associated with the given TOSA
specification.

The specification is normalized to its canonical form, which means that
only the version and profiles are considered, without extensions.

r   z(No values found for TOSA specification: )r2   r&   extendr   getr$   KeyError)r   r   
base_specsresultbase	norm_bases         r   r6   TosaSpecMapping.get@   st     ))$/
D++-IMM$--++Ir:;  v;!EdVLMMr   r   )__name__
__module____qualname____firstlineno__r   r   r)   staticmethodr   r2   r6   __static_attributes__ r   r   r   r      sc    =/+ /A /$ /2 
1 
d;N6O 
 
+ Q r   r   c                   \   \ rS rSr% Sr\\S'   \\S'   \\	   \S'   \" S5      \" S5      /r
SS	/rS
\4S jrS
\4S jrS\	S
\4S jrS\S\\	   4S jr\S\\	-  S
\4S j5       r\S
\S    4S j5       r\S\	S
\S    4S j5       r\S\\	-  S
\S    4S j5       r\S\	S
S 4S j5       rSS jrSrg)r   T   a  Represent a TOSA specification.

A specification includes a semantic version, one or more profiles, and
optional extensions and levels (for example ``8k``).
The encoded form follows ``TOSA-<major>.<minor>.<patch>+<PROFILE>[+<LEVEL>][+<EXT>...]``.
Profiles use uppercase (for example ``INT``, ``FP``); levels and extensions
use lowercase.

Attributes:
    version (Version): Parsed TOSA semantic version.
    is_U55_subset (bool): True if the ``u55`` subset is requested.

r0   r   r    z1.0z1.1r-   r,   r   c                     [         e)z0Return True if integer operations are supported.NotImplementedErrorr   s    r   support_integer!TosaSpecification.support_integeri       !!r   c                     [         e)z7Return True if floating-point operations are supported.rG   r   s    r   support_floatTosaSpecification.support_floatm   rK   r   	extensionc                     [         e)Return True if an extension is supported and enabled.

Args:
    extension (str): Extension name (for example ``int4``, ``bf16``).

Returns:
    bool: True if the extension is valid for the active profiles and selected.

rG   )r   rO   s     r   support_extension#TosaSpecification.support_extensionq   s
     "!r   extrasc                 x    Xl         / U l        SU;   U l        U R                  (       a  UR                  S5        gg)zInitialize the base specification.

Args:
    version (Version): Parsed TOSA semantic version.
    extras (List[str]): Remaining tokens such as profiles, levels, and extensions.

u55N)r0   r    r   remove)r   r0   rT   s      r   r   TosaSpecification.__init__}   s6     "f_MM%  r   c                     [        U[        5      (       a  UnO:[        U5      nUR                  S5      (       a  U[	        S5      S  n[        U5      n[        UR
                   SUR                   35      $ )Nr.   .)r"   r	   str
startswithr$   majorminor)clsr0   parsedversion_strs       r   _normalize_version$TosaSpecification._normalize_version   sf    gw''Fg,K%%g..)#g,.9[)F&,,q788r   c           
          / nU R                    H<  nU R                   H)  nUR                  U R                  SU SU 35      5        M+     M>     U$ )z5Return specs for all supported versions and profiles.r.   +)_SUPPORTED_VERSIONS_SUPPORTED_PROFILESr'   r1   )r_   specsr0   profiles       r   all_versions_and_profiles+TosaSpecification.all_versions_and_profiles   sT     ,...G22S33eG9AgY4OPQ 3 / r   ri   c           	          UR                  5       nX R                  ;  a  [        SU 35      eU R                   Vs/ s H  nU R	                  SU SU 35      PM     sn$ s  snf )z;Return specs for all supported versions of a given profile.zUnsupported TOSA profile: r.   re   )upperrg   r!   rf   r1   )r_   ri   
normalizedr0   s       r   all_versions_for_profile*TosaSpecification.all_versions_for_profile   ss     ]]_
4449'CDD 22
2 ""U7)1ZL#AB2
 	
 
s   !A c           	      R   U R                  U5      nU R                   Vs1 s H  o3R                  UR                  4iM     nnUR                  UR                  4U;  a  [	        SU 35      eU R
                   Vs/ s H  nU R                  SU SU 35      PM     sn$ s  snf s  snf )z<Return specs for all supported profiles for a given version.zUnsupported TOSA version: r.   re   )rb   rf   r]   r^   r!   rg   r1   )r_   r0   rn   v	supportedri   s         r   all_profiles_for_version*TosaSpecification.all_profiles_for_version   s    
 ++G4
141H1HI1HAggqww'1H	Ij../y@9'CDD 22
2 ""U:,ay#AB2
 	
 J
s   !B;!B$reprc                    Sn[         R                  " X5      nU(       a  UR                  S5      n[        UR                  S5      5      nUR                  S5      R	                  S5      nUS:w  a  [        SU  35      eUR                  UR                  4= a   S:H  a  u  S:X  a  S:X  a    [        XE5      $    a   S:H  a  u  S:X  a  S:X  a  [        XE5      $    [        S	U S
U  35      e[        SU  35      e)a/  Create a specification from a standard string format.

Example: ``TOSA-1.00.0+INT+FP+int4+cf``.

Args:
    repr (str): Standard representation string.

Returns:
    TosaSpecification: Parsed specification instance.

Raises:
    ValueError: If the representation is malformed or version is unsupported.

z^(TOSA)-([\d.]+)\+(.+)$r         re   TOSAz-Malformed TOSA specification representation: r   zWrong TOSA version: z from z3Failed to parse TOSA specification representation: )
rematchgroupr	   splitr!   r]   r^   r#   Tosa_1_1)rv   patternr|   namer0   rT   s         r   r1   $TosaSpecification.create_from_string   s      -';;q>Dekk!n-G[[^))#.Fv~ #PQUPV!WXX--.VaV$W55 Va#G44 $';G9F4&%QRRNtfUVVr   c                     [         e)zYReturns a new TosaSpecification instance with only version and
profiles (no extensions).
rG   r   s    r   r&    TosaSpecification._canonical_key   s
     "!r   )r    r   r0   N)r   r   )r=   r>   r?   r@   __doc__r	   __annotations__boolr   r[   rf   rg   rI   rM   rR   r   classmethodrb   rj   ro   rt   rA   r1   r&   rB   rC   r   r   r   r   T   sH    S	"5>75>: $-" ""t "
"3 
"4 
"! !c ! 	93 	97 	9 	9 $/B*C   
s 
t<O7P 
 
 
m
	!	"
 
 W W)< W WB"r   r   c                      ^  \ rS rSr% Sr\\   \S'   \\S'   \\   \S'   SS/r	/ SQ/ S	QS
.r
S\S\\   4U 4S jjrS\4S jrS\4S jrS rS\4S jrS\S\4S jrS rS rS\S\4S jrSS jrSrU =r$ )r#      a  Provide TOSA 1.00 profile and extension semantics.

This variant validates profiles (``INT``, ``FP``), the optional ``8k`` level,
and allowed extensions based on the selected profiles.

Attributes:
    profiles (List[str]): Selected profiles, e.g., ``["INT"]`` or ``["INT", "FP"]``.
    level_8k (bool): True if the ``8k`` level is enabled.
    extensions (List[str]): Enabled extensions valid for the chosen profiles.

r%   level_8kr    r-   r,   )int16int4varcfrV   )bf16fp8e4m3fp8e5m2fftr   r   r-   r,   r0   rT   c                 |  >^ [         TU ]  X5        U R                  nU Vs/ s H  oDUR                  ;   PM     snR	                  S5      S:X  a  [        SUR                   SU S35      eU Vs/ s H  oDUR                  ;   PM     snR	                  S5      [        UR                  5      :  a  [        SUR                   SU S35      eU Vs/ s H  oDUR                  ;   d  M  UPM     snU l        U R                   H  nUR                  U5        M     SU;   U l	        U R                  (       a  UR                  S5        / mU R                   H  nTUR                  U   -  mM     [        U4S jU 5       5      (       d!  [        S	U U R                  5        S
U 35      eX l        gs  snf s  snf s  snf )a  Initialize the 1.00 specification and validate extras.

Args:
    version (Version): Semantic version (major=1, minor=0).
    extras (List[str]): Tokens including profiles, level, and extensions.

Raises:
    ValueError: If no/too many profiles are provided or extensions are invalid.

Tr   zNo profile (z) found in: rZ   zToo many profiles (8kc              3   ,   >#    U  H	  oT;   v   M     g 7fr   rC   ).0ecombined_extensionss     r   	<genexpr>%Tosa_1_00.__init__.<locals>.<genexpr>$  s     <V++Vs   zBad extensions for TOSA-z: N)superr   	__class__available_profilescountr!   r$   r%   rW   r   valid_extensionsall_get_profiles_stringr    )r   r0   rT   r_   r   pr   r   s         @r   r   Tosa_1_00.__init__   s    	)nn 288A'''8>>tDIs556l6(!L 
 288A'''8>>tDs""H
 
 %c&<&<%=\&QRS 
 %+JFq33I3I.IFJAMM!  ==MM$ A3#7#7#::  <V<<<*7)D4M4M4O3PPRSYRZ[ 
 !A 9 9 Ks   F/0F4F9(F9r   c                 j    SR                  U R                   Vs/ s H  nSU-   PM
     sn5      $ s  snf )z<Return the ``+``-joined profile segment (e.g., ``+INT+FP``). re   )joinr%   )r   r   s     r   r   Tosa_1_00._get_profiles_string,  s+    ww7Aa7887   0c                 j    SR                  U R                   Vs/ s H  nSU-   PM
     sn5      $ s  snf )z@Return the ``+``-joined extensions segment (e.g., ``+int4+cf``).r   re   )r   r    )r   r   s     r   _get_extensions_string Tosa_1_00._get_extensions_string0  s+    ww9Aa9::9r   c                     U R                  5       nU R                  (       a  US-  nU R                  (       a  US-  nSU R                   U R	                  5        U 3$ )zuReturn the standard specification string format.

Returns:
    str: Standard form like ``TOSA-1.00.0+INT+8k+int4``.

z+8kz+u55r.   )r   r   r   r0   r   )r   r    s     r   __repr__Tosa_1_00.__repr__4  sY     002
==%J& Jt||nT%>%>%@$A*NNr   c                 `    [        [        U R                  5      U R                  5       -   5      $ )zvReturn a stable hash for use in sets and dict keys.

Returns:
    int: Hash value derived from version and profiles.

)hashr[   r0   r   r   s    r   __hash__Tosa_1_00.__hash__B  s&     C%(A(A(CCDDr   otherc                     [        U[        5      (       aA  U R                  UR                  :H  =(       a!    U R                  5       UR                  5       :H  $ g)zReturn True if another instance represents the same spec.

Args:
    other (object): Object to compare.

Returns:
    bool: True if versions and profiles match.

F)r"   r#   r0   r   )r   r   s     r   __eq__Tosa_1_00.__eq__K  sJ     eY''LLEMM1 ))+u/I/I/KK r   c                      SU R                   ;   $ )z.Return True if the ``INT`` profile is present.r-   r%   r   s    r   rI   Tosa_1_00.support_integer[  s    %%r   c                      SU R                   ;   $ )z-Return True if the ``FP`` profile is present.r,   r   r   s    r   rM   Tosa_1_00.support_float_  s    t}}$$r   rO   c                     U R                   nU R                   H(  nXR                  U   ;   d  M  XR                  ;   d  M(    g   g)rQ   TF)r   r%   r   r    )r   rO   r_   r   s       r   rR   Tosa_1_00.support_extensionc  s=     nnA0033	__8T  r   c                     SSK Jn  U" U R                  R                   SU R                  R                   S35      n[        X R                  R                  5       5      $ )zReturns a new Tosa_1_00 instance with only major.minor version and
profiles (no extensions).

Patch version is set to zero for normalization.

r   r   rZ   z.0)packaging.versionr	   r0   r]   r^   r#   r%   copy)r   r	   norm_versions      r   r&   Tosa_1_00._canonical_keys  sL     	.$,,"4"4!5Qt||7I7I6J"MN}}'9'9';<<r   )r    r   r%   )r   r#   )r=   r>   r?   r@   r   r   r[   r   r   r   r   r	   r   r   r   r   intr   objectr   rI   rM   rR   r&   rB   __classcell__)r   s   @r   r#   r#      s    
 3iNS	4@
0! 0!c 0!d9c 9; ;OE# EF t  &%3 4  
= 
=r   r#   c                   &    \ rS rSr/ SQ/ SQS.rSrg)r   i  )shapeint64r   r   r   r   rV   )r   r   r   r   r   r   r   r   randommxfpblockscale_ue5m3r   rC   N)r=   r>   r?   r@   r   rB   rC   r   r   r   r     s     G
" 	r   r   c                       \ rS rSr% Sr\R                  " S5      r\R                  \S'   \R                  " S5      r	\R                  \S'   SS\
S\S-  4S	 jjrS
 rS rSrg)TosaLoweringContexti  ap  Manage the TOSA specification context for lowering.

For now, only the active ``TosaSpecification`` is tracked, but this can be
extended to carry additional lowering policies or configuration.

Attributes:
    tosa_spec_var (contextvars.ContextVar): Context variable storing the active spec.
    spec (TosaSpecification): Specification passed to the context manager.

	tosa_spectosa_spec_var	shape_envshape_env_varNr   c                     Xl         X l        g)zInitialize the lowering context with a specification.

Args:
    spec (TosaSpecification): Active specification to put into context.

N)r   r   )r   r   r   s      r   r   TosaLoweringContext.__init__  s     	"r   c                     [         R                  R                  U R                  5      U l        [         R
                  R                  U R                  5      U l        U $ )zmSet the context variable and return self.

Returns:
    TosaLoweringContext: This context manager instance.

)r   r   r/   r   tosa_spec_tokenr   r   shape_env_tokenr   s    r   	__enter__TosaLoweringContext.__enter__  sC      3@@DDTYYO2@@DDT^^Tr   c                     [         R                  R                  U R                  5        [         R                  R                  U R
                  5        g)zReset the context variable to its previous state.

Args:
    exc_type (type | None): Exception type, if any.
    exc_value (BaseException | None): Exception instance, if any.
    traceback (TracebackType | None): Traceback, if any.

N)r   r   resetr   r   r   )r   exc_type	exc_value	tracebacks       r   __exit__TosaLoweringContext.__exit__  s8     	))//0D0DE))//0D0DEr   )r   r   r   r   r   )r=   r>   r?   r@   r   contextvars
ContextVarr   r   r   r   r
   r   r   r   rB   rC   r   r   r   r     sb    	 -8,B,B;,OM;))O,7,B,B;,OM;))O#. #8d? #Fr   r   r   c                  r     [         R                  R                  5       $ ! [         a    [	        S5      ef = f)zGet the current ``TosaSpecification`` from the lowering context.

Returns:
    TosaSpecification: Active specification retrieved from the context var.

Raises:
    RuntimeError: If called outside a ``TosaLoweringContext``.

6Function must be executed within a TosaLoweringContext)r   r   r6   LookupErrorRuntimeErrorrC   r   r   get_context_specr     s:    U"004466 USTTUs     6c                       [         R                  R                  5       n U c  [        S5      e[         R                  R                  5       $ ! [         a    [        S5      ef = f)zGet the current ShapeEnv from the lowering context, if any.

Returns:
    ShapeEnv: Active ShapeEnv retrieved from the context var.

Raises:
    RuntimeError: If called outside a ``TosaLoweringContext`` or if no ShapeEnv is set.

z2No ShapeEnv set in the current TosaLoweringContextr   )r   r   r6   r   r   )r   s    r   get_context_shape_envr     s`    U'5599;	STT"004466 USTTUs   A	A A"r   rh   c                 N    [         R                  U 5      nU H
  nX1;   d  M
    g   g)a  Check if a specification matches any in a set, considering base specs.

Args:
    spec (TosaSpecification): Specification to check.
    specs (Set[TosaSpecification]): Set of specifications to match against.

Returns:
    bool: True if a match is found, False otherwise.

TF)r   r2   )r   rh   r8   r:   s       r   tosa_spec_in_setr     s+     !006J=  r   )r   r   r{   typingr   r   r   r   r   r   r	   %torch.fx.experimental.symbolic_shapesr
   r   r   r   r#   r   r   r   r   r   r   rC   r   r   <module>r      s   
  	 4 4 % :CL;gaj ;|L" L"^Z=! Z=z	y 	,2F 2FjU+ U Ux U(, S9J5K PT r   