Ë
    Q/æj˜,  ã                  óÆ   — d dl mZ d dlZd dlZd dlZd dlmZ d dlZd dlm	Z
 erd dlZ ej                  e«      Z	 d	 	 	 	 	 	 	 	 	 	 	 d	d„Zd„ Z	 d
	 	 	 	 	 	 	 	 	 	 	 	 	 dd„Zy)é    )ÚannotationsN)ÚTYPE_CHECKING)Ú_type_utilsc                óæ  — ddl }|�3t        j                  j                  |j                  j
                  «      n(t        j                  j                  | j                  «      }|�<|j                  «       | j                  k7  r| j                  |j                  «       «      }  |j                  «       }||_
        |j                  «       |_        |j                  j                  | j                  «       |j                  j                   |_        |d| j%                  «       j'                  «       dœ}|j)                  «       D ]6  \  }	}
|j*                  j-                  «       }|	|_        t1        |
«      |_        Œ8 t4        j6                  j9                  ||«      }t4        j6                  j;                  |«      rt5        j<                  |«       t4        j6                  j?                  |«      }t4        j6                  j;                  |«      st5        j@                  |«       tC        |d«      5 }|jE                  | jG                  d¬«      jI                  «       «       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Ú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                  úh/root/repos/pocs/video-evals/.venv/lib/python3.12/site-packages/torch/onnx/_internal/fx/serialization.pyÚ'_create_tensor_proto_with_external_datar>      sÿ  € ó6 ð Ð%ô 	×$Ñ$×3Ñ3Ø×&Ñ&×0Ñ0ô	
ô ×)Ñ)×4Ñ4°V·\±\ÓBð ð Ð! k×&7Ñ&7Ó&9¸V¿\¹\Ò&IØ—‘˜;×,Ñ,Ó.Ó/ˆà#�4×#Ñ#Ó%€LØ€LÔØ(×2Ñ2Ó4€LÔà×Ñ×Ñ˜VŸ\™\Ô*Ø!%×!1Ñ!1×!:Ñ!:€LÔð
 ØØ×(Ñ(Ó*×1Ñ1Ó3ñ€Oð
  ×%Ñ%Ó'ò ‰ˆˆ1Ø×*Ñ*×.Ñ.Ó0ˆØˆŒ	Ü˜!“fˆ�ðô !Ÿg™gŸl™l¨8°XÓ>ÐÜ	‡w�w‡~�~Ð-Ô.Ü
�	‰	Ð)Ô*ô  ŸW™WŸ_™_Ð-DÓEÐÜ�7‰7�>‰>Ð0Ô1ô 	�‰Ð*Ô+ô 
Ð% tÓ	,ð <°	ð 	�‰˜Ÿ™¨4˜Ó0×8Ñ8Ó:Ô;÷	<ð Ð÷<ð Ðús   È,0I&É&I0c                óÈ   — ddl m} i } || dd¬«      5 }|j                  «       D ]$  }|j                  |«      j	                  «       ||<   Œ& 	 d d d «       |S # 1 sw Y   |S xY w)Nr   )Ú	safe_openÚptÚcpu)Ú	frameworkÚdevice)Úsafetensorsr@   ÚkeysÚ
get_tensorrB   )Úsafetensors_filer@   ÚtensorsÚfr7   s        r=   Ú$_convert_safetensors_to_torch_formatrK   g   sh   € õ &à€GÙ	Ð#¨t¸EÔ	Bð /ÀaØ—‘“ò 	/ˆAØŸ™ a›×,Ñ,Ó.ˆG�AŠJñ	/÷/ð €N÷/ð €Nús   ”8AÁA!c                óX  — ddl }i }t        |j                  j                  «      D ��	ci c]  \  }}	|	j                  |“Œ }
}}	|j                  j
                  D �ch c]  }|j                  ’Œ }}|D �]†  }t        |t        «      r|}nFt        |t        «      r|j                  d«      rt        |«      }n	 t        j                  |dd¬«      }|j)                  «       D �]  \  }}|r|j+                  d
d«      }||v r|j-                  |«       n>|D ]9  }|j                  |«      s|j                  |«      sŒ&|}|j-                  |«        n t.        j0                  j3                  ||«      }|j                  j
                  D �	ci c]  }	|	j                  |	j4                  “Œ }}	||
