
    `i8                       d Z ddlmZ ddlmZ erddlmZ ddlmZ ddlZddl	m
Z
 ddlmZmZ dd	lmZmZ d
dlmZmZ d
dlmZ g dZ G d de
          Z ed           G d dej                              ZdddZd d!dZdS )"z%Module related objects and functions.    )annotations)TYPE_CHECKING)Sequence)AnyN)IntEnum)PathLikefspath)ClassVarcast   )_ffi_apicore)register_object)ModuleModulePropertyMaskload_module
system_libc                      e Zd ZdZdZdZdZdS )r   zRuntime Module Property Mask.r         N)__name__
__module____qualname____doc__BINARY_SERIALIZABLERUNNABLECOMPILATION_EXPORTABLE     b/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/tvm_ffi/module.pyr   r   )   s'        ''H"r   r   z
ffi.Modulec                      e Zd ZU dZded<   dZded<   ed-d	            Zed.d            Zd/d0dZ	d1dZ
d/d2dZ	 d/d3dZd/d4dZd5dZd1dZd6dZd7d8d!Zd9d#Zd:d%Zd;d&Zd;d'Zd;d(Zd<d)Zd7d=d+Zd,S )>r   a~  Module container for dynamically loaded Module.

    Examples
    --------
    .. code-block:: python

        import tvm_ffi

        # Load the module from a shared library
        mod = tvm_ffi.load_module("path/to/library.so")

        # Call exported function
        mod.func_name(*args)

        # Query function metadata (type signature)
        metadata = mod.get_function_metadata("func_name")

        # Query function documentation (if available)
        doc = mod.get_function_doc("func_name")

    See Also
    --------
    :py:func:`tvm_ffi.load_module`
    :py:meth:`get_function_metadata`
    :py:meth:`get_function_doc`

    Notes
    -----
    If you load a module within a local scope, be careful when any called function
    creates and returns an object. The memory deallocation routines are part of
    the library's code. If the module is unloaded before the object is destroyed,
    the deleter may call an invalid address. Keep the module loaded until all returned
    objects are deleted. You can safely use returned objects inside a nested function
    that finishes before the module goes out of scope. When possible, consider keeping
    the module alive in a long-lived/global scope (for example, in a global state) to
    avoid premature unloading.

    .. code-block:: python

        def bad_pattern(x):
            # Bad: unload order of `tensor` and `mod` is not guaranteed
            mod = tvm_ffi.load_module("path/to/library.so")
            # ... do something with the tensor
            tensor = mod.func_create_and_return_tensor(x)


        def good_pattern(x):
            # Good: `tensor` is freed before `mod` goes out of scope
            mod = tvm_ffi.load_module("path/to/library.so")

            def run_some_tests():
                tensor = mod.func_create_and_return_tensor(x)
                # ... do something with the tensor

            run_some_tests()

    zSequence[Any]imports_mainzClassVar[str]
entry_namereturnstrc                *    t          j        |           S )zGet type key of the module.)r   ModuleGetKindselfs    r    kindzModule.kindu   s     %d+++r   list[Module]c                    | j         S )zgGet imported modules.

        Returns
        -------
        modules
            The module

        )r"   r)   s    r    importszModule.importsz   s     }r   Fnamequery_importsboolc                .    t          j        | ||          S )a  Return True if the module defines a global function.

        Notes
        -----
        ``implements_function(name)`` does not guarantee that
        ``get_function(name)`` will return a callable, because some module
        kinds (e.g. a source-only module) may not provide a packed function
        implementation until further compilation occurs. However, a non-null
        result from ``get_function(name)`` should imply the module implements
        the function.

        Parameters
        ----------
        name
            The name of the function

        query_imports
            Whether to also query modules imported by this module.

        Returns
        -------
        True if module (or one of its imports) has a definition for name.

        )r   ModuleImplementsFunction)r*   r/   r0   s      r    implements_functionzModule.implements_function   s    2 0t]KKKr   core.Functionc                    	 |                      |          }|| j        |<   |S # t          $ r t          d| d          w xY w)z2Accessor to allow getting functions as attributes.Module has no function '')get_function__dict__AttributeError)r*   r/   funcs      r    __getattr__zModule.__getattr__   se    	E$$T**D"&DM$K 	E 	E 	E !CD!C!C!CDDD	Es	    # Ac                    t          j        | ||          }t          t          j        |          }|t          d| d          |S )a  Get function from the module.

        Parameters
        ----------
        name
            The name of the function

        query_imports
            Whether to also query modules imported by this module.

        Returns
        -------
        The result function.

        Nr7   r8   )r   ModuleGetFunctionr   r   Functionr;   )r*   r/   r0   r<   s       r    r9   zModule.get_function   sM      )$mDDDM4((< !CD!C!C!CDDDr   dict[str, Any] | Nonec                ^    t          j        | ||          }|dS t          j        |          S )a  Get metadata for a function exported from the module.

        This retrieves metadata for functions exported via c:macro:`TVM_FFI_DLL_EXPORT_TYPED_FUNC`
        and when c:macro:`TVM_FFI_DLL_EXPORT_INCLUDE_METADATA` is on, which includes type schema
        information.

        Parameters
        ----------
        name
            The name of the function

        query_imports
            Whether to also query modules imported by this module.

        Returns
        -------
        metadata
            A dictionary containing function metadata. The ``type_schema`` field
            encodes the callable signature.

        Examples
        --------
        .. code-block:: python

            import tvm_ffi
            from tvm_ffi.core import TypeSchema
            import json

            mod = tvm_ffi.load_module("add_one_cpu.so")
            metadata = mod.get_function_metadata("add_one_cpu")
            schema = TypeSchema.from_json_str(metadata["type_schema"])
            print(schema)  # Shows function signature

        See Also
        --------
        :py:func:`tvm_ffi.get_global_func_metadata`
            Get metadata for global registry functions.

        N)r   ModuleGetFunctionMetadatajsonloads)r*   r/   r0   metadata_strs       r    get_function_metadatazModule.get_function_metadata   s4    T  9$mTT4z,'''r   
str | Nonec                :    t          j        | ||          }|r|ndS )a^  Get documentation string for a function exported from the module.

        This retrieves documentation for functions exported via c:macro:`TVM_FFI_DLL_EXPORT_TYPED_FUNC_DOC`.

        Parameters
        ----------
        name
            The name of the function

        query_imports
            Whether to also query modules imported by this module.

        Returns
        -------
        doc : str or None
            The documentation string if available, None otherwise.

        Examples
        --------
        .. code-block:: python

            import tvm_ffi

            mod = tvm_ffi.load_module("mylib.so")
            doc = mod.get_function_doc("process_batch")
            if doc:
                print(doc)

        See Also
        --------
        :py:meth:`get_function_metadata`
            Get metadata including type schema.

        N)r   ModuleGetFunctionDoc)r*   r/   r0   doc_strs       r    get_function_doczModule.get_function_doc   s(    F /dMJJ!+wwt+r   moduleNonec                0    t          j        | |           dS )zAdd module to the import list of current one.

        Parameters
        ----------
        module
            The other module.

        N)r   ModuleImportModule)r*   rM   s     r    import_modulezModule.import_module  s     	#D&11111r   c                t    t          |t                    st          d          |                     |          S )z;Return function by name using item access (module["func"]).z%Can only take string as function name)
isinstancer&   
ValueErrorr9   )r*   r/   s     r    __getitem__zModule.__getitem__   s8    $$$ 	FDEEE  &&&r   argsr   c                     | j         | S )z*Call the module's entry function (`main`).)r#   )r*   rV   s     r    __call__zModule.__call__&  s     ty$r    fmtc                ,    t          j        | |          S )zGet source code from module, if available.

        Parameters
        ----------
        fmt
            The specified format.

        Returns
        -------
        The result source code.

        )r   ModuleInspectSource)r*   rZ   s     r    inspect_sourcezModule.inspect_source+  s     +D#666r   Sequence[str]c                *    t          j        |           S )zGet the format of the module.)r   ModuleGetWriteFormatsr)   s    r    get_write_formatszModule.get_write_formats:  s    -d333r   intc                *    t          j        |           S )zGet the runtime module property mask. The mapping is stated in ModulePropertyMask.

        Returns
        -------
        Bitmask of runtime module property

        )r   ModuleGetPropertyMaskr)   s    r    get_property_maskzModule.get_property_mask>  s     -d333r   c                L    |                                  t          j        z  dk    S )zReturn whether the module is binary serializable (supports save_to_bytes).

        Returns
        -------
        True if the module is binary serializable.

        r   )re   r   r   r)   s    r    is_binary_serializablezModule.is_binary_serializableH  s%     &&((+=+QQVWWWr   c                L    |                                  t          j        z  dk    S )zReturn whether the module is runnable (supports get_function).

        Returns
        -------
        True if the module is runnable.

        r   )re   r   r   r)   s    r    is_runnablezModule.is_runnableR  s$     &&((+=+FF1LLr   c                L    |                                  t          j        z  dk    S )zReturn whether the module is compilation exportable.

        write_to_file is supported for object or source.

        Returns
        -------
        True if the module is compilation exportable.

        r   )re   r   r   r)   s    r    is_compilation_exportablez Module.is_compilation_exportable\  s%     &&((+=+TTYZZZr   c                .    t          j        |            dS )z!Remove all imports of the module.N)r   ModuleClearImportsr)   s    r    clear_importszModule.clear_importsh  s    #D)))))r   	file_namec                2    t          j        | ||           dS )a*  Write the current module to file.

        Parameters
        ----------
        file_name
            The name of the file.
        fmt
            The format of the file.

        See Also
        --------
        tvm.runtime.Module.export_library : export the module to shared library.

        N)r   ModuleWriteToFile)r*   ro   rZ   s      r    write_to_filezModule.write_to_filel  s     	"4C88888r   N)r%   r&   )r%   r,   )F)r/   r&   r0   r1   r%   r1   )r/   r&   r%   r5   )r/   r&   r0   r1   r%   r5   )r/   r&   r0   r1   r%   rA   )r/   r&   r0   r1   r%   rH   )rM   r   r%   rN   )rV   r   r%   r   rY   )rZ   r&   r%   r&   )r%   r^   )r%   rb   )r%   r1   )r%   rN   )ro   r&   rZ   r&   r%   rN   )r   r   r   r   __annotations__r$   propertyr+   r.   r4   r=   r9   rG   rL   rQ   rU   rX   r]   ra   re   rg   ri   rk   rn   rr   r   r   r    r   r   1   s        8 8x  !'J&&&&, , , X, 	 	 	 X	L L L L L6E E E E    . 05-( -( -( -( -(^$, $, $, $, $,L	2 	2 	2 	2' ' ' '       
7 7 7 7 74 4 4 44 4 4 4X X X XM M M M
[ 
[ 
[ 
[* * * *9 9 9 9 9 9 9r   r   rY   symbol_prefixr&   r%   c                *    t          j        |           S )a  Get system-wide library module singleton with functions prefixed by ``__tvm_ffi_{symbol_prefix}``.

    The library module contains symbols that are registered via :cpp:func:`TVMFFIEnvModRegisterSystemLibSymbol`.

    .. note::
        The system lib is intended to be statically linked and loaded during the entire lifecycle of the program.
        If you want dynamic loading features, use DSO modules instead.

    Parameters
    ----------
    symbol_prefix
        Optional symbol prefix that can be used for search. When we lookup a symbol
        symbol_prefix + name will first be searched, then the name without symbol_prefix.

    Returns
    -------
    The system-wide library module.

    Examples
    --------
    Register the function ``test_symbol_add_one`` in C++ with the name ``__tvm_ffi_test_symbol_add_one``
    via :cpp:func:`TVMFFIEnvModRegisterSystemLibSymbol`.

    .. code-block:: cpp

        // A function to be registered in the system lib
        static int test_symbol_add_one(void*, const TVMFFIAny* args, int32_t num_args, TVMFFIAny* ret) {
          TVM_FFI_SAFE_CALL_BEGIN();
          TVM_FFI_CHECK(num_args == 1, "Expected 1 argument, but got: " + std::to_string(num_args));
          int64_t x = reinterpret_cast<const AnyView*>(args)[0].cast<int64_t>();
          reinterpret_cast<Any*>(ret)[0] = x + 1;
          TVM_FFI_SAFE_CALL_END();
        }

        // Register the function with name `test_symbol_add_one` prefixed by `__tvm_ffi_`
        int _ = TVMFFIEnvModRegisterSystemLibSymbol("__tvm_ffi_testing.add_one", reinterpret_cast<void*>(test_symbol_add_one));

    Look up and call the function from Python:

    .. code-block:: python

        import tvm_ffi

        mod: tvm_ffi.Module = tvm_ffi.system_lib(
            "testing."
        )  # symbols prefixed with `__tvm_ffi_testing.`
        func: tvm_ffi.Function = mod["add_one"]  # looks up `__tvm_ffi_testing.add_one`
        assert func(10) == 11

    )r   	SystemLib)rv   s    r    r   r   ~  s    f m,,,r   Tpathstr | PathLikekeep_module_aliver1   c                x    t          |           } t          j        |           }|rt          j        |           |S )a  Load module from file.

    Parameters
    ----------
    path
        The path to the module file.

    keep_module_alive
        Whether to keep the module alive. If True, the module will be kept alive
        for the duration of the program until libtvm_ffi.so is unloaded.

    Returns
    -------
    The loaded module

    Examples
    --------
    .. code-block:: python

        import tvm_ffi
        from pathlib import Path

        # Works with string paths
        mod = tvm_ffi.load_module("path/to/module.so")
        # Also works with pathlib.Path objects
        mod = tvm_ffi.load_module(Path("path/to/module.so"))

        mod.func_name(*args)

    See Also
    --------
    :py:class:`tvm_ffi.Module`

    )r	   r   ModuleLoadFromFileModuleGlobalsAdd)ry   r{   mods      r    r   r     s>    F $<<D

%d
+
+C '!#&&&Jr   rs   )rv   r&   r%   r   )T)ry   rz   r{   r1   r%   r   )r   
__future__r   typingr   collections.abcr   r   rD   enumr   osr   r	   r
   r   rY   r   r   registryr   __all__r   Objectr   r   r   r   r   r    <module>r      s  " , +
 # " " " " "             ((((((                ! ! ! ! ! ! ! !         % % % % % %
G
G
G# # # # # # # # I9 I9 I9 I9 I9T[ I9 I9 I9X
3- 3- 3- 3- 3-l' ' ' ' ' ' 'r   