
    Ph                        d dl mZ d dlZd dlZd dlmZmZmZ d dlZd dl	m
Z d dlmZ erd dlZej                  	 	 	 	 	 	 	 	 	 	 dd       Zej                  	 d		 	 	 	 	 	 	 	 	 	 	 	 	 d
d       Zy)    )annotationsN)TupleTYPE_CHECKINGUnion)_type_utils)	_beartypec                   ddl } |j                         }||_        t        j                  j                  | j                        j                         |_        |j                  j                  | j                         |j                  j                  |_        |d| j                         j                         d}|j!                         D ]6  \  }}|j"                  j%                         }	||	_        t)        |      |	_        8 t,        j.                  j1                  ||      }
t,        j.                  j3                  |
      rt-        j4                  |
       t,        j.                  j7                  |
      }t,        j.                  j3                  |      st-        j8                  |       t;        |
d      5 }|j=                  | j?                  d      jA                                ddd       |S # 1 sw Y   |S xY w)a  Create a TensorProto with external data from a PyTorch tensor.
    The external data is saved to os.path.join(basepath, location).

    Args:
        tensor: Tensor to be saved.
        name: Name of the tensor (i.e., initializer name in ONNX graph).
        location: Relative location of the external data file
            (e.g., "/tmp/initializers/weight_0" when model is "/tmp/model_name.onnx").
        basepath: Base path of the external data file (e.g., "/tmp/external_data" while model must be in "/tmp").


    Reference for ONNX's external data format:
        How to load?
        https://github.com/onnx/onnx/blob/5dac81ac0707bdf88f56c35c0a5e8855d3534673/onnx/external_data_helper.py#L187
        How to save?
        https://github.com/onnx/onnx/blob/5dac81ac0707bdf88f56c35c0a5e8855d3534673/onnx/external_data_helper.py#L43
        How to set ONNX fields?
        https://github.com/onnx/onnx/blob/5dac81ac0707bdf88f56c35c0a5e8855d3534673/onnx/external_data_helper.py#L88
    r   N)locationoffsetlengthxbT)force)!onnxTensorProtonamejit_type_utilsJitScalarType
from_dtypedtype	onnx_type	data_typedimsextendshapeEXTERNALdata_locationuntyped_storagenbytesitemsexternal_dataaddkeystrvalueospathjoinexistsremovedirnamemakedirsopenwritenumpytobytes)tensorr   r
   basepathr   tensor_protokey_value_pairskventryexternal_data_file_pathexternal_data_dir_path	data_files                pC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\torch/onnx/_internal/fx/serialization.py'_create_tensor_proto_with_external_datar;      s   0 #4##%LL+99DDik  V\\*!%!1!1!:!:L
 ((*113O
  %%'1**..0	!f ( !ggll8X>	ww~~-.
		)*  WW__-DE77>>01 	*+ 
%t	,	 	4088:;	 
-  
- s   70G11G;c                   ddl } |j                         }|j                  |       |j                  j                  D ch c]  }|j
                   }	}|D ]  }
t        j                  |
      }|j                         D ]  \  }}|r|j                  dd      }||	v r|	j                  |       n>|	D ]9  }|j                  |      s|j                  |      s&|}|	j                  |        n t        j                  j                  ||      }t        ||||       }|j                  j                   j#                  |          |j$                  |t        j                  j                  | |             yc c}w )am  Load PyTorch tensors from files and add to "onnx_model" as external initializers.

    Output files:
        ONNX model file path:
        ONNX initializer folder: os.path.join(basepath, initializer_location)

    After running this function, you can do
        ort_sess = onnxruntime.InferenceSession(os.path.join(basepath, model_location))
    to execute the model.

    Arguments:
        basepath: Base path of the external data file (e.g., "/tmp/large-onnx-model").
        model_location: Relative location of the ONNX model file.
            E.g., "model.onnx" so that the model file is saved to
            "/tmp/large-onnx-model/model.onnx".
        initializer_location: Relative location of the ONNX initializer folder.
            E.g., "initializers" so that the initializers are saved to
            "/tmp/large-onnx-model/initializers".
        torch_load_paths: Files which containing serialized PyTorch tensors to be saved
            as ONNX initializers. They are loaded by torch.load.
        onnx_model: ONNX model to be saved with external initializers.
            If an input name matches a tensor loaded from "torch_load_paths",
            the tensor will be saved as that input's external initializer.
        rename_initializer: Replaces "." by "_" for all ONNX initializer names.
            Not needed by the official torch.onnx.dynamo_export. This is a hack
            for supporting `FXSymbolicTracer` tracer with fake tensor mode.
            In short, `FXSymbolicTracer` lifts FX parameters (self.linear_weight)
            as inputs (`def forward(self, linear_weight)`) and therefore, `.` cannot be used.
    r   N._)r   
ModelProtoCopyFromgraphinputr   torchloadr   replacer)   endswithr%   r&   r'   r;   initializerappendsave)r1   model_locationinitializer_locationtorch_load_paths
onnx_modelrename_initializerr   onnx_model_with_initializersrB   onnx_input_namesr&   
state_dictr   r0   onnx_input_namerelative_tensor_file_pathr2   s                    r:   save_model_with_external_datarT   S   sZ   N #24??#4  ))*50:0@0@0F0FG0Fu

0FG ZZ%
&,,.LD&!
 ||C- '' ''-'7O&//59W  /(//@ (8 )+5I4(P% C7L )..::AA,OK / !T DII*BGGLL>,RSY Hs   E5)
r0   ztorch.Tensorr   r#   r
   r#   r1   r#   returnzonnx.TensorProto)F)r1   r#   rJ   r#   rK   r#   rL   z"Tuple[Union[str, io.BytesIO], ...]rM   zonnx.ModelProtorN   boolrU   None)
__future__r   ior%   typingr   r   r   rC   
torch.onnxr   r   torch.onnx._internalr   r   beartyper;   rT        r:   <module>r`      s    " 	 	 . .  4 * @@ #@/2@>A@@ @F   %VTVTVT VT 9	VT
  VT VT 
VT VTr_   