v r|||
|   <   t7        |||| |j9                  |d«      «      }|j                  j                  j;                  |«       �Œ �Œ‰ t        t=        |j)                  «       d¬«      «      }|j?                  «       D ]  }|j                  j                  |= Œ  |j@                  |t.        j0                  j3                  | |«      «       yc c}	}w c c}w # t        t        f$ rŒ}dt        |«      v st        |t        j                   «      rXt"        j%                  d«       t        |t        j                   «      r|j'                  d«       t        j                  |d¬	«      }n|‚Y d}~�ŒPd}~ww xY wc c}	w )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.safetensorsrB   T)Úmap_locationÚmmapz+mmap can only be used with files saved withz®Failed 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.)rM   ú.Ú_)Úreverse)!r   Ú	enumerateÚgraphÚinitializerr   ÚinputÚ
isinstanceÚdictr$   ÚendswithrK   ÚtorchÚloadÚRuntimeErrorÚ
ValueErrorÚioÚBytesIOÚlogÚwarningÚseekr    Úreplacer*   r&   r'   r(   Útyper>   ÚpopÚappendÚsortedrF   Úsave)r2   Úmodel_locationÚinitializer_locationÚtorch_state_dictsÚ
onnx_modelÚrename_initializerr   Úinitializers_to_be_deletedÚidxr7   Úexisting_initializersrU   Úonnx_input_namesÚelÚ
state_dictÚer   r1   Úonnx_input_nameÚrelative_tensor_file_pathÚmodel_input_typesr5   s                         r=   Úsave_model_with_external_datarw   t   sú  € óN à!#Ðä"+¨J×,<Ñ,<×,HÑ,HÓ"I÷Ù˜˜Qˆ�‰�‰ðÐñ ð 1;×0@Ñ0@×0FÑ0FÖG u˜Ÿ
›
ÐGÐÐGØó I>ˆÜ�bœ$Ôð ‰Jä˜"œcÔ" r§{¡{°>Ô'BÜAÀ"ÓE‘
ð ô "'§¡¨B¸UÈÔ!N�Jð '×,Ñ,Ó.ó .	>‰LˆD�&Ù!ð
 —|‘| C¨Ó-�ð Ð'Ñ'à ×'Ñ'¨Õ-à'7ò �OØ&×/Ñ/°Ô5¸¿¹ÀÕ9Wð  /˜Ø(×/Ñ/°Ô@Ùðô )+¯©¯©Ð5IÈ4Ó(PÐ%ð :D×9IÑ9I×9OÑ9OÖ P°A §¡¨¯©¡Ð PÐÐ Pð Ð,Ñ,ØJNÐ*Ð+@ÀÑ+FÑGÜBØØØ)ØØ!×%Ñ% d¨DÓ1óˆLð ×Ñ×(Ñ(×/Ñ/°Ö=ò].	>ð7I>ôV "&ÜÐ)×/Ñ/Ó1¸4Ô@ó"Ðð *×.Ñ.Ó0ò .ˆØ×Ñ×(Ñ(¨Ñ-ð.ð €D‡I�Iˆjœ"Ÿ'™'Ÿ,™, x°Ó@ÕAùómùò Høô %¤jÐ1ò  ØDÌØóIñ ä# B¬¯
©
Ô3ÜŸ™ðzôô & b¬"¯*©*Ô5ØŸG™G AœJÜ%*§Z¡Z°ÀÔ%G™
à˜õ #ûð üò^ !Qs*   ©I>ÁJÂ7J	ÆL'Ê	L$ÊBLÌL$)N)r1   ztorch.Tensorr   r$   r   r$   r2   r$   r3   zonnx.TypeProto | NoneÚreturnzonnx.TensorProto)F)r2   r$   rh   r$   ri   r$   rj   z#tuple[dict | str | io.BytesIO, ...]rk   zonnx.ModelProtorl   Úboolrx   ÚNone)Ú
__future__r   r]   Úloggingr&   Útypingr   rY   Ú
torch.onnxr   r   r   Ú	getLoggerÚ__name__r_   r>   rK   rw   © ó    r=   ú<module>rƒ      sß   ðå "ã 	Û Û 	Ý  ã Ý 4ñ Ûà€g×Ñ˜Ó!€ð -1ðQØðQà
ðQð ðQð ð	Qð
 *ðQð óQòh	ð&  %ð@BØð@Bàð@Bð ð@Bð ;ð	@Bð
  ð@Bð ð@Bð 
ô@Br‚   