
    2Vh                         d dl Z d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlm	Z	 d dlm
Z
 d d	lmZ d d
lmZ ddZd Zd Zy)    N)backend)treeconvert_spec_to_tensor)get_input_signature)make_tf_tensor_spec)DEFAULT_ENDPOINT_NAME)ExportArchive)patch_tf2onnx)io_utilsc                    |}|d}|$t        |       }|r| j                  st        d      t        j                         dv rWddlm} t        j                  t        |      }t        | |fi |}t                |j                  j                  |||       n`t        j                         dk(  r=ddl}t        j                  d	 |      }	t        |	      }	t        d
 |	D              rt        d      t!        | d      r| j#                          t%        j&                         5  t%        j(                  dd       t%        j(                  dd       t%        j(                  dd       t%        j(                  dd       t%        j(                  dd       	 |j*                  j-                  | |	|d      }
t!        |
d      r|
j/                          |
j1                  |       ddd       nt3        d      |rt5        j6                  d| d       yy#  |d}|j*                  j-                  | |	||       Y XxY w# 1 sw Y   PxY w)a  Export the model as a ONNX artifact for inference.

    This method lets you export a model to a lightweight ONNX artifact
    that contains the model's forward pass only (its `call()` method)
    and can be served via e.g. ONNX Runtime.

    The original code of the model (including any custom layers you may
    have used) is *no longer* necessary to reload the artifact -- it is
    entirely standalone.

    Args:
        filepath: `str` or `pathlib.Path` object. The path to save the artifact.
        verbose: `bool`. Whether to print a message during export. Defaults to
            `None`, which uses the default value set by different backends and
            formats.
        input_signature: Optional. Specifies the shape and dtype of the model
            inputs. Can be a structure of `keras.InputSpec`, `tf.TensorSpec`,
            `backend.KerasTensor`, or backend tensor. If not provided, it will
            be automatically computed. Defaults to `None`.
        **kwargs: Additional keyword arguments.

    **Note:** This feature is currently supported only with TensorFlow, JAX and
    Torch backends.

    **Note:** The dtype policy must be "float32" for the model. You can further
    optimize the ONNX artifact using the ONNX toolkit. Learn more here:
    [https://onnxruntime.ai/docs/performance/](https://onnxruntime.ai/docs/performance/).

    **Note:** The dynamic shape feature is not yet supported with Torch
    backend. As a result, you must fully define the shapes of the inputs using
    `input_signature`. If `input_signature` is not provided, all instances of
    `None` (such as the batch size) will be replaced with `1`.

    Example:

    ```python
    # Export the model as a ONNX artifact
    model.export("path/to/location", format="onnx")

    # Load the artifact in a different process/environment
    ort_session = onnxruntime.InferenceSession("path/to/location")
    ort_inputs = {
        k.name: v for k, v in zip(ort_session.get_inputs(), input_data)
    }
    predictions = ort_session.run(None, ort_inputs)
    ```
    NTzSThe model provided has never called. It must be called at least once before export.)
tensorflowjaxr   )tf2onnx)output_pathtorchc                     t        | d      S )N   )replace_none_numberr   )xs    E/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/export/onnx.py<lambda>zexport_onnx.<locals>.<lambda>\   s    ,QAF     c              3   <   K   | ]  }t        |t                y w)N)
isinstancedict).0r   s     r   	<genexpr>zexport_onnx.<locals>.<genexpr>a   s     :qz!T":s   zUCurrently, `export_onnx` in the torch backend doesn't support dictionaries as inputs.evalignorez4.*\n.*\n*.*\n*.*export will treat it as a constant.*)messagez+.*not properly registered as a submodule,.*z3.*which is what 'get_attr' Nodes typically target.*z2.*underlying reference in the owning GraphModule.*z(.*suppressed about get_attr references.*)verbosedynamooptimizeF)r"   zI`export_onnx` is only compatible with TensorFlow, JAX and Torch backends.zSaved artifact at 'z'.)r   _called
ValueErrorr   keras.src.utils.module_utilsr   r   map_structurer   get_concrete_fnr   convertfrom_functionr   tupleanyhasattrr   warningscatch_warningsfilterwarningsonnxexportr$   saveNotImplementedErrorr   	print_msg)modelfilepathr"   input_signaturekwargsactual_verboser   decorated_fnr   sample_inputsonnx_programs              r   export_onnxr?      sZ   ` N-e4emmA 
 118,,
 'uoHH 	%%/x 	& 	
 
	g	%**F
 m,:M::* 
 5&!JJL$$& &	##O ##F ##N ##M ##"M$zz00=.  1   <4 ))+!!(+9&	 &	P "
 	

 0
"=> !	? &+N 

!!=(N " I&	 &	s    %A4IAH%H><II
c                     | j                         } d| vrd| d<   d| vrddd| d<   | d   durt        d      | d   d   durt        d      | d   d	   durt        d
      | S )N	is_staticTjax2tf_kwargsF)
enable_xlanative_serializationzB`is_static` must be `True` in `kwargs` when using the jax backend.rC   zU`enable_xla` must be `False` in `kwargs['jax2tf_kwargs']` when using the jax backend.rD   z_`native_serialization` must be `False` in `kwargs['jax2tf_kwargs']` when using the jax backend.)copyr&   )r:   s    r   _check_jax_kwargsrF      s    [[]F& "{f$  $)#
 k$&P
 	
 o|,E9*
 	
 o56eCD
 	
 Mr   c                    t        j                          dk(  rt        |      }t               } |j                  t        | |fi | t        j                          dk(  r|j                          |j                  t              S )z0Get the `tf.function` associated with the model.r   r   )r   rF   r
   track_and_add_endpointr	   _filter_and_track_resources_get_concrete_fn)r7   r9   r:   export_archives       r   r)   r)      sp    E!"6*"_N)N))uo9? L(224**+@AAr   )NN)r/   	keras.srcr   r   keras.src.export.export_utilsr   r   r   keras.src.export.saved_modelr	   r
   keras.src.export.tf2onnx_libr   keras.src.utilsr   r?   rF   r)    r   r   <module>rR      s5       @ = = > 6 6 $I?X8
Br   