
    i*                         S r SSKrSSKJr  SSKJr  SSKJrJrJ	r	J
r
JrJrJrJr   SSKJrJrJrJr   " S S	5      r " S
 S5      r " S S5      r " S S5      r " S S5      rg! \ a  r\" S5      \eSrCff = f)a  
Example usage:

.. code-block:: python

    from pathlib import Path

    import torch
    from executorch.runtime import Runtime, Program, Method

    et_runtime: Runtime = Runtime.get()
    program: Program = et_runtime.load_program(Path("/tmp/program.pte"))
    print("Program methods:", program.method_names)
    forward: Method = program.load_method("forward")

    inputs = (torch.ones(2, 2), torch.ones(2, 2))
    outputs = forward.execute(inputs)
    print(f"Ran forward({inputs})")
    print(f"  outputs: {outputs}")

Example output:

.. code-block:: text

    Program methods: {'forward'}
    Ran forward((tensor([[1., 1.],
            [1., 1.]]), tensor([[1., 1.],
            [1., 1.]])))
      outputs: [tensor([[2., 2.],
            [2., 2.]])]

Example usage with ETDump generation:

Note: ETDump requires building ExecuTorch with event tracing enabled
(CMake option ``EXECUTORCH_ENABLE_EVENT_TRACER=ON``).

.. code-block:: python

    from pathlib import Path
    import os

    import torch
    from executorch.runtime import Runtime, Program, Method

    # Create program with etdump generation enabled
    et_runtime: Runtime = Runtime.get()
    program: Program = et_runtime.load_program(
        Path("/tmp/program.pte"),
        enable_etdump=True,
        debug_buffer_size=int(1e7),  # 10MB buffer to capture all debug info
    )

    # Load method and execute
    forward: Method = program.load_method("forward")
    inputs = (torch.ones(2, 2), torch.ones(2, 2))
    outputs = forward.execute(inputs)

    # Write etdump result to file
    etdump_file = "/tmp/etdump_output.etdp"
    debug_file = "/tmp/debug_output.bin"
    program.write_etdump_result_to_file(etdump_file, debug_file)

    # Check that files were created
    print(f"ETDump file created: {os.path.exists(etdump_file)}")
    print(f"Debug file created: {os.path.exists(debug_file)}")
    print("Directory contents:", os.listdir("/tmp"))

Example output:

.. code-block:: text

    ETDump file created: True
    Debug file created: True
    Directory contents: ['program.pte', 'etdump_output.etdp', 'debug_output.bin']

Example usage with backend and operator introspection:

.. code-block:: python

    from executorch.runtime import Runtime

    runtime = Runtime.get()

    # Check available backends
    backends = runtime.backend_registry.registered_backend_names
    print(f"Available backends: {backends}")

    # Check if a specific backend is available
    if runtime.backend_registry.is_available("XnnpackBackend"):
        print("XNNPACK backend is available")

    # List all registered operators
    operators = runtime.operator_registry.operator_names
    print(f"Number of registered operators: {len(operators)}")

Example output:

.. code-block:: text

    Available backends: ['XnnpackBackend', ...]  # Depends on your build configuration
    XNNPACK backend is available
    Number of registered operators: 247  # Depends on linked kernels
    N)Path)
