
    oi                       / S Qr SSKrSSKJr  SSKJr  SSKJr  SSKJ	r	J
r
  SSKJr   SS	KJrJr   S
rSSKrSSKr SSKJr   SSKJr  SSKrSSKrSSKJr  SSK J!r!J"r"J#r#  SSK$r$SSK%J&r&J'r'  S r(   SPS jr) SSKJ*r*J+r+J,r,  SSK-J.r.  SSK/J0r0  SSKJ1r1  SSK2J2r3  SSKrSSK4r4SSK5r5SSK6r6S r7 S\Rp                  Rr                  S\:4S jr; S r< SSK=J>r>  SSKrSSK?r@SSKArASSK2J2r3  SSKBJCrC  \C " S S5      5       rD S  rE \R                  SQS! j5       rG SSKrSSKHrHSSKIrISSK-r-SSKrSSKJrJSSKKrK \-R&                  R                  rM \R                     SRS$ j5       r] \R                  SPS% j5       r^ SS&KJ_r_J`r`Jara  S' rb S( rc          SSS) jrd S*\4S+ jre S, rf S-\g\h   S\:4S. jri\R                            STS/ j5       rj S0\hS1\"\h   S2\hS3\#\   S4\#\h   S\:4S5 jrk S6\!\h\4   S2\hS7\h4S8 jrl S\#\   4S9 jrm S:rn    SUS; jro            SVS< jrp S=\h4S> jrq S? rr S@ rs  SWSA jrt SB ru SXSC jrv SD rw SXSE jrx SXSF jry SG rz SH r{ SI r| SJ r} SK r~ SYSL jr SM r SYSN jr SO rg! \\4 a    SrSr GN]f = f!    SSKJr  O!   SSKJr   O= f GNi= f!   \
R                  " S"5        \R                  \R                  \R                  \R                  \R                  \R                  \R                  \R                  \R                  \Rt                  \R                  \R                  \R                  \R                  \R                  S#.rM GN"= f)Z)create_huggingface_repomerge_and_dequantize_loramerge_and_overwrite_lora    N   )get_lora_layer_modules)
_get_dtype)dtype_from_config)UNSLOTH_ENABLE_LOGGINGlogger)defaultdict)convert_moe_packed_tensorsconvert_moe_packed_tensors_cpuaG  ---
base_model: {base_model}
tags:
- text-generation-inference
- transformers
- unsloth
- {model_type}
- {extra}
license: apache-2.0
language:
- en
---

# Uploaded finetuned {method} model

- **Developed by:** {username}
- **License:** apache-2.0
- **Finetuned from model :** {base_model}

This {model_type} model was trained 2x faster with [Unsloth](https://github.com/unslothai/unsloth) and Huggingface's TRL library.

[<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)
)	get_token)PushToHubMixin)Path)UnionListOptional)PeftModelForCausalLM	PeftModelc                    / n/ nU R                  5        H  u  p4[        U[        R                  R                  5      (       aX  [        UR                  S5      (       a*  UR                  R                  b  UR                  U5        Ms  UR                  U5        M  [        U[        R                  R                  5      (       d  M  UR                  U5        M     X4$ )Nquant_state)named_modules
isinstancebnbnn
Linear4bithasattrweightr   appendtorchLinear)modelskipped_modulesquantized_modulesnamemodules        R/home/james-whalen/.local/lib/python3.13/site-packages/unsloth_zoo/saving_utils.pyfind_skipped_quantized_modulesr)   S   s    O++-fcff//00v}}m449R9R9^!((.&&t,00""4( . --    c                    [        U5      [        L d   eUR                  S5      S:w  a  [        SU S35      eSSKJnJn  Uc
  [        5       nU" US9nUR                  UUSS	9nUR                  S5      S   nU R                  R                  n	[        R                  R                  U	5      (       a[  [        R                  R                  U	5      (       a7  [!        U	5      n
U
b'  [        R                  R                  U
5      (       d  U
n	OUn	["        R%                  UU	U R                  R&                  S
SS9nU" U5      nUR)                  XSS9  U" US9nXU4$ )N/r   z.Unsloth: You are pushing to Hugging Face, but z is not a valid repo.r   )	ModelCardHfApitokenT)repo_idprivateexist_ok unsloth)username
base_model
model_typemethodextrazUnsloth Model Card)r0   commit_message)typestrcount	TypeErrorhuggingface_hubr-   r.   r   create_reposplitconfig_name_or_pathospathexistsisdirget_original_model_id
MODEL_CARDformatr8   push_to_hub)r#   r1   r2   r0   r-   r.   apirepo_urlr6   r7   original_model_idcontentcardhf_apis                 r(   r   r   a   sQ    =C }}SQH	Qfghh0}ike

C  H
 }}S!!$H ++J	ww~~j!!bggmmJ&?&?1*=(@Q1R1R*J !J \\,,   G WDW>RS5!Ff$$r*   )snapshot_downloadhf_hub_downloadHfFileSystem)	safe_open)	save_file)OrderedDict)tqdmc           	         UR                   b  UR                  c  U $ U R                  S[        R                  SS9n U R                  UR                  R                  S[        R                  SS9UR                   R                  S[        R                  SS9UR                  S9n [        R                  " [        R                  " U 5      5      R                  5       (       d  [        SU-   5      eU $ )NcudaT)dtypenon_blocking)alphaz8Unsloth: Merge failed as there are infinite elements in )lora_Alora_Btor!   float32addmm_r^   isfiniteamaxitem
ValueError)W
lora_statsr&   s      r(   _merge_lorarj      s     J$5$5$=ax	VU]]4@A	VU]]4PVU]]4P   	 	A
 >>%**Q-(--//SVZZ[[Hr*   r'   returnc                 &   [        U S5      (       d  g[        U S5      (       a  g[        U R                  5      R                  R	                  S5      (       a  gU R                  n[        U[        R                  R                  5      (       d!  [        U[        R                  5      (       a  ggUR                  R                  nUS;  a  g[        U SS 5      nUR                  nUR                  [        R                  " S5      R                  :H  ng)	Nr   FW_qTztorchao.)
Params4bit
Int8Paramsstatecpu)r   r<   r   
__module__
startswithr   r!   r   	ParameterTensor	__class____name__getattrdevice)r'   r   cls_namer   ry   is_cpus         r(   check_if_quantizedr|      s     68$$Uvu 	fmm		'	'	2	2:	>	> ]]Ffehh0011fell++ ((H33&'40K]]F[[ELL/444Fr*   c                     UR                  5       R                  5       nU H  oBR                  U S-   U-   5        M     U$ )N.)
state_dictkeysadd)r&   r'   original_keysr   keys        r(   expand_module_keysr      s:    ##%D&&tczC'78tr*   )dequantize_module_weight)	dataclassc                       \ rS rSr% \R
                  R                  \S'   \R                  \S'   \R                  \S'   \	\S'   Sr
