
    shb-                        S SK Jr  S SKrS SKrS SKrS SKJrJr  S SKrS SK	J
r  \(       a
  S SKrS SKJr  \R                  " \5      r S	           S
S jjrS r S             SS jjrg)    )annotationsN)IOTYPE_CHECKING)_type_utils)FileLikec                   SSK nUb3  [        R                  R                  UR                  R
                  5      O([        R                  R                  U R                  5      nUb=  UR                  5       U R                  :w  a  U R                  UR                  5       5      n UR                  " 5       nXl
        UR                  5       Ul        UR                  R                  U R                  5        UR                  R                   Ul        USU R%                  5       R'                  5       S.nUR)                  5        H5  u  pUR*                  R-                  5       nXl        [1        U
5      Ul        M7     [4        R6                  R9                  X25      n[4        R6                  R;                  U5      (       a  [4        R<                  " U5        [4        R6                  R?                  U5      n[4        R6                  R;                  U5      (       d  [4        R@                  " U5        [C        US5       nURE                  U RG                  SS9RI                  5       5        SSS5        U$ ! , (       d  f       U$ = f)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jit_type_utilsJitScalarTypefrom_onnx_typetensor_type	elem_type
from_dtypedtypetoTensorProtoname	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	   basepathdtype_overrider   scalar_typetensor_protokey_value_pairskventryexternal_data_file_pathexternal_data_dir_path	data_files                  y/Users/tiagomarins/Projetos/claudeai/copy_bank/venv/lib/python3.13/site-packages/torch/onnx/_internal/fx/serialization.py'_create_tensor_proto_with_external_datar@      s   6  % 	$$33&&00	
 ))44V\\B  !k&7&7&9V\\&I;,,./##%L(224LV\\*!%!1!1!:!:L
 ((*113O
  %%'**..0	!f ( !ggll8>	ww~~-..
		)*  WW__-DE77>>011 	*+ 
%t	,	 	4088:;	 
-  
-	, s   9-I00
I?c                    SSK Jn  0 nU" U SSS9 nUR                  5        H$  nUR                  U5      R	                  5       X$'   M&     S S S 5        U$ ! , (       d  f       U$ = f)Nr   )	safe_openptcpu)	frameworkdevice)safetensorsrB   keys
get_tensorrD   )safetensors_filerB   tensorsfr9   s        r?   $_convert_safetensors_to_torch_formatrM   i   sa     &G	#tE	BaAa,,.GJ  
C N 
C	B Ns   9A
A#c                r   SSK n0 n[        UR                  R                  5       VV	s0 s H  u  pU	R                  U_M     n
nn	UR                  R
                   Vs1 s H  oR                  iM     nnU GH  n[        U[        5      (       a  UnOr[        U[        [        R                  45      (       a6  [        R                  " U5      R                  S5      (       a  [        U5      nO [        R                  " USSS9nUR5                  5        GH-  u  nnU(       a  UR7                  S
S5      nUU;   a  UR9                  U5        OJU HD  nUR                  U5      (       d  UR                  U5      (       d  M1  UnUR9                  U5          O   [        R:                  R=                  UU5      nUR                  R
                   V	s0 s H  oR                  U	R>                  _M     nn	UU
;   a  UXzU   '   [A        UUUU URC                  US5      5      nUR                  R                  RE                  U5        GM0     GM     [        [G        UR5                  5       SS95      nURI                  5        H  nUR                  R                  U	 M     URJ                  " U[        R:                  R=                  X5      5        gs  sn	nf s  snf ! [         ["        4 a  nS[        U5      ;   dO  [        U[$        R&                  [(        45      (       a  UR+                  5       (       a{  UR-                  5       (       af  [.        R1                  S5        [        U[$        R&                  [(        45      (       a  UR3                  S5        [        R                  " USS	9n SnAGNUeSnAff = fs  sn	f )a  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 ONNX external data file (e.g., "/path/to/large_model/").
    model_location: Relative location of the ONNX model file.
        E.g., "model.onnx" so that the model file is saved to
        "<basepath>/model.onnx".
    initializer_location: Relative location of the ONNX initializer folder.
        E.g., "initializers" so that the initializers are saved to
        "<basepath>/initializers/".
        Note: When initializers are >2GB, must be the same as `model_location`.
    torch_state_dicts: Dictionaries or files which contain PyTorch tensors to be saved
        as ONNX initializers. For non-dict arguments, `torch.load` will be used to load them from file-like objects.
    onnx_model: ONNX model to be saved with external initializers.
        If an input name matches a tensor loaded from "torch_state_dicts",
        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   Nz.safetensorsrD   T)map_locationmmapz+mmap can only be used with files saved withzFailed to load the checkpoint with memory-map enabled, retrying without memory-map.Consider updating the checkpoint with mmap by using torch.save() on PyTorch version >= 1.6.)rO   ._)reverse)&r   	enumerategraphinitializerr   input
isinstancedictr&   r(   PathLikefspathendswithrM   torchloadRuntimeError
ValueErrorioIOBaser   readableseekablelogwarningseekr"   replacer,   r)   r*   typer@   popappendsortedrH   save)r4   model_locationinitializer_locationtorch_state_dicts
onnx_modelrename_initializerr   initializers_to_be_deletedidxr9   existing_initializersrW   onnx_input_namesel
state_dicter   r3   onnx_input_namerelative_tensor_file_pathmodel_input_typesr7   s                         r?   save_model_with_external_datar}   v   s!   N !#"+J,<,<,H,H"I"I"I   1;0@0@0F0FG0Fu

0FGb$ J"sBKK011biim6L6L7 7 B"E
  "'BU!NJ" ',,.LD&!
 ||C- '' ''-'7O&//559W9W  /(//@ (8 )+5I4(P% :D9I9I9O9O P9OA9O P ,,JN*+FGB)!%%dD1L ((//=] /?  ^ "&)//14@" *..0((- 1 	IIj"'',,x@Au H  %j1  DAN"2		277KKMMKKMMz &b299b/::GGAJ%*ZZ%G
 b !Qs0   KK.K N4N1&B>N,*N,,N1)N)r3   ztorch.Tensorr   r&   r	   r&   r4   r&   r5   zonnx.TypeProto | Nonereturnzonnx.TensorProto)F)r4   r&   rn   r&   ro   r&   rp   ztuple[dict | FileLike, ...]rq   zonnx.ModelProtorr   boolr~   None)
__future__r   ra   loggingr(   typingr   r   r]   
torch.onnxr   r   r   torch.typesr   	getLogger__name__re   r@   rM   r}        r?   <module>r      s    " 	  	 $  4 $! -1QQ
Q Q 	Q
 *Q Qh	&  %DBDBDB DB 3	DB
  DB DB 
DBr   