
    ¯wg.X                     D   d dl mZmZmZmZmZmZmZmZm	Z	m
Z
 d dlZd dlZd dlmZmZ d dlmZ  ed      ZdZ G d de      Z	 d!dd	d
ej*                  j,                  deeeeedf         e	e
eeeedf         f   f   deeee   e	e
ee   f   f      deee      dej*                  j,                  f
dZ	 	 	 	 d"d
ej*                  j,                  deeeedf         deee      deee      ddf
dZ	 	 	 d#d
ej*                  j,                  de	e
eeeedf         f   deee      dee	e
ee   f      ddf
dZ	 d$dededededeeeej8                  f   eee   f   f
dZdej*                  j,                  deee   ee   f   fdZdedededefdZ dddZ!d  Z"y)%    )
AnyTypeVarOptionalTupleList
NamedTupleUnionSequenceDictCallableN)	TupleTypeListType)wrap_cpp_moduleT   c                   8    e Zd ZU dZeed<   dZeed<   dZeed<   y)InflatableArga  Helper type for bundled inputs.

    'value' is the compressed/deflated input that is stored in the model. Value
    must be of the same type as the argument to the function that it is a deflated
    input for.

    'fmt' is a formatable code string that is executed to inflate the compressed data into
    the appropriate input. It can use 'value' as an input to the format str. It must result
    in a value of the same type as 'value'.

    'fmt_fn' is a formatable function code string that is executed to inflate the compressed
    data into the appropriate input. It must result in a value of the same type as 'value'.
    The function name should be the formatable part of the string.

    Note: Only top level InflatableArgs can be inflated. i.e. you cannot place
    an inflatable arg inside of some other structure. You should instead create
    an inflatable arg such that the fmt code string returns the full structure
    of your input.
    value{}fmt fmt_fnN)	__name__
__module____qualname____doc__r   __annotations__r   strr        _/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/torch/utils/bundled_inputs.pyr   r      s!    ( JCOFCr    r   )_receive_inflate_exprmodelinputs.infor"   returnc                   t        | t        j                  j                        st	        d      t        |       \  }}t        j                  j                  | j                  ||      }t        |      }t        |t              r$t        |t              s|J t        ||||       |S t        |t              s|J t        ||||       |S )a  Create and return a copy of the specified model with inputs attached.

    The original model is not mutated or changed in any way.

    Models with bundled inputs can be invoked in a uniform manner by
    benchmarking and code coverage tools.

    If inputs is passed in as a list then the inputs will be bundled for 'forward'.
    If inputs is instead passed in as a map then all the methods specified in the map
    will have their corresponding inputs bundled. Info should match watchever type is
    chosen for the inputs.

    The returned model will support the following methods:

        `get_all_bundled_inputs_for_<function_name>() -> List[Tuple[Any, ...]]`
            Returns a list of tuples suitable for passing to the model like
            `for inp in model.get_all_bundled_inputs_for_foo(): model.foo(*inp)`

        `get_bundled_inputs_functions_and_info() -> Dict[str, Dict[str: List[str]]]`
            Returns a dictionary mapping function names to a metadata dictionary.
            This nested dictionary maps preset strings like:
                'get_inputs_function_name' -> the name of a function attribute in this model that can be
                    run to get back a list of inputs corresponding to that function.
                'info' -> the user provided extra information about the bundled inputs

    If forward has bundled inputs then these following functions will also be defined on the returned module:

        `get_all_bundled_inputs() -> List[Tuple[Any, ...]]`
            Returns a list of tuples suitable for passing to the model like
            `for inp in model.get_all_bundled_inputs(): model(*inp)`

        `get_num_bundled_inputs() -> int`
            Equivalent to `len(model.get_all_bundled_inputs())`,
            but slightly easier to call from C++.

    Inputs can be specified in one of two ways:

      - The model can define `_generate_bundled_inputs_for_<function_name>`.
        If the user chooses this method inputs[<function>] should map to None

      - The `inputs` argument to this function can be a dictionary mapping functions to a
        list of inputs, of the same form that will be returned by get_all_bundled_inputs_for_<function_name>.
        Alternatively if only bundling inputs for forward the map can be omitted and a singular list of inputs
        can be provided instead.

        The type of the inputs is List[Tuple[Any, ...]]. The outer list corresponds with a
        list of inputs, the inner tuple is the list of args that together make up one input.
        For inputs of functions that take one arg, this will be a tuple of length one. The Any, ...
        is the actual data that makes up the args, e.g. a tensor.

    Info is an optional parameter that maps functions to a list of strings providing extra information about that
    function's bundled inputs. Alternatively if only bundling inputs for forward the map can be omitted and
    a singular list of information can be provided instead. This could be descriptions, expected outputs, etc.
        - Ex: info={model.forward : ['man eating icecream', 'an airplane', 'a dog']}

    This function will attempt to optimize arguments so that (e.g.)
    arguments like `torch.zeros(1000)` will be represented compactly.
    Only top-level arguments will be optimized.
    Tensors in lists or tuples will not.
    Only ScriptModule is supported.)