g)	LoraStats   r'   r_   r`   r^    N)rw   rr   __qualname____firstlineno__r!   r   Module__annotations__ru   float__static_attributes__r   r*   r(   r   r      s)    XX__\\\\Nr*   r   c                 l   [        U S5      (       a  U R                  R                  OU nUR                  5       R	                  5       n[        5       nU H  nUR                  S5      nUR                  S5      nUS:w  a  US U[        S5      -    nOUS:w  a  US U[        S5      -    nO [        UR                  S5      UR                  S5      5      nUS:w  a  US U XUR                  S5      S  -   nUR                  U5        M      U[        U5      -  n	[        U	5      S:w  a  [        S	U	 S
35      eg )Nr7   .weight.bias.lora_.base_layerr~   r   zUnsloth: Extracted keys = z do not match!)r   r7   r#   r   r   setrfindlenmaxr   RuntimeError)
r#   new_state_dictinner_modelr   all_original_keysxwhere_weight
where_biasj
differences
             r(   assert_same_keysr      s,   ,3E<,H,H%""((eK**,113Mwwy)www'
21%ClS^&C#Dq21%AjS\&A#Dq !177=#9:7"1''#,- 00Aa   	"S%88J
:!7
|>RSSr*   c                    [        5       n[        S U 5       5      n[        R                  " S 5      nSu  pVpx[	        5       n	[	        5       n
[        U 5      nUR                  5        GHB  u  pUS:X  a  M  UR                  S5      (       a3  UR                  XLS [        S5      *     l
        US-  n[        XU	5        GOUR                  S5      (       a3  UR                  XLS [        S5      *     l        US-  n[        XU	5        GO[        X5      (       aU  [        US5      (       a  UR                  S	   OUR                   nUR"                  U   XL   l        US-  n[        XU	5        GO=UR                  S
5      (       aK  XUS [        S
5      *     l        US-  nU	R)                  U5        U	R)                  US [        S
5      *  5        OU(       dm  [+        U5      (       a]  XU   l        U
R)                  US-   5        [-        USS 5      b  U
R)                  US-   5        [        XU	5        U	R)                  U5        OhSU;   a  GM  [        X[	        5       5      nU H4  nUR                  S5      (       a  M  SU;   a  U	R)                  U5        M4  M6     U	R)                  U5        GME      XVs=:X  a  Us=:X  a  U:X  d   e   eU(       a  UR/                  5       n[        R0                  " 5       nUR3                  5        H  u  nnUR                  S5      (       a  US [        S5      *  nX;   aD  XL   UUS-   '   [-        XL   R&                  SS 5      b  XL   R&                  R4                  UUS-   '   Mt  X;   a  US [        S5      *  nUU;   a  UU   nOOX;   a  M  UUU'   M     OS n U(       a  [7        U U5        UU4$ )Nc              3   *   #    U  H	  oS    v   M     g7f)r   Nr   .0r   s     r(   	<genexpr>)create_lora_statistics.<locals>.<genexpr>  s     @-?t-?s   c                      [        S S S S5      $ )Nr   )r   r   r*   r(   <lambda>(create_lora_statistics.<locals>.<lambda>  s    9T4q3Qr*   )r   r   r   r   r4   z.lora_A.defaultr   z.lora_B.defaultactive_adaptersr   r   r   biasr   r   )r   r   z.weight.z.base_layer.weight)r   tuplecollectionsr   r   find_lora_base_modelr   endswithr   r   r_   r   r`   r   r   r   active_adapterscalingr^   r'   r   r|   rx   r   rX   itemsr   r   )r#   merge_into_originalreturn_state_dictLinear_LoRA_Layerslora_weightsmodule_countlora_A_countlora_B_countscaling_countremove_keys	keep_keysr   r&   r'   r   new_keysr   old_state_dictr   param	lora_names                        r(   create_lora_statisticsr     s   
 01@-?@@**+QRL>H;L%K%I&u-K#1132:x]],--BH--L6$5 6678?ALt[9]],--BH--L6$5 6678?ALt[933 122 $33A68>8M8M '-~~n'EL$QMt[9]]=))>D2M 2234;ALOOD!OOD!53}#5"567%+=f+E+E(.%MM$*+vvt,8)--w:Wt[9OOD!x *$>H||$899!S(#,    OOD!] 4^ 	H<H=HIHIH $//1$002
)//1KD%}}1227c"6778#1=1C
4)+,<-44fdCO1=1C1J1J1O1OJtg~." !13y>/2	,(3E $h$Jt) 2* 	
*5*=##r*   zSUnsloth: `safetensors.torch._TYPES` does not exist. Will set to our default version)F64F32F16BF16I64I32I16I8U8BOOLF8_E4M3F8_E5M2U64U32U16c           
      N   U(       a;  US:X  a5  US:w  a/  [         (       a  [        R                  " S5        [        XX#XEU5      $  [        R
                  R                  X5      nSn	[        U/ US9n
S nS nS nSn [        US5      n[        R                  " UR                  5       S[        R                  S9n[        R                  UR                  S5      S5      n[        R                   " UR                  U5      5      nUR#                  S5        [%        US	S
S9 n['        UR)                  5       5      n[        UUUS9n
[+        5       nU GH  nUU;   a  M  [,        R.                  R1                  5       (       a<  [,        R.                  R3                  5         [,        R.                  R5                  5         U=(       a    US:H  =(       a    US:H  nU(       aR  UR7                  S5      (       d  UR7                  S5      (       a&  [         (       a  [        R                  " SU 35        M   UnSnUR9                  U5      nUR:                  nUc  GM  UR7                  S5      (       a  US [=        S5      *  OUnU
R?                  US 5      nUb0  [A        US5      (       a  URB                  b  [E        UUU5      nU	S-  n	[G        XUUUU5      nU(       d  [I        S5      eA[,        R.                  R3                  5         GM      S S S 5         URK                  5         URM                  5         URM                  5         [,        R.                  R1                  5       (       a  [,        R.                  R3                  5         U	Ub   URM                  5         Ub   URM                  5         $ $ ! , (       d  f       N= f!    N+= f!    $ = f! [N         a  n[I        SU 35      eS nAff = f! Ub   URM                  5         O!    O= fUb   URM                  5         f !    f = ff = f)Nmxfp4z\mxfp4 quantized model detected. Using safe rewrite strategy (requires temporary disk space).r   model_class_namezr+b)lengthaccess   littleptrq   	frameworkry   _blocks_scalesz![DEBUG] Preserving MXFP4 tensor: Fr   r_   r   z%Failed to write tensor to model file.zModel merge failed with error: )(r
   r   info_merge_and_overwrite_lora_mxfp4rE   rF   join'_convert_lora_keys_to_safetensor_formatopenmmapfilenoACCESS_WRITEint
from_bytesreadjsonloadsseekrV   listr   r   r!   r[   is_availableempty_cachesynchronizer   
get_tensorr\   r   getr   r_   rj   _write_tensor_direct_torchr   flushclose	Exception)save_directoryfilenamer   output_dtyper   base_model_is_quantized
quant_typesave_methodfilename_originalr>   converted_lora_weightsraw_pointermmheader_metadatalength_of_headerfilesafetensor_keysprocessed_mxfp4_keysr   is_save_mxfp4
output_keyaction_loggedrh   W_original_dtypelora_keyri   successes                               r(   _merge_and_overwrite_lorar    s    :#8[G=S!!KKvw /lz
 	
 	^>E E
+ K	BOZ,e4YY{))+a$BSBST >>"''!*h?**RWW-=%>?

(dUKt"499;/O &M#3&" $'5 &.. ::**,,JJ**,JJ**, 7 lJ'<Q lVaelVl cll9&=&=iAXAX .-&Gu$MN 
 %OOC(#$77 9 <F;N;Ny;Y;Y:&6I7_i377$G
)gj(.K.KPZPaPaPm#Az:>AQJE 5RJZ\fhik{|&)NPP

&&(W 'X q Lt 	



::""$$JJ""$ >
 "!!# #Y LKT  B<QC@AAB
 >
"!!#	 #s   9B$O
 G(N+A;O
 N<O+
N95O
 <O O

O'O""O''O* *P$/P ?P$ PP$PP$P P$c           
      0   [         R                  R                  X5      n[        5       nSn	SS Kn
SS KnSn[        U/ US9n[        USSS9 n[        UR                  5       5      n[        UUUS9n[        5       nU GH  nUU;   a  M  [        R                  R                  5       (       a<  [        R                  R                  5         [        R                  R                  5         S nUnSnUR!                  S5      (       GaD  ["        c  [%        S	5      eUS ['        S5      *  nUS
-   nUnUU;  a  [(        R*                  " SU SU S35        M  UR-                  U5      UR-                  U5      nn[        R                  R                  5       (       a<  [        R                  R                  5         [        R                  R                  5         [/        UU5      u  nnnUS:X  aW   SSKJn  U" UUUS9R5                  SS5      R7                  5       n[8        (       a  [:        R<                  " SU SUS S35        OR[#        UUUS9R5                  SS5      R7                  5       n[8        (       a  [:        R<                  " SU SUS S35        UR?                  U5        UR?                  U5        URA                  US 5      nU(       aU  [C        US5      (       aD  URD                  b7  [8        (       a  [:        R<                  " SU 35        U	S-  n	[G        UUU5      nO$[8        (       a  [:        R<                  " SU 35        SnO*UR!                  S
5      (       a  GM  UR-                  U5      nUR!                  S5      (       a  US ['        S5      *  OUnURA                  US 5      nUb<  Ub9  [C        US5      (       a(  URD                  b  U(       d  U	S-  n	[G        UUU5      nSnUc  GMt  [H        RJ                  " SSS9 nURL                  n [        RN                  " URQ                  U5      U XRR                  S9  A[        RT                  " U SSSS9nS S S 5         [         RV                  " W 5        WUU'   [        R                  R                  5         GM"     S S S 5        [         RL                  S :X  a+  [Z        R\                  " 5         [^        R`                  " S!5        [H        RJ                  " S"U SS#9 n!U!RL                  n"S S S 5        [c        UW"S$S0S%9   [         Rd                  " U"U5        U	$ ! [$         a-    [#        UUUS9R5                  SS5      R7                  5       n GNf = f! , (       d  f       GN!= f! [X         a     GNf = f! , (       d  f       N= f! , (       d  f       N= f! [X         a  n#[g        S&U# S'35        SS K4n$[         RL                  S :X  aj  [k        S(5       HZ  n% U$Rl                  " U"U5          OY! [n         a6    U%S:X  a  e [^        R`                  " S)5        [Z        R\                  " 5          MX  f = f   OU$Rl                  " U"U5         [         RV                  " U"5         S n#A#U	$ !     S n#A#U	$ = fS n#A#ff = f)*Nr   i  +r   r   rq   r   Fr   zYMXFP4 dequantization is required, but `convert_moe_packed_tensors` could not be imported.r   zFound mxfp4 tensor z but missing its scales tensor z. Skipping.)r   )rows_per_chunkr      z%[DEBUG] Using CPU dequantization for  with ,z rows per chunkz%[DEBUG] Using GPU dequantization for r_   z:[DEBUG] DEQUANTIZING MXFP4 & MERGING LoRA into Key Group: z&[DEBUG] DEQUANTIZING MXFP4 Key Group: Tr   z.pt)suffixdelete)pickle_modulepickle_protocol)map_locationr   weights_onlyntg?.safetensors)r  dirr  rK   metadatazError renaming temporary file: z. Attempting copy and replace.   g      ?)8rE   rF   r   rX   psutilpickler   rV   r   r   r   r!   r[   r   r   r   r   r   ImportErrorr   warningswarnr   !_choose_mxfp4_processing_strategytransformers.integrations.mxfp4r   	transpose
contiguousr
   r   r   r   r   r   r_   rj   tempfileNamedTemporaryFiler&   savera   HIGHEST_PROTOCOLloadremoveOSErrorgccollecttimesleeprW   replaceprintshutilrangecopy2PermissionError)&r   r   r   r   r   r   r   r   tensorsr>   r"  r#  limitr  r  r  r  r   rh   r
  r  	base_name
scales_keyblocks_tensorscales_tensordevice_type	device_idr  r   ri   r  	temp_filetemp_filenametmpfiletemp_filename_safetensorsr  r8  attempts&                                         r(   r   r     s    ^>mGEE E
+ 
$$	G4tyy{+ "I/"
  #u"C** zz&&((

&&(

&&(AJ!M ||I&&-5%  'B  C  C 0#i.1	&2
&
_4MM$7u<[\f[ggr"st/3s/CT__U_E`}::**,,JJ**,JJ**, :[!=:6Y
 %'7b:)=#)Aq/**,  21"KK*OPY{Z`aopq`r  sB  )C  D 3%}^i1ojjl  .-&KI;V\]klm\nn}$~$((-/C/G/G
/S377	4H
'*h"?"?JDUDUDa--&`aj`k$lmQJEK:z$J--&LYK$XY $i((
 OOC( 8B7J7J97U7Uz"2C	N?3[eH/33HdCJ}!7GJPX<Y<Y^h^o^o^{$QJE#Az:>A$(My,,E%HI )

144-}Fd{d{|JJ}5tZ_` I		-(
 #$GJ JJ""$a # 
H@ 
ww$




3 
	$	$NW\	]ah$+LL! 
^ g0Hd;KL


,.?@6 LW ' 76)=#)Aq/**, 7^ IH  m 
H	GJ 
^	]  /s2PQR 77d? 8!LL!:<MN& !!|JJsOJJL	!	 $ LL24EF	II/00 L	L5s   FV*AT:?GVAU4V#V9(V>V(!V9 :3U1-V0U11V4
V>V
VVVV
V%(
V69
Z5Z9XZ<Y
ZYZ(ZZZZZ)$split_state_dict_into_shards_factoryget_torch_storage_sizeget_torch_storage_idc                     [        U [        5      (       aN  U R                  R                  U R                  R                  4n[        [        R                  " U5      5      U-  $ [        U 5      $ N)	r   r   r'   in_featuresout_featuresr   npprodrJ  )r   element_sizeshapes      r(   get_torch_storage_size_newrT    sP    !Y%%qxx'<'<=2775>"\11%a((r*   c                 D    [        U [        5      (       a  g [        U 5      $ rM  )r   r   rK  r   s    r(   get_torch_storage_id_newrW    s    !Y#A&&r*   c                   ^ SSK Jn  Un[        U5      [        La  U" U5      n S nSu  pnU(       aj  Uc
  [	        5       n[        U UUUS9u  pn[        R                  R                  U5      (       d  U
(       a"  [        R                  " SS9nUR                  nSn
  Uc  [        [        U R                  5      5      nU[        R                   [        R"                  [        R$                  [        R&                  4;   d   e[        [        R&                  5      [        R(                  L d   e[        R*                  " / US9R-                  5       m[/        U USS9u  nn[1        U4S	 jUR3                  5        5       5      n[        R                  R5                  U5      (       d   [        R6                  " USS
9   [>        R@                  " U5      u  nnn[        US-  5      nS n UU:  a  U
(       a=  U(       a  UU	:  a  SnO-U" 5         O%US:  a  U(       a  SnUnOU" 5         O[;        S5      e [        R                  " SS9nUR                  n[>        R@                  " U5      u  nnn[        US-  5      nU(       d  UU:  a  U" 5         O@U(       a  UU:  a  [;        S5      eU(       a  [C        SU S35        UnUnSn
O[;        S5      e  XUUUTUUUUXU
X4$ ! [8         a  n[;        SU S[=        U5       35      eS nAff = f)Nr   )parse_size_to_int)NNN)r#   r1   r2   r0   T)ignore_cleanup_errors)r\   )r   r   c              3   <   >#    U  H  n[        UT5      v   M     g 7frM  )rT  )r   r   rR  s     r(   r   !prepare_saving.<locals>.<genexpr>  s     ]I\A.q,??I\s   r3   z"Unsloth: Error creating directory z with error = gffffff?c                      [        S5      e)NzjUnsloth: Failed saving locally - no disk space left. Uploading can work luckily! Use .push_to_hub instead.)r   r   r*   r(   raise_upload_works*prepare_saving.<locals>.raise_upload_works&  s    D
 	
r*    z#Failed saving - no disk space left!z/Unsloth: Failed uploading - no disk space left.zUnsloth: Saving to zU will fail, but using a temp folder works! Switching to a temp folder then uploading!)"#huggingface_hub.serialization._baserY  r<   r   r   r   rE   rF   rH   r+  TemporaryDirectoryr&   r   r	   rC   r!   rb   float16float64bfloat16r\   tensorrR  r   sumvaluesrG   makedirsr   r   r=   r8  
disk_usager7  )r#   r   rL   max_shard_sizer2   r0   r   r   low_disk_space_usagemin_size_in_bytesuse_temp_filerY  max_shard_size_in_bytesrD  r6   r1   rR   r   r   	save_sizeerrortotalusedfreer_  try_temp_filetry_save_directoryrR  s                              @r(   prepare_savingrx    s    F,#$C/"3N"CI 0Hv=)+%$;$	%
!6 77==((M 33DQI&^^N MJ7H7V,W\EMM5==%--XXYX5;;./.<<L9FFHL  61  L* ]IZIZI\]]I 77>>.))	pKK48 	 )).9E4tDy>D
 	i"+++/((*#+/(.2+(*"#HII !33DQ*//"--.@AtT49~ti/1C1ETI-PQQ%n%5 6= =
 &I/N MDEE 	65lj)T= s  	p!CNCSSabefkblamnoo	ps   (K" "
L,LLconfig_pathc                 <   U R                  5       (       d   S5       e[        U SSS9 n[        R                  " U5      nS S S 5        SW;   a  US	 Og [        U SSS9 n[        R                  " X!SS9  S S S 5        g ! , (       d  f       NC= f! , (       d  f       g = f)	NzGiven config does not existrutf-8encodingquantization_configw   indent)rG   r   r   r/  dump)ry  frC   s      r(   _remove_quantization_configr  a  s    >!>>	k37	3q1 
4&()	k37	3q		&a( 
4 
4	3 
4	3s   A<B<
B

Bc                    [         R                  R                  US5      n[         R                  R                  U5      (       a  U b  [	        U SS 5      nUbp   [        USSS9 n[        R                  " U5      nS S S 5        SW;  d  US   c  U R                  US'   [        USSS9 n[        R                  " XESSS	9  S S S 5          [        USSS9 n[        R                  " U5      nS S S 5        SW;   a  US   S
:X  d  US   c  US	 [        USSS9 n[        R                  " XESSS	9  S S S 5         [         R                  R                  US5      n[         R                  R                  U5      (       ao   [        USSS9 nUR                  5       nS S S 5        WR                  SS5      nUR                  SS5      n[        USSS9 nUR                  U5        S S S 5        g g ! , (       d  f       GNw= f! , (       d  f       GND= f!    GNL= f! , (       d  f       GN2= f! , (       d  f       GN= f!    GN
= f! , (       d  f       N= f! , (       d  f       g = f!    g = f)Nztokenizer_config.jsonchat_templater{  r|  r}  r  r  F)r  ensure_asciir4   config.jsonz"dtype"z"torch_dtype"z'dtype'z'torch_dtype')rE   rF   r   rG   rx   r   r   r/  r  r  r   r6  write)	tokenizersaved_foldertokenizer_config_pathold_chat_templater  new_fconfig_file_pathdatas           r(   fix_tokenizer_config_jsonr  p  s   GGLL7NO	ww~~+,,1F#IE(/wG1		!A H"!+q/A/I)2)@)@Ao&/wG5IIa5I H 		+S7CqIIaL D!#?);r)AQEWE_o&+S7Cu		!QuE D 	ww||L-@	ww~~&''	&g>!vvx ?<<	?;D<<	?;D&g>! ? C HG HG
 DC DC	 ?> ?> 	
s   H $G+;.H )G= H 
H; H,+H; H).H; <I% I7I% I!I% +
G:5H =
HH H H
H&!H; )
H83H; 8H; ;I 
II% 
I"I% "I% %I)	filenamesc                    [         R                  " S5      nU  Vs/ s H  o!R                  U5      PM     nn[        U5      (       d  gU Vs/ s H4  oDR	                  S5      UR	                  S5      UR	                  S5      4PM6     nn[        U6 u  pgn[        [        U5      5      S:H  =(       a    [        [        U5      5      S:H  $ s  snf s  snf )zMCheck if filenames follow HF sharded naming: model-00001-of-00005.safetensorsz#^(.+?)-(\d+)-of-(\d+)\.safetensors$Fr   r  r!  )recompilematchallgroupzipr   r   )	r  patternr  matchesmparsedprefixes_totalss	            r(   is_hf_sharded_safetensorsr    s    jj?@G)23A}}QG3w<< =DDGqwwqz1771:qwwqz2GFD v,Hs8}"<s3v;'71'<< 4
 Es   C	;Cc                 N  ^^I^J [        U[        5      (       a  UR                  R                  OUn[	        US5      (       a  UR                  OUn/ nSnSnUR
                  n[        S5       GH  n[        U[        5      (       d  [        R                  " S5          g US:X  a   U " UR
                  R                  SS9n  [        WU5      u  nnnnnU(       a*  US:X  d  US:X  a  US	:X  a  [        R                  " S
5          g Uc  [        R                  " SU S35          g UnSn[        R                  R                  U5      (       Ga  [        R                  R                  U5      (       Gab  Sn[        SU 35        [        R                   " U5       H|  nUR#                  S5      (       d  M  UR%                  U5        [        R                  R'                  UU5      n[        R                  R)                  U5      n[+        UU5      nUU-  nM~     [        R                  R'                  US5      n[        R                  R                  U5      (       a   [-        USSS9 n[.        R0                  " U5      nSU;   a  [3        US   R5                  5       5      nU(       d  [7        U5      nU Hy  n[        R                  R'                  UU5      n[        R                  R                  U5      (       d  MI  [        R                  R)                  U5      n[+        UU5      nUU-  nM{     S S S 5        [        R                  R'                  US5      n [        R                  R                  U 5      (       aU  [        R:                  " TSS9  [<        R>                  " U [        R                  R'                  TS5      5        [        S5        O [A        US9RC                  USS9n!U! Hi  n#U#S   R#                  S5      (       d  M  UR%                  [        R                  RI                  U#S   5      S   5        [+        UU#S   5      nUU#S   -  nMk     U(       d  [K        S U 35      eUS:w  a  US:w  d   e[M        UTUS!UUUU	SUU
S"9u  n$mJmInnn%n&n'n(n)n*mn+n	n,U
=(       d    U+n
[O        T5      n-S#R'                  U&RQ                  5       5      n.U.RS                  S$5      U.RS                  S#5      S%-   :H  n/U/(       aK  US&:X  aE  UR#                  S'5      (       a/   U " URU                  S'5      SS9n[        S(U S)35        / nSnSnGM     O    Sn0SdUIUJU4S* jjn1 Ub  URW                  TS+9  [Y        UT5        US,:X  d  US-:X  Ga  [        U[        5      (       a  UR                  OUn2[        S.5        [        U[Z        5      (       d   [        U[        5      (       d  []        S/5      e[_        UR
                  S0S 5      (       d  [G        S15      e U2Ra                  5       n3[        S25        [c        U35      u  n4n5[e        U45      S:  aT  [        S4U4 S535        [	        U3R
                  S05      (       d  0 U3R
                  l3        U4U3R
                  Rf                  S6'   [        S7T S835         U3RW                  TS+9  [        S95        [Y        UT5        U(       a  U1" 5         U(       a  W*b  [        S;5        U*Ri                  5         [        S=5        T$  US	:X  a'  URW                  T5        [k        [O        T5      S>-  S?9  O.US&:X  a(  SS@K6J7n6  U6Rq                  WS SSA9n7U7RW                  T5        [Y        UT5        U(       a  U1" 5         SS K9n8SB[u        [v        Rx                  R{                  S5      5      ;   n9US	:X  a  [}        U9UU5      OSn:[        5       n;Sn<Sn=[        U5      n>[e        U5      S%:  d  U>(       a  S/O/ n?W(       a  WS&:X  a  U(       a  US&:X  a  US&:X  a  U:(       d  W(       a  [        R:                  " TSS9  U?(       a{  [        R                  R'                  WS5      n@[        R                  R                  U@5      (       a7   [<        R>                  " W@[        R                  R'                  TS5      5        O%O$SU? Vs/ s H  nUPM     sn;   a  [        WTS/SSD9  U(       a  U?(       a  U1" S5          W(       d  U;b  [        WUTU;USE9n<[        US/TU;USE9n=U<(       d,  U	(       d%  U(       d  [        SFW S835        [        UTU?U-   SSD9  U=(       d*  U	(       d#  U(       d  [        SGW S835        [        UTS/SSD9  / nA[        USHSI9 GH'  nB[        R                  R'                  TUB5      nU(       a  [        R                  R                  U5      (       dk  [        R                  R'                  WWB5      nC[        R                  R                  UC5      (       a&  [<        R>                  " WCU5        [        SJWB SK35        OEU<(       d>  U	(       a7  [        R                  R                  U5      (       d  U(       d  [        WWBSLTSM9   U:(       a  [        WBTSNSO9nDOWB/nDWAR                  WD5        GM*      U	(       ak  U(       dd  U<(       d]  [        R                  R'                  TS5      n [        R                  R                  U 5      (       d   [        WSSLTUSP9  [        SQ5        U:(       a  [        WAT5      nA[        WA5      nEU=(       a    WS&:H  =(       d    U:=(       a#    [e        WA5      S%:  =(       d    WE=(       a    US&:g  nF0 nG[        WASSUS&:X  a  S&OST 3SI9 H  nBU0[        TUBW&U[        U5      R                  R                  UWUSU9-  n0[v        Rx                  R                  5         [        R                  R'                  TUB5      nWF(       a0  [        USVSWSX9 nURQ                  5        H  nHWBWGUH'   M
     S S S 5        U	(       aC  U(       a<  U1" WB5        [        R                  " [        R                  R'                  TUB5      5        M      WF(       ai  [        SY5        0 WGSZ.n[        R                  R'                  TS5      n[-        US[SS9 n[.        R                  " UUS\S]9  S S S 5        U(       a  U1" S5        U	(       d  U(       a  U H  nBU1" UB5        M     U1" 5         [e        W&5      U0:w  a  [K        S^[e        U&5       S_U0 S`35      e W*b  U*Ri                  5          U(       a;  [        R                  R                  T5      (       a   [<        R                  " T5         [        Sc[        R                  R                  T5       S)35        T$ !   UR
                  R                  n GNK= f! , (       d  f       G
N= f! [8         a  n[        SU 35         S nAGNS nAff = f!   [E        U5      n"U"nU"c  [G        SU S35      e[A        US9RC                  USS9n! G
N= f!    G	N;= f! [8         a  n[K        S3U 35      eS nAff = f! [8         a  n[K        S:U 35      eS nAff = f! [8         a  n[        S<U 35         S nAGNS nAff = f! [<        R                   a     GN[8         a  n[        SCU 35        UeS nAff = fs  snf ! [8         a  n[        SR5         S nAGNS nAff = f! , (       d  f       GN= f! , (       d  f       GNh= f!    GN= f! [8         a  n[        SaT SbU 35         S nAGNS nAff = f)eNr7   r   r  z|Model is not a PeftModel (no Lora adapters detected). Skipping Merge. Please use save_pretrained() or push_to_hub() instead!F)load_in_4bitnf4fp4merged_16bitzwBase model should be a 16bits or mxfp4 base model for a 16bit model merge. Use `save_method=forced_merged_4bit` insteadzModel z$ not found locally or on HuggingFaceTz Detected local model directory: r  zmodel.safetensors.index.jsonr{  r|  r}  
weight_mapz'Warning: Could not process index file: ztokenizer.modelr]  z1Copied tokenizer.model from local model directoryr/   detailz+Could not determine original model ID from zP. If using a local model, ensure the path exists and contains safetensors files.r&   r   sizez2No '.safetensors' files found for the base model: 5GBr#   r   rL   rl  r2   r0   r   rm  r   rn  ro  
	self_attnr   r   z-BF16z Unsloth: Found MXFP4 variant = ``c                    > TSSS.nU c  TR                   " SST0UD6  g TR                  " S[        R                  R	                  TU 5      U S.UD6  g )Nr#   z(Trained with Unsloth))r1   	repo_typer;   folder_path)path_or_fileobjpath_in_repor   )upload_folderupload_filerE   rF   r   )r   extrasrR   r1   r   s     r(   upload_items.merge_and_overwrite_lora.<locals>.upload_itemsK  sj    %WQil  I~II 	  "$'',,~x"H' 
 	r*   r   merged_4bitforced_merged_4bitz0Unsloth: Merging LoRA weights into 4bit model...zIModel must be a PeftModelForCausalLM or PeftModel for 'merged_4bit' save.r  z@Model does not appear to be quantized. Cannot use 'merged_4bit'.zUnsloth: Merging finished.z-Failed to merge LoRA weights for 4-bit save: z Unsloth: Found skipped modules: z. Updating config.llm_int8_skip_modulesz%Unsloth: Saving merged 4bit model to z...z!Unsloth: Merged 4bit model saved.z#Failed to save merged 4-bit model: z&Unsloth: Cleaning up temporary file...z&Warning: Failed to cleanup temp file: z-Unsloth: Merged 4bit model process completed.r  )ry  )
AutoConfig)r0   trust_remote_codezTesla T4z,Error copying model.safetensors.index.json: )r1   	local_dirallow_patternslocal_dir_use_symlinks)r1   filenames_to_checktarget_dir_strhf_cache_dirr0   zDownloading safetensors for z+Attempting to download tokenizer.model for z)Unsloth: Preparing safetensor model filesdesczCopied z from local model directoryr#   )r1   r   r  r  g      ?)max_shard_size_gb)r1   r   r  r  r0   zDownloaded tokenizer.modelzINote: tokenizer.model not found (this is OK for non-SentencePiece models)zUnsloth: Merging weights into 16bit)r   r   r   r   r   r   r   r   r   rq   r   zFUnsloth: Regenerating safetensors index for dequantized MXFP4 model...)r   r  r  r  r  z8Unsloth: Saving LoRA finetune failed since # of LoRAs = z% does not match # of saved modules = z. Please file a bug report!z.Warning: Failed to remove temporary directory : z+Unsloth: Merge process complete. Saved to `rM  )Sr   r   r7   r#   r   rC   r9  r%  r&  rD   determine_base_model_sourcerE   rF   rG   rH   r7  listdirr   r    r   getsizer   r   r   r/  r   ri  r   r   rj  r8  r:  rU   lsrI   rg   rB   r   rx  r   r   r>   removesuffixsave_pretrainedr  r   r?   rx   merge_and_unloadr)   r   r  cleanupr  transformersr  from_pretrained
subprocessr=   r!   r[   get_device_nameshould_split_shards_get_hf_cache_dirr  SameFileErrorrS   _try_copy_all_from_cacheProgressBarrT   split_safetensor_fileextendrenumber_safetensor_filesr  r   rv   rw   r   rV   r0  r  rmtreeabspath)Kget_model_namer#   r  r   rL   r2   r0   r   r   rm  ro  cleanup_temp_filer   safetensors_listmax_size_in_bytestotal_size_in_bytesrC   loop_iteration
model_namefinal_model_nameis_local_pathsource_infor   r   r  	file_path	file_size
index_pathr  
index_dataindexed_filesr  tokenizer_model_path	file_listrO   r   r6   rR  r   r   rq  ru  rD  new_use_temp_filerp  _save_dir_pathall_lora_keysonly_attention_lorasn_saved_modulesr  r7   merged_modelr$   r  r  model_configr  is_t4needs_splitting_hf_cache_dircopied_all_from_cache!copied_tokenizer_model_from_cacheis_hf_shardedsafe_tensor_index_fileslocal_index_pathfinal_safetensors_listr   local_file_pathresulting_files!is_final_safetensors_list_shardedregenerate_indexr  r   rR   r1   sK      `                                                                     @@r(   r   r     s   " -7ui,H,H%""((eK,3E<,H,H+((kK\\F(%++MM  Y  ZQ8+ELL,F,FW\]
 \w  yC  EJ  ]KY-6Mz"
e(;zU?RXcguXuMM  T  U#MMF:,.RST%
 77>>*%%"''--
*C*C M4ZLAB 

:.==00$++D1 "Z >I "	 :I(+,=y(I%'94' / j2PQJww~~j))Ij#'Ba%)YYq\
':5,/
<0H0O0O0Q,RM#3373F 0,<D02Z0NI')ww~~i'@'@46GGOOI4N	<?@QS\<](9(;y(H(; -= C$ $&77<<
<M#N ww~~233NT:1277<<Pa3bcIKV(7:::PT:U	 y)).998 ''ai(@(DE$'(91V9$E!#qy0#	   "TU_T` abb A%*=*BCB +%"'#7"& 1)
	
gvu,*i~'8 "9 &:):n- 		,"3"3"56,22;?MDWDWX\D]`aDabK7$:z?R?RSZ?[?[	+J,C,CG,L]bc
8AFG#% $%!&'# 	A #B 	O
 
 	 !!>!B!)^< m#{6J'J)3E9)E)EU%%5
@B%!566z%QZ?[?[hiiu||%:DAA`aa	T%668L.0
 <LI!#4_4EEWXY<..0EFF:<##7O^L334KL5n5ESIJ	K((.(I57 	")^< N !6:;""$ 	=> n$~.#$~2F2VW		+!11 % 2 

 	$$^4
 i8 #ejj88;<<ENY]kNk)%9IJqvO%'M!(-%-.>?MCFGWCX[\C\`m=>tv %w)>D[`jnu`u  {F  JQ  {Q  \kKK48&#%77<<
<Z#[ 77>>"233 %5rww||NTr7st .=T1U=T!=T1UU!( .&D%E-2	 278 ]6 8 !1+(!
 -E 12)&-
) !)=m,ZL<= &47GG%*		
 -5IR_;J<sKL &/0%*		
     09deGGLL:	 	!:!: ggll:x@Oww~~o.._i8z)DEF&+?W`HaHajw$##*	 	3Hn`cdO'jO 	%%o65 f6 	M:O!ww||N<MNww~~233d(0 ' .! 23
 !:;QSa!b(ABX(Y%0JZ75J^  Fehi  fA  DE  fE  fj  Ij  F  p{  F  pFJ 6?]itv}i}^e  DK  ^L  >M  N4+''3E:DDMM&=#%	
 		
 	

 GGLL:	 9$G1668C&.JsO $ H  K"IIbggll>8<=3 N4 	 VW"$J?
WW\\.2PQ
*cg6!IIj!a0 7 78  K )H" ) <O+Fs<GXFY Z33B2CC^`
 	
 	  rww~~n55	ZMM.) 		78W7XXY
Z[{8"\\77
B CB  ! ICA3GHHIV$9*$E!.
$,$'RS]R^ _u &u v v(7:::PT:U	`N  	T!NqcRSS	T   	K"EaS IJJ	K V5+QRSQT)U#V#VV^ "// $   LQCPQ 
 2Vx  daccd: HG" 764 	  	ZB>BRRTUVTWXYY	Zs!  %w0x (Bx>4x2x y +zz 3z, <{ 5{2 |*%|/ 6},}$.}6 +}> 0x
x	x x  
y*x>>y8zz	
z)z$$z),
{	6{{	
{/{**{/2|'		|'|""|'/
}9}

}
}!	$
}36};>
~$~~$r1   r  r  r  r0   c                 &   SSK Jn  U(       a  U(       d  [        S5        g[        U5      n[        S5        0 nSnU H  n	 [	        X	SS9n
[        U
5      Xy'   M     U(       d  [        S5        g [        R                  " USS9  [        R                  " U[        R                  [        R                  -  5      (       d  [        SU 35      e Sn[        UR                  5       S[        U5       SU S3S9 H  u  p [!        XU	5        M      U(       a  [        S[        U5       SU S35        g[        S5        g! U a    [        SU	 S	35        Sn   M  [         a!  n[        S
U	 SU S35        Sn SnA  GM#  SnAff = f! [         a  n[        SU SU 35         SnAgSnAff = f! ["        [        [$        4 a%  n[        SU	 SU SU SU 35        Sn SnA  M  SnAf[         a  n[        SU	 SU 35        Sn SnA  M  SnAff = f)z
Checks if ALL specified files exist in the HF cache. If yes, creates the
target_dir_str and copies ALL files into it using os functions.
Returns True if successful, False otherwise.
r   )LocalEntryNotFoundErrorz?Skipping cache check: No cache directory or no files specified.Fz.Checking cache directory for required files...T)r1   r   local_files_onlyzCache check failed: z not found in local cache.z'Cache check failed: Error checking for r  r~   NzENot all required files found in cache. Will proceed with downloading.r]  z2No write/execute permission for target directory: z?Cache copy failed: Could not create or access target directory zUnsloth: Copying z files from cache to `r  r  z!Cache copy failed: Error copying z from  to z8Cache copy failed: An unexpected error occurred copying zSuccessfully copied all zKFailed to copy one or more files from cache. Will proceed with downloading.)huggingface_hub.errorsr	  r7  r=   rT   r   r   rE   rj  r   W_OKX_OKr;  r  r   r   _copy_file_from_sourceIOErrorFileNotFoundError)r1   r  r  r  r0   r	  hf_cache_dir_strcached_paths_map	all_foundr   cached_path_str	check_errdir_err
all_copiedcached_pathcopy_errr  s                    r(   r  r  o  sW    ?1OP<(	:<I&
	-imnO)-o)>& ' UV
Nt4yy277):;;"%WXfWg#hii < J!,-=-C-C-EPabefxbyaz  {Q  R`  Qa  ab  Oc  "d	&";I "d 	(-?)@(AAWXfWgghij[\Q ' 	(
2LMNI 	;H:R	{RSTUI	  OP^O__abiajkl *;< 	'6xj{mSWXfWggijristuZ 	&LXJVXYZX[\]J	&s[   D?0AF ?F/?F	F#E??F
F,F''F,/HG$$H1HHsrc_pathr   c           	         [        U 5      n [        R                  R                  X5      nU R	                  5       (       d  [        SU  S35      e[        R                  " U [        R                  5      (       d  [        SU  35      e [        R                  " [        U 5      U5        g! [         a  n[        SU  SU SU 35      UeSnAff = f)zECopies a file from src_path to target_dir_str/filename using os.path.zSource z is not a valid file.z$No read permission for source file: zFailed to copy r  r  N)r   rE   rF   r   is_filer  r   R_OKr;  r8  r:  r=   r   r  )r  r  r   dst_pathr  s        r(   r  r    s    H~Hww||N5H'(3H IJJ99Xrww''!EhZPQ	QNS]H- NzhZr!EFAMNs    B) )
C3CCc            	      n   / n S[         R                  ;   a+  U R                  [        [         R                  S   5      5        S[         R                  ;   a.  U R                  [        [         R                  S   5      S-  5        U R                  [        R                  " 5       S-  S-  S-  5        U  H  n UR                  5       (       a  [         R                  " U[         R                  [         R                  -  [         R                  -  5      (       a.  [        SUR                  5        35        UR                  5       s  $ [        SU S35          g	UR                  5       (       a  [        S
U S35          g	M     [        S5        g	! [         a  n[        SU SU S35         S	nAM  S	nAff = f)z0Determines the Hugging Face Hub cache directory.HF_HUB_CACHEHF_HOMEhubz.cachehuggingfacez'Found HuggingFace hub cache directory: zWarning: Found cache directory z/, but lack R/W/X permissions. Cannot use cache.NzWarning: Path z1 exists but is not a directory. Cannot use cache.z.Warning: Error accessing potential cache path r  z. Checking next option.z>No existing and accessible Hugging Face cache directory found.)rE   environr    r   homeis_dirr   r  r  r  r7  resolverG   r   )potential_paths	cache_dirr  s      r(   r  r    sk   O#tBJJ~$>?@BJJtBJJy$9:UBC499;1MAEIJ$		!! 99Y"''(9BGG(CDDCIDUDUDWCXYZ$,,..;I;Fuvw!!##	{2cde $ %2 

JK  	B9+RPQsRijk	s%   7BFF$F
F4F//F4a  
PushToHubMixin._upload_modified_files(
    PushToHubMixin,
    working_dir = save_directory,
    repo_id = '{repo_id}',
    files_timestamps = files_timestamps,
    commit_message = "Upload Unsloth finetuned model",
    token = token,
    create_pr = False,
    revision = {revision},
    commit_description = "Upload Unsloth finetuned model",
)
if {use_temp_file} and temp_file is not None: temp_file.cleanup()
else:
    shutil.rmtree(save_directory)
    os.makedirs(save_directory, exist_ok = True)
if {use_temp_file}:
    temp_file = tempfile.TemporaryDirectory(ignore_cleanup_errors = True)
    save_directory = temp_file.name
files_timestamps = PushToHubMixin._get_files_timestamps(PushToHubMixin, save_directory)
c                 h   [         R                  " SU 5      nUc   eUR                  S5      nU S US   S-
   S-   XS   S  -   n  SU ;  a  [        S5      e[         R                  " SU [         R                  [         R
                  -  S9nUc   eUR                  S5      nU [        US   US   S	-
  5      US   S-
   n[         R                  " S
US S S2   5      R                  S5      S   nXS   US   U-
  S-
   n[        [         R                  " SU5      S   5      n	UR                  S5      S-   n
UR                  5       nU(       aa  US U
 XzS  -   SU	-  -   [         R                  " SS[        R                  UUUS9R                  5       5      R                  SSSU	-  -   5      -   nOUn US-   SU	-  -   S-   SU	S-   -  -   S-   nU(       a4  US-   SU	S-
  -  -   SU S3-   SU	-  -   S-   SU	-  -   S-   SU	-  -   SU S3-   n U R                  X{5      n U(       d  U R                  SSS5      n  U $ )Nz!os\.makedirs\(save_directory.+?\nr   r   zS; files_timestamps = self._get_files_timestamps(save_directory); temp_file = None;
z.for shard_file, tensors in filename_to_tensorszHUnsloth: Failed to find `for shard_file, tensors in filename_to_tensors`zPfor shard_file, tensors in filename_to_tensors\:.*?[\n]{1,}[ ]{4}[a-zA-Z0-9\_\#])flagsr   z[\n]{1,}r   z\n([ ]{4,})r   z[ ]{8,}r4   )r1   revisionro  zfor tensor in shard:
r  z4if tensor in DEQUANTIZED_KEYS: shard[tensor] = None
zif z:
zFtemp_file = tempfile.TemporaryDirectory(ignore_cleanup_errors = True)
z save_directory = temp_file.name
zrepo_id = 'z'
zfor shard_file, tensors in ProgressBar(filename_to_tensors, desc = 'Unsloth: Saving ' + str(len(filename_to_tensors)) + ' safetensor(s)'))r  searchspanr   DOTALL	MULTILINEr   r   findallfindrstripsub_PUSHING_CODErK   r6  )r  rm  ro  r1   r.  makedirr0  for_loopwherespacesfirst_newlinenew_for_loops               r(   incremental_save_pretrainedr>    s    ii<oNG<<?D%jtAwqy1^_Q!"O 	 8Neffyy	,		BLL(	H  ==Ds47DGAI6aCHIIk8DbD>277:1=EAwaq9HNH5a89FMM$'!+M H/^$%J FF:r ''!("*'4 (  fh gdD3v:-.	/  F
 	!! 	VAX	
 	@@L #N -$% L	
 VV L 00 L '#&	' 	%--hEO)11< X

 	r*   c                 H  ^! [        U [        5      (       a  U R                  R                  OU n[	        U S5      (       a  UR                  OUn[        U UUUUUU	U
SSUS9u  pnnn	nnnnnnp+n
nSS Kn[        R                  " UR                  R                  R                  5      nUR                  S5      m!UR                  S5      nSR                  U!4S jU 5       5      nU(       a  [        UU
UUUS	9n [!        UR                  5      n[#        S
SR                  U5       S3[%        5       ['        5       5        S[)        U	5       SU SU S3nUR                  S5      nUS:X  a  [+        S5      eUR                  SU5      S-   nUS U U-   UUS  -   nSU;  a  [+        S5      eUR-                  SSS5      nSU;  a  [+        S5      eUR-                  SSS5      n0 n[#        U['        5       U5        US   n[.        R0                  " U5      n[2        R4                  " [2        U5      nU" U4USUUUUUS.UD6  Ub  UR                  US9  U(       a0  [2        R6                  " [2        UUUSUSUSS9	n [9        S U 35        U $  Ub  UR;                  5         g g !    g = f)!Nr7   Fra  r  r   defr  c              3   ,   >#    U  H	  oTS  v   M     g 7frM  r   )r   r   r;  s     r(   r   ,merge_and_dequantize_lora.<locals>.<genexpr>  s     DOq&'
Os   )r  rm  ro  r1   r.  z)from transformers.modeling_utils import (z, )a:  
    DEQUANTIZED_KEYS = []

    def merge_lora_weights(state_dict, name):
        x = state_dict[name]
        if type(x) is LoraStats:
            DEQUANTIZED_KEYS.append(name)
            W = dequantize_module_weight(x.module)
            W = _merge_lora(W, x, name)
            x = W.to(device = 'cpu', dtype = z, non_blocking = True)
        # Remove memory leak
        state_dict[name] = None
        return x
    pass
    state_dict_split = split_state_dict_into_shards_factory(
        state_dict,
        max_shard_size   = z,
        filename_pattern = filename_pattern,
        get_storage_size = functools.partial(get_torch_storage_size_new, element_size = zB),
        get_storage_id   = get_torch_storage_id_new,
    )
    z5state_dict_split = split_torch_state_dict_into_shardsr   z*Unsloth: Failed to find `state_dict_split`r   zstate_dict[tensor].contiguous()z9Unsloth: Failed to find `state_dict[tensor].contiguous()`z3merge_lora_weights(state_dict, tensor).contiguous()zdef save_pretrainedz-Unsloth: Failed to find `def save_pretrained`zdef save_pretrained_dequantizedsave_pretrained_dequantized)r   rL   rl  safe_serializationr0   r2   r   r  zUpload Unsloth finetuned model)working_dirr1   files_timestampsr;   r0   	create_prr.  commit_descriptionz2Unsloth: Uploaded model to https://huggingface.co/)r   r   r7   r#   r   rx  transformers.modeling_utilsinspect	getsourcemodeling_utilsPreTrainedModelr  r4  rB   r   r>  r  execlocalsglobalsr=   r   r6  r!   inference_moder   _get_files_timestamps_upload_modified_filesr7  r  )"r#   r  r   rL   rl  rE  r0   r2   r.  r   rm  ro  kwargsr   r6   r1   rR   rR  r   r   rq  ru  rD  rp  r  r  	functionsreplace_state_dictleftrightrD  rG  commitr;  s"                                    @r(   r   r   W  s1   " -7u>R,S,S%""((Y^K,3E<,H,H+((kK 	'!'#3#'%	65lj)T>5 '''(C(C(S(S(c(cdO!!%(F%++D1OiiDODDO 5-#7)
 	L//0I4TYYy5I4J!	LfhX_Xab	. /2,.?-@ A 44 5YYeXf g%,   !XYDrz&RSS  d+a/E%et,/AAOTYTZD[[O(?VWW%--)=	O O3JKK%--)	O I')Y/"+,I"J"'"6"67R"S%;;  
+"4/"$'
 
 i777Y66(/=!A

 	B7)LM  	s   J J!
local_pathc                    SS K nSS KnUR                  R                  U S5      nUR                  R	                  U5      (       a1  [        USSS9 nUR                  " U5      nS S S 5        SW;   a  US   $ UR                  R                  U S5      nUR                  R	                  U5      (       a1  [        USSS9 nUR                  " U5      nS S S 5        SW;   a  US   $ g ! , (       d  f       N= f! , (       d  f       N+= f)	Nr   r  r{  r|  r}  rD   zadapter_config.jsonbase_model_name_or_path)r   rE   rF   r   rG   r   r/  )r[  r   rE   ry  r  rC   s         r(   rI   rI     s    '',,z=9K	ww~~k""+sw71YYq\F 8
 f$/**'',,z+@AK	ww~~k""+sw71YYq\F 8 %.344! 87 87s   C$=C5$
C25
Dc                 z     [        SU /S9n[        X5      n[        US0 5      $ ! [        [        4 a    0 s $ f = f)z@Get the checkpoint conversion mapping for a specific model classr  )fromlist_checkpoint_conversion_mapping)
__import__rx   r$  AttributeError)r   r'   model_classs      r(   "_get_checkpoint_conversion_mappingrd    sJ    N6F5GHf7{$DbII( 	s   "% ::c           	      H  ^
 U(       d  gSnSnUR                  5        Vs/ s H  n[        R                  " U5      PM     nnUR                  5        Vs/ s H0  n[        R                  " S[        R                  " U5      -   5      PM2     nnU  H`  m
[        T
[        5      (       d  M  [        U
4S jU 5       5      n[        U
4S jU 5       5      n	U(       a  US-  nMR  U	(       d  M[  US-  nMb     US:  a  US:X  a  gUS:  a  US:X  a  gX2:  a  gX#:  a  ggs  snf s  snf )Nnewr   ^c              3   D   >#    U  H  oR                  T5      v   M     g 7frM  r  r   r{  r   s     r(   r   %detect_keys_format.<locals>.<genexpr>$       C0B1''#,,0B    c              3   D   >#    U  H  oR                  T5      v   M     g 7frM  ri  rj  s     r(   r   rk  %  rl  rm  r   old)r   r  r  ri  escaper   r=   any)keys_to_checkforward_mappingcount_matches_old_patterncount_matches_new_patternpold_regex_compiledvalnew_regex_compiledmatched_newmatched_oldr   s             @r(   detect_keys_formatr|    s    ! ! 2A1E1E1GH1GA"**Q-1GHGVG]G]G_`G_"**TBIIcN%:;G_`#s##X C0BCCC0BCC%*%[%*%   !1$)Ba)GPU 1$)Ba)GPU !<U <U7 I`s    D7Dc           	         SS K n[        U5      nU(       d  [        U R                  U 5      $ 0 nUR	                  5        H	  u  pgXeU'   M     Sn[        X5      n	[        U R                  5      n
SnU R	                  5        H  u  p[        U[        5      (       d  XU'   M   UnSnUS:X  ae  U	S:X  a_  UR	                  5        HJ  u  pgUR                  " SSUR                  S5      5      nUR                  " XgU5      u  nnUS:  d  MF  UnSn  OJ   OGUS:X  aA  U	S:X  a;  UR	                  5        H'  u  pgUR                  " XgU5      u  nnUS:  d  M#  UnSn  O   U(       a  US	-  nXU'   M     U
$ )
Nr   rf  Fro  z\^?([^(?]+).*z\1rg  Tr   )r  rd  r   default_factoryr   r|  r   r=   r6  lstripsubn)r   r  r   r  rs  reverse_mappingr  replacementlora_key_format_assumedshard_key_formatconverted_lora_weights_outputconversion_applied_countlora_key_module_nameri   converted_key_for_lookupapplied_conversion_for_this_keytemp_key	n_replaces                     r(   r   r   7  s   
  99IJO<77FF O / 5 5 7'.$ !8 $)/K$/0L0L$M! ,8,>,>,@(.44BL*>?#7 */'"e+0@E0I )8(=(=(?$ ff%5uk>P>PQT>UV&(gggD\&]#)q=/7,6:3 )@ %-2Be2K(7(=(=(?$&(gggD\&]#)q=/7,6:3 )@ +$)$BL&>?? -A@ )(r*   c                 ~    U n[        US5      (       a  UR                  n[        US5      (       a  UR                  nU$ )Nr7   r#   )r   r7   r#   )model_to_inspectcurrents     r(   r   r   r  s:    Gw%%$$w  --Nr*   c                 d     [        US9R                  U SS9n[        S U 5       5      $ !    g= f)z$Check if model exists on HuggingFacer/   Tr  c              3   H   #    U  H  oS    R                  S5      v   M     g7f)r&   r  N)r   r   s     r(   r   (check_hf_model_exists.<locals>.<genexpr>  s      Iy!V9%%n55ys    "F)rU   r  rq  )r  r0   r  s      r(   check_hf_model_existsr  {  s<     u-00D0I	IyIIIs   (+ /c                    S nS n/ nUR                  U 5        U" U 5      nU(       a  UR                  U5        SU ;   ay  U R                  S5      S   nUR                  U5         [        R                  " S5       H8  nUR	                  5       UR	                  5       :X  d  M'  UR                  U5          O    [        5       n/ nU H5  n	U	(       d  M  X;  d  M  UR                  U	5        UR                  U	5        M7     U H1  n	U" U	5      (       d  M  [        R                  R                  U	5      s  $    g! [
        [        4 a     Nf = f)zx
Check if model exists locally with case insensitive naming patterns.
Returns the actual path if found, None otherwise.
c                 .   [         R                  R                  U 5      (       a$  [         R                  R                  U 5      (       d  g [         R                  " U 5       H  nUR                  S5      (       d  M    g   g! [        [        4 a     gf = f)z-Check if directory contains safetensors filesFr  T)rE   rF   rG   rH   r  r   r1  r;  )	directoryr  s     r(   has_safetensors1check_local_model_exists.<locals>.has_safetensors  sp    ww~~i((i0H0H	

9-==00 . ) 		s   -B <B >B BBc                    [         R                  R                  U 5      (       a  U $ U R                  [         R                  5      nSn[        U5       GHO  u  p4US:X  a$  US:X  a  [         R                  nM$  US:X  a  SnO"UnO[         R                  R                  X$5      n[         R                  R                  U5      (       a  Mu  US:  a  [         R                  R                  U5      OSn[         R                  R                  U5      R                  5       n[         R                  R                  U5      (       d    g Sn[         R                  " U5       H:  nUR                  5       U:X  d  M  [         R                  R                  XX5      nSn  O   U(       d    gGMR     [         R                  R                  U5      (       a  U$ S$ ! [        [        4 a       gf = f)z+Find a path that matches case-insensitivelyr4   r   r~   NFT)rE   rF   rG   rB   sep	enumerater   dirnamebasenamelowerr  r1  r;  )	target_pathpartscurrent_pathipartparent_pathtarget_namefound_matchrf   s	            r(   find_case_insensitive_path<check_local_model_exists.<locals>.find_case_insensitive_path  sw   77>>+&& !!"&&) 'GAAv2:#%66LS[#&L#'L!ww||L? ww~~l++ <=q5"''//,7cK''**<8>>@K77>>+..#JJ{3Dzz|{2')ww||K'F&*	 4 # #A (J  "ww~~l;;|EE _- s   -G4,GG#"G#r,   r   r~   N)r    rB   rE   r  r  r1  r;  r   r   rF   r  )

model_pathr  r  paths_to_checkcase_insensitive_fullr  rf   seenunique_pathsrF   s
             r(   check_local_model_existsr    s5   
.Fb N *% 7zB34 j%%c*2.
 	j)	

3::<:#3#3#55"))$/ ( 5DL4D$HHTN%  4  77??4((  ! ) 		s   &9D8 #D8 6D8 8E
Ec                 d   Sn[         R                  R                  U 5      (       a  [         R                  R                  U 5      (       aq  [         R                  R	                  U S5      n[         R                  R                  U5      (       a,   [        USSS9 n[        R                  " U5      nSSS5        O;O: SSKJ	n  U" U SSUS9n[        USSS9 n[        R                  " U5      nSSS5        U(       a  S	U;   a~  US	   n[        U[        5      (       a  UR                  S
5      S:X  a  g[        U[        5      (       a9  UR                  SS5      nUR                  SS5      nU(       a  SU(       a  U4$ S4$ g! , (       d  f       N= f!    N= f! , (       d  f       N= f!    N= f)z;Check if a model is quantized (works for both HF and local)Nr  r{  r|  r}  r   )rT   )r1   r   r*  r0   r  quant_methodr   )Tr   r  Fbnb_4bit_quant_typeTbitsandbytesFN)rE   rF   rG   rH   r   r   r   r/  r@   rT   r   dictr   )	model_name_or_pathr0   rC   ry  r  rT   quant_configis_quantizedr   s	            r(   check_model_quantization_statusr    sv   F	ww~~())bggmm<N.O.Oggll#5}E77>>+&&+sw?1!YYq\F @? '	7),( 	K k39Q1 :
 '6134 lD))l.>.>~.NRY.Y" d++'++NEBL%))*?FJJjKKNKKG @? :9	sT   F F2F =F+ F.F+ 
FF F F
F($F+ (F+ +F/c                 z   [        X5      n[        U 5      nSu  pESu  pgU(       a  [        X5      u  pEU(       a  [        U5      u  pgU(       a  U(       d  USSSS4$ U(       a  U(       a  US:X  a  USSSS4$ U(       a  U(       d  U SSSS4$ U(       a  U(       a
  U SS	U 3SU4$ U(       a  U(       a
  USS
U 3SU4$ g)z
Determine the best source for base model using branched logic
Returns: (final_model_name, is_local_path, source_info, is_quantized, quant_type)
)NNTlocal_unquantizedFNr   local_mxfp4HF_unquantizedHF_local_)NFr4   FN)r  r  r  )r  r0   	hf_existsr[  hf_is_quantizedhf_quant_typelocal_is_quantizedlocal_quant_types           r(   r  r    s     &j8I)*5J &0"O+5()H)[&/Nz/Z, ,D"5udCC (-=-HD-w?? E#3UDAA _ES#8$NN (DF+;*<"=tEUVV *r*   c            
      >   0 n SSK nUR                  5       nUR                  UR                  UR                  UR
                  UR                  S.U S'   / U S'   [        R                  R                  5       (       a  [        [        R                  R                  5       5       Hv  n[        R                  R                  U5      nUS   nUS   nU S   R                  U[        R                  R                  U5      UUXV-
  US:  a
  XV-
  U-  S-  OSS.5        Mx     U $ )	z-Get current memory statistics for CPU and GPUr   N)rs  	availablert  percentru  rq   gpusr   d   )rC  r&   rs  ru  rt  r  )r"  virtual_memoryrs  r  rt  r  r!   r[   r   r9  device_countmem_get_infor    r  )statsr"  cpu_memr  gpu_memrs  ru  s          r(   get_memory_statsr  K  s   E ##%G&&??!!E%L E&Mzz  uzz..01Ajj--a0GAJE1:D&M  

2215=BQYU\U2c9A" 	 2 Lr*   c                 J    S H  nU S:  a
  U S SU 3s  $ U S-  n M     U S S3$ )z&Convert bytes to human readable format)BKBMBGBTBg      @.2fr-  z PBr   )bytes_valueunits     r(   format_bytesr  m  sD    -!#&av..v . #c""r*   c                 <    [        SUS-  5      nU S-  US-  S-  -   $ )N      ?i  @g333333?
   g?)min)speed_score
chunk_sizechunk_factors      r(   calculate_combined_scorer  v  s.    sJ*;<=L|b03666r*   c                   ^^^ SSK nU R                  Gt p4nUR                  U5      U-  mU(       a  US-  OSmU R                  5       UR                  5       S-  -   nTU-  S-  S-  nXg-   mSnSn	S n
UUU4S	 jn[	        5       n/ nUS
    Hk  nU
" US   US9nU" U5      nU(       d  M  [        UT5      T-  nTU-   n[        SU5      nUR                  SUS   UUS   U-  US   UUSUUUU-  US.5        Mm     U
" US   S   U	S9nU" U5      nU(       aQ  [        UT5      T-  nTU-   n[        SU5      nUR                  SSUUS   S   U	-  US   S   UUSUU	SUU-  US.5        U(       a  UR                  S SS9  US   n[        (       a^  [        R                  " SUS    SUS   =(       d    S SUS   S S US!   S" S#US$   S% S&[        US'   5       S([        US)   5       35        US   US   US   4$ / nUR                  SSUS   S   U	-  US   S   S*.5        US
    H%  nUR                  SUS   US   U-  US   S*.5        M'     UR                  S+ SS9  US   nUS   T-
  nUS:  a$  [        S,[        S-[        UT-  5      T5      5      nO[        S,T5      n[        R                   " S.US    SUS   =(       d    S S/US S0[        US1   5       S2[        T5       S335        US   US   U4$ )4zZ
Choose optimal device and chunk size for mxfp4 dequantization based on available memory.
r   N#   i  r  r  g      ?c                     X-  nU$ rM  r   )free_memorysafety_factorusable_from_frees      r(   calculate_safe_usable_memoryG_choose_mxfp4_processing_strategy.<locals>.calculate_safe_usable_memory  s    &6r*   c                 b   > U T-
  nUS::  a  g[        UT-  5      n[        TU5      nUS:  a  gU$ )zDCalculate the largest chunk size that fits in the safe usable memoryr   N   )r   r  )safe_usable_memorytemp_memory_budgetmax_chunk_from_memoryoptimal_chunkbase_memory_per_rowpersistent_memory
rows_totals       r(   calculate_optimal_chunk_sizeG_choose_mxfp4_processing_strategy.<locals>.calculate_optimal_chunk_size  sJ    /2CC" #$6:M$M NJ(=>4r*   r  ru  )r  r  g      @r[   rC  rs  )rB  rC  r  available_memorytotal_memoryr  needed_memoryr  efficiency_scorer  memory_utilizationcombined_scorerq   r  r  )rB  rC  r  r  r  r  r  r  r  r  fragmentation_factorr  r  c                     U S   $ )Nr  r   rV  s    r(   r   3_choose_mxfp4_processing_strategy.<locals>.<lambda>  s
    q1A/Br*   T)r   reversez[MXFP4] Selected rB  :r4   r  r  r  z  rows per chunk (safety factor: r  z.0%z, safe memory utilization: r  z.1%z
) - Need: r  z, Available: r  )rB  rC  r  total_availablec                     U S   $ )Nr  r   rV  s    r(   r   r  
	  s    +r*   r  i    zH[MXFP4] Insufficient memory for optimal processing on any device. Using z with minimal chunks (z). Available: r  z, Required: z. Processing will be slow.)mathrS  rQ  numelr  r  r  r    sortr
   r   r   r  r   r   r%  r&  )r@  rA  r  prefix_shapeGr  
input_sizeoutput_sizeGPU_SAFETY_FACTORCPU_SAFETY_FACTORr  r  r  suitable_strategiesgpur  r  temp_memorytotal_memory_neededr  cpu_safe_usable_memorycpu_chunk_sizebestfallback_optionsbest_fallbackremaining_memoryfallback_chunk_sizer  r  r  s                              @@@r(   r'  r'  }  sT     (--\a<(1,J %&!b&8$$&)<)<)>)BBJq.1$q(K"0   E V}9F+
 22DE
:j*58KKK"3k"A5c:FN&&% -",$'K2C$C #G&8!4"$.!2&9<N&N"0(  : :%L-' 22HIN.*58KK/+=1#~F"" , %e[ 9<M M!%L1"80 ..$'"58N"N,$
 	   	  %BD Q"1%!!KK#D$7#8${:K:Qr9R S-.q1 2##'#8"= >,,01E,Fs+K L'_(=>? @*40B+CDEG ]#T+%6=M8NOO  5\+.1BB <4	  V}![)V'88"6{	!
 	  6E$Q'M %[14EE!!$D#6FJ]6]2^`j(kl!$
3MM}-.ak0J0Pb/Q R  3A6 7"=1B#CDE F!"345 6#		$ -(-*DFYZZr*   c                 t    U (       d  g[        US5      (       a  UR                  R                  5       S:X  a  gg)zHDetermine if we need to split shards based on T4 and GPT-OSS conditions.Fr8   gpt_ossT)r   r8   r  )r  r  r  s      r(   r  r   	  s2    |\**""((*i7r*   c                    [         R                  R                  X5      n[         R                  R                  U5      (       d  U /$ [         R                  R	                  U5      nUS-  S-  S-  nXE::  a  U /$ [        SU  SUS-  S S35         [        X25      nSSKn[        UR                  5       5      SS	 n/ n	[        U5       H  u  pS
U SU
S S3n[         R                  R                  X5      n[        XSS0S9  U	R                  U5        [        S UR                  5        5       5      n[        (       d  Mx  [         R"                  " SU SUS-  S S35        M     [         R$                  " U5        [        (       a  [         R"                  " SU  35        U	$ ! [&         a  n[        SU  SU 35        U /s SnA$ SnAff = f)zGSplit a file if needed, using temporary names to avoid messy numbering.r  z
Splitting z (size: i   @r  z GB)...r   Nr   temp_split_r  03dr  rK   r   r  c              3   b   #    U  H%  oR                  5       UR                  5       -  v   M'     g 7frM  )r  rR  )r   rg  s     r(   r   (split_safetensor_file.<locals>.<genexpr>J	  s$     aR`\\^f.A.A.CCR`s   -/zCreated temp chunk: z GB)zRemoved original file: zError splitting r  )rE   rF   r   rG   r  r7  split_safetensors_to_shardsuuidr=   uuid4r  rW   r    rh  ri  r
   r   r   r0  r   )r   r   r  r  r  max_shard_size_bytesshardsr  	temp_basetemp_filenamesr  shardrE  temp_file_path
shard_sizer  s                   r(   r  r  ,	  s   ^6I77>>)$$z	*I,t3d:TA(z	Jxjg)>s(C7
KL,YJ 	

%bq)	!&)HA))AaWLIMWW\\.HNex6FG!!-0aRWR^R^R`aaJ%%2=/*X_J`adIeeijk * 			)!!KK1(<=  
"QC01zs&   B,F!  A F! !
G	+G>G	G	c                 Z   [        U 5      S::  a  [        U 5      S:X  a  U S   S:w  a  [        R                  R                  XS   5      n[        R                  R                  US5      n[        R                  R	                  U5      (       a>  [        R
                  " X#5        [        (       a  [        R                  " SU S    S35        S/$ U $ [        U 5      n[        U5       Vs/ s H  nSUS-   S SUS S	3PM     nn[        (       a  [        R                  " S
5        [        [        X5      5      nU H  u  p[        R                  R                  X5      n[        R                  R                  X5      n[        R                  R	                  U5      (       d  Mi  X:w  d  Mp  [        R                  R                  USU	 35      n
[        R
                  " X*5        [        R
                  " X5        [        (       d  M  [        R                  " SU SU	 35        M     U$ s  snf )z/Renumber all files with clean sequential names.r   r   zmodel.safetensorszRenamed z -> model.safetensorszmodel-05dz-of-r  zBUnsloth: Renumbering safetensor files with sequential numbering...	renaming_z -> )r   rE   rF   r   rG   renamer
   r   r   r9  r   r  )r  r   old_pathnew_pathtotal_filesr  clean_namesrename_pairsold_namenew_name	temp_paths              r(   r  r  Z	  s   
9~y>Q9Q<3F#Fww||NaLAHww||N4GHHww~~h''		(-))KK(9Q<.8M NO'(( i.KPUVaPbcPb1VAaC9DS(9FPbKcXY I34L +77<<977<<977>>(##(<^y
5KLIIIh*IIi*%%hxjXJ?@ + + ds   )H(c                    US-  S-  S-  n[        U SSS9 nUR                  5        Vs0 s H  oDUR                  U5      _M     nnSSS5        / n[        5       nSnWR	                  5        HZ  u  pIU	R                  5       U	R                  5       -  n
X-   U:  a$  U(       a  UR                  U5        [        5       nSnXU'   X-  nM\     U(       a  UR                  U5        U$ s  snf ! , (       d  f       N= f)z-Split a safetensors file into smaller shards.r  r   rq   r   Nr   )rV   r   r   rX   r   r  rR  r    )r  r  rl  r  r   all_tensorsr   current_shardcurrent_sizerg  tensor_sizes              r(   r  r  	  s    &-4t;N	9U	;q9:B#ALL--B 
< FMML"((*llnv':':'<<%6=MM-('MML#c# + m$M) C 
<	;s   C*C%C*%C**
C8c                     X1;  a  gX   nUS   u  pxUSU-   -  nUSU-   -  nX-
  n	UR                  U5      R                  5       R                  5       n
U
R                  5       R	                  5       nX:w  a+  [
        (       a  [        R                  " SU SU	 SU 35        gU
R                  [        R                  5      nSSKnUR                  5       nUR                  UR                  5       -  R                  U5      n[!        U5      XU& AAA
Ag	! ["         a1  n[
        (       a  [        R$                  " S
U SU 35         SnAgSnAff = f)zK
Write tensor directly to memory-mapped file using pure PyTorch operations
Fdata_offsetsr   zSize mismatch for z: expected z, got r   NTzDirect tensor write failed for r  )ra   r*  rq   untyped_storagenbytesr
   r   warningviewr!   uint8ctypesdata_ptrc_ubyter  from_addressbytesr   r   )r  r  r  r
  rg  r   key_metadataindex_Lindex_Rexpected_sizetensor_formattedtensor_bytestensor_viewr>  r?  	byte_datar  s                    r(   r   r   	  s]   /,&2'7 	1'''1''') "99\2==?CCE (779@@B(%%!3J<{=/Y_`l_mno '++EKK8 	'')^^k&7&7&99GGQ	 $I.7  !!KK9*RsKLs$   D BD "A0D 
E'E		Er  )FT)FNr  )	Fr  TNNFFra  F)
Nunsloth_finetuned_mergeFFNr  NFFT)TTr4   N)NrK  Fr  TNFNNFF)rN  rM  )r  )__all__r%  
peft_utilsr   utilsr   hf_utilsr	   temporary_patches.commonr
   r   r   r   r(  r   r   r$  ModuleNotFoundErrorrJ   r!   r  r   r@   r   huggingface_hub.utilshuggingface_hub.utils._tokenrJ  r   r   rE   pathlibr   typingr   r   r   r+  peftr   r   r)   r   rS   rT   rU   safetensorsrV   safetensors.torchrW   rX   rY   r  r8  r  	functoolsrj   r   r   boolr|   r   peft.utils.integrationsr   numpyrP  rK  dataclassesr   r   r   rR  r   r2  r4  r   r>  _TYPESSAFETENSORS_DTYPESr   re  rb   rd  rf  int64int32int16int8r=  float8_e4m3fnfloat8_e5m2uint64uint32uint16r  r   rI  rJ  rK  rT  rW  rx  r  r  r   r=   r  r   r  r  r  r7  r>  r   rI   rd  r|  r   r   r  r  r  r  r  r  r  r'  r  r  r  r  r   r   r*   r(   <module>ri     s  "
  .  ' D #*j  2  	)  6  	  ( (  0. 
 	.%^  
 " ' # $    
  uxx  4  L 
  =    $ !
  
 	,  _$ _$@   	     $**11(  $ C CH x xr  ) '
   #yt 	T 	 (R =c =t =(   4  )  | |z CCS	C C 4.	C
 C=C 
CH NU39%5 Ns NVY N #8D> #H  2  Pb 
  4     R	f c .  #H 
 '8)r   jV +X )*T @ # 7
 `[B 	 +X %L 4 3h gM 	() * &*%)"	*H	;3;:X	
KKef}}}}}}{{{{{{jjkk

&&$$||||||sA   J  J 7J0  JJJ-JJ-J'%J-0B<M/