ModuleType)AnyBinaryIODictListOptionalSequenceSetUnion)ExecuTorchMethodExecuTorchProgram
MethodMetaVerificationzrPrebuilt <site-packages>/extension/pybindings/_portable_lib.so is not found. Please reinstall ExecuTorch from pip.c                   `    \ rS rSrSrS\SS4S jrS\\   S\\   4S jr	\
S\4S	 j5       rS
rg)Method   zaAn ExecuTorch method, loaded from a Program.
This can be used to execute the method with inputs.
methodreturnNc                     Xl         g N_method)selfr   s     Z/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/executorch/runtime/__init__.py__init__Method.__init__   s        inputsc                 $    U R                  U5      $ )zExecutes the method with the given inputs.

Args:
    inputs: A sequence of input values, typically torch.Tensor objects.

Returns:
    A list of output values, typically torch.Tensor objects.
r   )r   r   s     r   executeMethod.execute   s     ||F##r   c                 6    U R                   R                  5       $ )zGets the metadata for the method.

The metadata includes information about input and output specifications,
such as tensor shapes, data types, and memory requirements.

Returns:
    The MethodMeta object containing method specifications.
)r   method_metar   s    r   metadataMethod.metadata   s     ||''))r   r   )__name__
__module____qualname____firstlineno____doc__r   r   r
   r   r!   propertyr   r&   __static_attributes__ r   r   r   r      sQ    / D 	$hsm 	$ 	$ 	** 	* 	*r   r   c                       \ rS rSrSrS\S\\   SS4S jr\	S\
\   4S j5       rS	\S\\   4S
 jrS\S\4S jrS\S\SS4S jrSrg)Program   zyAn ExecuTorch program, loaded from binary PTE data.

This can be used to load the methods/models defined by the program.
programdatar   Nc                     X l         Xl        0 U l        [        U R                  R	                  5       5       H+  nS U R                  U R                  R                  U5      '   M-     g r   )_data_program_methodsrangenum_methodsget_method_name)r   r3   r4   
method_idxs       r   r   Program.__init__   sN    
57   9 9 ;<JGKDMM$--77
CD =r   c                 H    [        U R                  R                  5       5      $ )z8Returns method names of the Program as a set of strings.)setr8   keysr%   s    r   method_namesProgram.method_names   s     4==%%'((r   namec                     U R                   U   nUc2  [        U R                  R                  U5      5      nX R                   U'   U$ )zsLoads a method from the program.

Args:
    name: The name of the method to load.

Returns:
    The loaded method.
)r8   r   r7   load_method)r   rC   r   s      r   rE   Program.load_method   sA     t$>DMM55d;<F"(MM$r   method_namec                 8    U R                   R                  U5      $ )zGets the metadata for the specified method without loading it.

Args:
    method_name: The name of the method.

Returns:
    The metadata for the method, including input/output specifications.
)r7   r$   )r   rG   s     r   r&   Program.metadata   s     }}((55r   etdump_pathdebug_buffer_pathc                 :    U R                   R                  X5        g)zWrites the etdump and debug result to a file.

Args:
    etdump_path: The path to the etdump file.
    debug_buffer_path: The path to the debug buffer file.
N)r7   write_etdump_result_to_file)r   rJ   rK   s      r   rM   #Program.write_etdump_result_to_file   s     	11+Qr   )r6   r8   r7   )r(   r)   r*   r+   r,   r   r	   bytesr   r-   r   strrA   r   rE   r   r&   rM   r.   r/   r   r   r1   r1      s    
L 1 L% LT L )c#h ) ) (8  	6C 	6J 	6	R	R36	R		Rr   r1   c                   Z    \ rS rSrSrS\SS4S jr\S\\	   4S j5       r
S\	S\4S	 jrS
rg)BackendRegistry   z;The registry of backends that are available to the runtime.legacy_moduler   Nc                     Xl         g r   _legacy_moduler   rT   s     r   r   BackendRegistry.__init__       +r   c                 6    U R                   R                  5       $ )zBReturns the names of all registered backends as a list of strings.)rW   _get_registered_backend_namesr%   s    r   registered_backend_names(BackendRegistry.registered_backend_names   s     ""@@BBr   backend_namec                 8    U R                   R                  U5      $ )zChecks if a specific backend is available in the runtime.

Args:
    backend_name: The name of the backend to check (e.g., "XnnpackBackend").

Returns:
    True if the backend is available, False otherwise.
)rW   _is_available)r   r_   s     r   is_availableBackendRegistry.is_available   s     ""00>>r   rV   )r(   r)   r*   r+   r,   r   r   r-   r   rP   r]   boolrb   r.   r/   r   r   rR   rR      sM    E,j ,T , C$s) C C	? 	? 	?r   rR   c                   H    \ rS rSrSrS\SS4S jr\S\\	   4S j5       r
Srg)	OperatorRegistry   z<The registry of operators that are available to the runtime.rT   r   Nc                     Xl         g r   rV   rX   s     r   r   OperatorRegistry.__init__   rZ   r   c                 H    [        U R                  R                  5       5      $ )zBReturns the names of all registered operators as a set of strings.)r?   rW   _get_operator_namesr%   s    r   operator_namesOperatorRegistry.operator_names   s     4&&::<==r   rV   )r(   r)   r*   r+   r,   r   r   r-   r   rP   rl   r.   r/   r   r   rf   rf      s7    F,j ,T , >C > >r   rf   c                       \ rS rSrSr\\R                  " SS9SS j5       5       rS\	SS4S	 jr
\R                  S
SS.S\\\\\\4   S\S\S\S\4
S jjrSrg)Runtimei  a5  An instance of the ExecuTorch runtime environment.

This can be used to concurrently load and execute any number of ExecuTorch
programs and methods.

Attributes:
    backend_registry: Registry for querying available hardware backends.
    operator_registry: Registry for querying available operators/kernels.
   )maxsizer   c                  ,    SSK Js  Js  Jn   [	        U S9$ )zGets the Runtime singleton.r   NrT   ),executorch.extension.pybindings.portable_lib	extension
pybindingsportable_libro   rs   s    r   getRuntime.get  s     	ML]33r   rT   Nc                P    [        U5      U l        [        U5      U l        Xl        g r   )rR   backend_registryrf   operator_registryrW   rX   s     r   r   Runtime.__init__  s"     / >!1-!@+r   Fr   )verificationenable_etdumpdebug_buffer_sizer4   r~   r   r   c                   [        U[        [        45      (       a/  U R                  R	                  [        U5      UUUS9n[        USS9$ [        U[        5      (       a  UnOe[        U[        5      (       a  [        U5      nOD[        US5      (       a  UR                  5       nO"[        S[        U5      R                   S35      eU R                  R                  UUUUS9n[        XVS9$ )aW  Loads an ExecuTorch program from a PTE binary.

Args:
    data: The binary program data to load. Can be a file path (str or Path),
        bytes/bytearray, or a file-like object.
    verification: Level of program verification to perform (Minimal or InternalConsistency).
        Default is InternalConsistency.
    enable_etdump: If True, enables ETDump profiling for runtime performance analysis.
        Default is False.
    debug_buffer_size: Size of the debug buffer in bytes for ETDump data.
        Only used when enable_etdump=True. Default is 0.

Returns:
    The loaded Program instance.
)r   r   program_verificationN)r4   readz\Expected data to be bytes, bytearray, a path to a .pte file, or a file-like object, but got .)
isinstancer   rP   rW   _load_programr1   rO   	bytearrayhasattrr   	TypeErrortyper(   _load_program_from_buffer)r   r4   r~   r   r   p
data_bytess          r   load_programRuntime.load_program  s    . dT3K((##11D	+"3%1	 2 A 14((e$$Ji((tJT6""Jnostxoy  pC  pC  oD  DE  F  99'/!-	 : 
 q**r   )rW   r{   r|   )r   ro   )r(   r)   r*   r+   r,   staticmethod	functools	lru_cacherx   r   r   r   InternalConsistencyr   rO   r   r   r   rP   rd   intr1   r   r.   r/   r   r   ro   ro     s     #4 $ 4, , , &2%E%E#!"1+E9hc9:1+ #	1+
 1+ 1+ 
1+ 1+r   ro   )r,   r   pathlibr   typesr   typingr   r   r   r   r	   r
   r   r   rt   r   r   r   r   ModuleNotFoundErrorer   r1   rR   rf   ro   r/   r   r   <module>r      s   fP    L L L * *@9R 9Rx? ?0
> 
>K+ K+Q  
	> s   A' 'A;-	A66A;