isinstancetorchjitScriptModule	Exception*_get_bundled_inputs_attributes_and_methods_C(_hack_do_not_use_clone_module_with_class_cr   dict0augment_many_model_functions_with_bundled_inputslist!augment_model_with_bundled_inputs)r#   r$   r%   r"   ignored_methodsignored_attrsclonecloned_modules           r!   bundle_inputsr:   (   s    F eUYY3349::%OPU%V"O]HH==E $E*M&$$%558Pegkl  $%55)-AVX\]r    c                     t        | t        j                  j                        st	        d      | j
                  }t        |d      sd|_        t        | ||i||r||ind|       y)a  Add bundled sample inputs to a model for the forward function.

    Models with bundled inputs can be invoked in a uniform manner by
    benchmarking and code coverage tools.

    Augmented models will support the following methods:

        `get_all_bundled_inputs() -> List[Tuple[Any, ...]]`
            Returns a list of tuples suitable for passing to the model like
            `for inp in model.get_all_bundled_inputs(): model(*inp)`

        `get_num_bundled_inputs() -> int`
            Equivalent to `len(model.get_all_bundled_inputs())`,
            but slightly easier to call from C++.

        `get_bundled_inputs_functions_and_info() -> Dict[str, Dict[str: List[str]]]`
            Returns a dictionary mapping function names to a metadata dictionary.
            This nested dictionary maps preset strings like:
                'get_inputs_function_name' -> the name of a function attribute in this model that can be
                    run to get back a list of inputs corresponding to that function.
                'info' -> the user provided extra information about the bundled inputs

    Inputs can be specified in one of two ways:

      - The model can define `_generate_bundled_inputs_for_forward`.
        If the user chooses this method inputs should be None

      - `inputs` is a list of inputs of form List[Tuple[Any, ...]]. A list of tuples where the elements
        of each tuple are the args that make up one input.
    r(   r   forwardN)r$   r"   r%   skip_size_check)	r)   r*   r+   r,   r-   r<   hasattrr   r3   )r#   r$   r"   r%   r=   r<   s         r!   r5   r5      sg    J eUYY3349::G 7J'$4&!3!%g4'r    c                    t        | t        j                  j                        st	        d      |st	        d      t        | d      st        | d      rt	        d      d}|j                         D ]@  \  }}t        |d      r|j                  }n$t        |d      r|j                  }nt	        d	      |t        |t              st        d| d      |j                  j                  dd
 D 	cg c]  }	|	j                   }
}	t        t        |
            }| j                   j#                  d| |g        t        | d|z         r|t	        d| d| d      |t%        |      dk(  rt	        d| d| d      g }g }t'        |      D ]  \  }}t        |t(              s"t        |t*              st        d| d| d      g }|j-                  d       t'        |      D ]y  \  }}	t/        |||      }t1        |	d| d| d||      \  }}}|j-                  |       |j-                  d| d        |sV| j3                  t5        j6                  |             { |j-                  t9        |             |j-                  d!        |j-                  d       d"j;                  |      }||j-                  |       t=        | d| |       t5        j6                  d#      j?                  ||$      }| j3                  |       | j3                  t5        j6                  d%      j?                  |&             |r||v rtA        ||         nd'}|d(| d)| d*| d+z  }|d,k(  s| j3                  t5        j6                  d-             | j3                  t5        j6                  d.             C | j3                  t5        j6                  d/| d0             y
