o
    XiU                     @  s   d Z ddlmZ ddgZddlZddlmZ ddlZddlm	Z	m
Z
mZ ddlmZ dd	lmZ ddddZ				ddddZdS )zLoad and save ONNX models.    )annotationsloadsaveN)Callable)_core
_protocolsserde)external_data)zippathstr | os.PathLikeformat
str | Nonereturn_core.Modelc                 C  s8   t j| |dd}t|}tj| }t|j	| |S )a  Load an ONNX model from a file.

    Args:
        path: The path to the ONNX file.
        format: The format of the file (e.g. protobuf, textproto, json, etc.).
            If None, the format is inferred from the file extension.

    Returns:
        The loaded model.
    F)r   load_external_data)
onnxr   r   deserialize_modelosr   dirname_external_dataset_base_dirgraph)r   r   protomodelbase_dir r   ?/home/ubuntu/.local/lib/python3.10/site-packages/onnx_ir/_io.pyr      s
   
   r   r	   str | os.PathLike | Nonesize_threshold_bytesintcallbackOCallable[[_protocols.TensorProtocol, _external_data.CallbackInfo], None] | NoneNonec                 C  s   |durjt j|rtd| dt j|}g }|  D ]
}||j  qdd |D }	z)t	j
| ||||d} t| }
tj|
||d W t||	dd	D ]\}}||_qPdS t||	dd	D ]\}}||_qaw t| }
tj|
||d dS )
a5	  Save an ONNX model to a file.

    The model remains unchanged after the call. If any existing external tensor
    references the provided ``external_data`` path, it will be invalidated
    after the external data is overwritten. To obtain a valid model, use :func:`load`
    to load the newly saved model, or provide a different external data path that
    is not currently referenced by any tensors in the model.

    .. tip::

        A simple progress bar can be implemented by passing a callback function as the following::

            import onnx_ir as ir
            import tqdm

            with tqdm.tqdm() as pbar:
                total_set = False

                def callback(tensor: ir.TensorProtocol, metadata: ir.external_data.CallbackInfo) -> None:
                    nonlocal total_set
                    if not total_set:
                        pbar.total = metadata.total
                        total_set = True

                    pbar.update()
                    pbar.set_description(f"Saving {tensor.name} ({tensor.dtype}, {tensor.shape}) at offset {metadata.offset}")

                ir.save(
                    ...,
                    callback=callback,
                )

    Args:
        model: The model to save.
        path: The path to save the model to. E.g. "model.onnx".
        format: The format of the file (e.g. ``protobuf``, ``textproto``, ``json``, etc.).
            If None, the format is inferred from the file extension.
        external_data: The relative path to save external data to. When specified,
            all initializers in the model will be converted to external data and
            saved to the specified directory. If None, all tensors will be saved unmodified.
            That is, if a tensor in the model is already external, it will be saved
            with the same external information; if the tensor is not external,
            it will be serialized in the ONNX Proto message.
        size_threshold_bytes: Save to external data if the tensor size in bytes is larger than this threshold.
            Effective only when ``external_data`` is set.
        callback: A callback function that is called for each tensor that is saved to external data
            for debugging or logging purposes.

    Raises:
        ValueError: If the external data path is an absolute path.
    NzDThe external data path must be relative to the ONNX file path, not 'z'.c                 S  s   g | ]}|j qS r   )const_value).0vr   r   r   
<listcomp>q   s    zsave.<locals>.<listcomp>)r    r"   )r   T)strict)r   r   isabs
ValueErrorr   graphsextendinitializersvaluesr   unload_from_modelr   serialize_modelr   r   r
   r%   )r   r   r   r	   r    r"   r   initialized_valuesr   tensorsr   initializertensorr   r   r   r   )   s6   <


)N)r   r   r   r   r   r   )NNr   N)r   r   r   r   r   r   r	   r   r    r!   r"   r#   r   r$   )__doc__
__future__r   __all__r   typingr   r   onnx_irr   r   r   r	   r   onnx_ir._polyfillr
   r   r   r   r   r   r   <module>   s   