c c}	w )1a
  Add bundled sample inputs to a model for an arbitrary list of public functions.

    Models with bundled inputs can be invoked in a uniform manner by
    benchmarking and code coverage tools.

    Augmented models will support the following methods:

        `get_all_bundled_inputs_for_<function_name>() -> List[Tuple[Any, ...]]`
            Returns a list of tuples suitable for passing to the model like
            `for inp in model.get_all_bundled_inputs_for_foo(): model.foo(*inp)`

        `get_bundled_inputs_functions_and_info() -> Dict[str, Dict[str: List[str]]]`
            Returns a dictionary mapping function names to a metadata dictionary.
            This nested dictionary maps preset strings like:
                'get_inputs_function_name' -> the name of a function attribute in this model that can be
                    run to get back a list of inputs corresponding to that function.
                'info' -> the user provided extra information about the bundled inputs

    If forward has bundled inputs then these following functions are also defined:

        `get_all_bundled_inputs() -> List[Tuple[Any, ...]]`
            Returns a list of tuples suitable for passing to the model like
            `for inp in model.get_all_bundled_inputs(): model(*inp)`

        `get_num_bundled_inputs() -> int`
            Equivalent to `len(model.get_all_bundled_inputs())`,
            but slightly easier to call from C++.

    Inputs can be specified in one of two ways:

      - The model can define `_generate_bundled_inputs_for_<function_name>`.
        If the user chooses this method inputs[<function>] should map to None

      - The `inputs` argument to this function can be a dictionary mapping functions to a
        list of inputs, of the same form that will be returned by get_all_bundled_inputs_for_<function_name>.
        The type of the inputs is List[Tuple[Any, ...]]. The outer list corresponds with a
        list of inputs, the inner tuple is the list of args that together make up one input.
        For inputs of functions that take one arg, this will be a tuple of length one. The Any, ...
        is the actual data that makes up the args, e.g. a tensor.

    Info is an optional parameter that maps functions to a list of strings providing extra information about that
    function's bundled inputs. This could be descriptions, expected outputs, etc.
        - Ex: info={model.forward : ['man eating icecream', 'an airplane', 'a dog']}

    This function will attempt to optimize arguments so that (e.g.)
    arguments like `torch.zeros(1000)` will be represented compactly.
    Only top-level arguments will be optimized.
    Tensors in lists or tuples will not.
    r(   z-Please provide inputs for at least 1 functionget_all_bundled_inputs%get_bundled_inputs_functions_and_infozModels can only be augmented with bundled inputs once. This Model seems to have already been augmented with bundled inputs. Please start afresh with one that doesn't have bundled inputs.r   r   namezcAt least one of your functions has no attribute name please ensure all have one. m.foo.name = "foo"NzError inputs for function z is not a Sequence   _bundled_inputs_deflated__generate_bundled_inputs_for_zinputs[z0] is not None, but _generate_bundled_inputs_for_z is already definedr   zinputs for z3 must be specified if _generate_bundled_inputs_for_z is not already definedz!Error bundled input for function z idx: z is not a Tuple or a List(z	deflated[z][])r=   z    ,z),
z
                def _generate_bundled_inputs_for_{name}(self):
                    deflated = self._bundled_inputs_deflated_{name}
                    return [
                {expr}
                    ]
                )exprrB   z
            def get_all_bundled_inputs_for_{name}(self):
                all_inputs = self._generate_bundled_inputs_for_{name}()
                assert all_inputs is not None
                return all_inputs
            )rB   z[]zP
            temp_dict : Dict[str,List[str]] = {}
            info: List[str] = zx

            temp_dict['info'] = info
            temp_dict['get_inputs_function_name'] = ['get_all_bundled_inputs_for_z']
            all_inputs['z'] = temp_dict
            r<   z
                def get_all_bundled_inputs(self):
                    return self.get_all_bundled_inputs_for_forward()
                z
                def get_num_bundled_inputs(self):
                    return len(self.get_all_bundled_inputs_for_forward())
                z
        def get_bundled_inputs_functions_and_info(self):
            all_inputs : Dict[str, Dict[str,List[str]]] = {}
            z'
            return all_inputs
        )!r)   r*   r+   r,   r-   r>   itemsr   rB   r
   	TypeErrorschema	argumentstyper   r   r1   _register_attributelen	enumerater   r   append_get_inflate_helper_fn_name_inflate_exprdefinetextwrapdedenttuplejoinsetattrformatrepr)r#   r$   r"   r%   r=   .get_bundled_inputs_functions_and_info_templatefunction
input_listfunction_nameargfunction_arg_typesdeflated_inputs_typedeflated_inputspartsinp_idxargsdeflated_argsarg_idxinflate_helper_fn_namedeflatedinflaterhelper_definitionrJ   
definitioninputs_infos                            r!   r3   r3      sG   p eUYY3349::GHHu./75Bi3j+
 	
 682 & d*8Z($--Mx( (y{ { !*Z*J8GYZ[[2://2K2KAB2OP3chhPP)1)<N2O)P$$'@%PRfhjk59MIJ%m_,\]j\kk~  3z?a#7m_ -00=>UW  !OE!*:!6 #!$.z$7M#;M?&QXPYYrs  !#S!$-dO ILGS-HRY[h-i*<I#G9Bwiq9.(7	=9Hh(9 "((2LL4z!34(X__5F%GHI  &&u]';<T")#* LL99U#D %0%,,T2E6}oFX! *  VMV:  LL$ 	X__ & 
 ]+	- /3x47Gd4>*T6 ?*m ,R S`Q` a& (; 	6 I%LL *   LL *  CdN 
LL & << =	"  s Qs   2Orb   refrk   r=   c           	      (   t        | t              r| j                  rj| j                  dvr)t	        d| d| j                   d| j                   d      | j                  j                  |      }d| d| d}| j                  ||fS | j                  | j                  j                  |      d fS t        | t        j                        rE| j                         j                         t        k  s|r| |d fS | j                         r*| j                         t        k  r| j                         |d fS t        j                  t        j                   fD ]  }| j                  |	      s| | j#                         d
   k(  j%                         j'                         sI | j#                         d
   j                         j(                  | j                          | d| dd fc S  t	        d| d| j                         j                          d      | |d fS )N)r   r   z$Bundled input argument at position 'z' has both arg.fmt_fn => 
z 
 and arg.fmt  => zd. Please choose `arg.fmt` if the deflater is straightforward or `arg.fmt_fn` if you need a function.zself.rF   ))memory_formatr   z.contiguous(memory_format=z ' is a tensor with storage size z6. You probably don't want to bundle this as an input. )r)   r   r   r   r-   r\   r   r*   Tensor_typed_storagesizeMAX_RAW_TENSOR_SIZEis_contiguousnumelr8   contiguous_formatchannels_lastflattenallitemexpand)rb   rq   rk   r=   rn   rJ   r   s          r!   rU   rU   l  s    #}%::wwj(:3% @,,/JJ< 8**-'' 3;;  !$

 1 12H I12!C5:D99d$55599cggnnS1477#u||$$$&*==T>! 399;2E#E99;T)) ++U-@-@A 	HC  s 3a@P9P8U8U8W8\8\8^7a(..077D%9#a@$H H	H 23% 8**-*<*<*>*C*C*E)F GCD
 	
 C~r    script_modulec                    g }g }t        | d      r3|j                  d       |j                  d       |j                  d       t        | d      r|j                  d       | j                         }|D ]  }|j                  d|z          |j                  d|z          |j                  d|z          t        | d|       }t	         |             }t        | |      }t        t	        |j                  j                        dz
        D ]>  }t        |      D ].  }	t        ||	|	      }
t        | |
      s|j                  |
       0 @  ||fS )
Nr@   get_num_bundled_inputsrun_on_bundled_inputrA   get_all_bundled_inputs_for_rE   rD   rC   rj   	input_idxra   )	r>   rS   rA   getattrrQ   rangerM   rN   rT   )r   methods
attributesall_infora   bundled_inputs_fnnum_bundled_inputsfuncrj   r   helper_fn_names              r!   r.   r.     sY   GJ }67/0/0-.}EF>? FFH% 	7MNN8=HINN:]JK9MIJ '-m_=! '**;*=&> =-8D T[[%:%:!;a!?@ 	7!&'9!: 7I%@ '"+&3&N }n=~67	7	70 Z  r    rj   r   ra   c                     d| d| d|  S )N_inflate_helper_for__input__arg_r   r   s      r!   rT   rT     s    
 "-	{%yQQr    dtypec                 d     t        j                  d|       j                  | }t        |d      S )z9Generate a tensor that will be inflated with torch.randn.rC   r   ztorch.randn_like({})r   r   )r*   zerosr   r   )r   rw   stubs      r!   bundle_randnr     s-    -5;;q&--t4Dt)?@@r    c                     t        | d      S )z3Wrap a tensor to allow bundling regardless of size.r   r   )r   )ts    r!   bundle_large_tensorr     s    qd++r    )N)NNNF)NNF)F)#typingr   r   r   r   r   r   r	   r
   r   r   rW   r*   torch._Cr   r   torch.jit._recursiver   r   rx   r   r+   r,   r   r:   r5   r3   boolru   rU   r.   intrT   r   r   r   r    r!   <module>r      s   d c c   ( 0 CL J : GKV
 6:Vyy%%Vhxc3h894(S[\abegjbj\kSlJm@m;nnoV uT#YXtCy-@(AABCV
  (S	2V YYVt 7;59$(3yy%%3%S/233  (S	23 tCy!	3 
3r 6:48tyy%%tXxsCx(ABBCt  (S	2t tHd3i/01	t 
tn LQ.	
...1.DH.
5ELL!356.`%!eii>T>T %!Y^_cdg_hjnorjs_sYt %!PRRR R 		R # A,r    