
    9ih                        S SK r S SKrS SK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JrJrJrJr  S SK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Jr  S S
KJrJr  S SK J!r!  S SK"J#r#  S SK$J%r%  \#" 5       r&\" 5       r'S r(     S S\R$                  RR                  S\*S\\   S\\   S\\+   S\,S\,SS4S jjr-  S!S\S\4S jjr.  S!S jr/S\4S jr0  S!S\\*\Rb                  4   S\*S\4S jjr2g)"    N)OrderedDict)copytreeignore_patternsrmtree)CallableDictOptionalUnion)nn)	Optimizer)_LRScheduler)FileLocalStorage)ConfigJSONIteratorEncoder)ConfigFields	ModelFile)copytree_py37)
get_logger)	is_masterc                     [        5       nU R                  5        H  u  p#UR                  5       X'   M     [        U S[        5       5      Ul        U$ )zCopy a model state_dict to cpu.

Args:
    state_dict (OrderedDict): Model weights on GPU.

Returns:
    OrderedDict: Model weights on GPU.
	_metadata)r   itemscpugetattrr   )
state_dictstate_dict_cpukeyvals       [/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/modelscope/utils/checkpoint.pyweights_to_cpur!      sI     !]N$$&!ggi '  'z;NN    modelfilename	optimizerlr_schedulermeta	with_meta
with_modelreturnc                    0 nU(       d  U(       d  [        S5      eU(       Gan  Uc  0 nO,[        U[        5      (       d  [        S[	        U5       35      eSSKJn  UR                  U[        R                  " 5       S9  [        U [        R                  R                  R                  5      (       a  U R                  n [        U S5      (       a&  U R                   b  UR                  U R                   S9  XGS	'   [        U["        5      (       a  UR%                  5       US
'   OI[        U[        5      (       a4  0 US
'   UR'                  5        H  u  pU
R%                  5       US
   U	'   M     Ub$  [        US5      (       a  UR%                  5       US'   U(       af  [        U [        R                  R                  R                  5      (       a  U R                  n [)        U R%                  5       5      nU(       d  UnOXS'   [*        R,                  " 5        n[        R.                  " X|5        [0        R2                  " UR5                  5       U5        SSS5        g! , (       d  f       g= f)a:  Save checkpoint to file.

The checkpoint will have 3 fields: ``meta``, ``state_dict`` and
``optimizer``. By default, ``meta`` will contain version and time info.

Args:
    model (Module): Module whose params are to be saved.
    filename (str): Checkpoint filename.
    optimizer (:obj:`Optimizer`, optional): Optimizer to be saved.
    lr_scheduler(:obj:`_LRScheduler`, optional): LRScheduler to be saved.
    meta (dict, optional): Metadata to be saved in checkpoint.
    with_meta (bool, optional): Save meta info.
    with_model(bool, optional): Save model states.
z;Save meta by "with_meta=True" or model by "with_model=True"Nz%meta must be a dict or None, but got r   )__version__)
modelscopetimeCLASSES)r/   r'   r%   r   r&   )
ValueError
isinstancedict	TypeErrortyper-   r,   updater.   asctimetorchr   parallelDistributedDataParallelmodulehasattrr/   r   r   r   r!   ioBytesIOsaver   writegetvalue)r#   r$   r%   r&   r'   r(   r)   
checkpointr,   nameoptim_weightsfs                r    save_checkpointrF   /   s   * JZIK 	K <DD$''7T
|DF F*{@eUXX..FFGGLLE5)$$)BKKK.!6 i++&/&:&:&<J{#	4((&(J{#(0050@0@0B
;'-  1 #l(K(K)5)@)@)BJ~&eUXX..FFGGLLE!%"2"2"45!J'/|$	

:!

1::<* 
s   <I
I'c                    [         R                  R                  U 5      (       d  [        SU  S35      e[        R
                  " U SSS9nUb  SU;   a  [        U[        5      (       a  UR                  US   5        O[        U[        5      (       aS  US   nUR                  5        H:  u  pgXe;   a  UR                  XV   5        M  [        R                  SU SU  35        M<     O[        R                  S	U  35        Ub3  S
U;   a  UR                  US
   5        O[        R                  SU  35        Ub  SU;  a  UOUS   nUR                  U5        UR                  S0 5      $ )NzCheckpoint file z does not exist!r   Tmap_locationweights_onlyr%   zThe state dict of optimizer z% cannot be found in checkpoint file: z@The state dict of optimizer cannot be found in checkpoint file: r&   zCThe state dict of lr_scheduler cannot be found in checkpoint file: r   r'   )ospathexistsr0   r7   loadr1   r   load_state_dictr2   r   loggerwarningget)	r$   r#   r%   r&   rA   optimizer_dictr   optimizer_insr   s	            r    load_checkpointrU   v   sb    77>>(##+H:5EFGGH5tLJ*$)Y//))*[*ABIt,,!+K!8*3//*;&C,%55n6IJ:3%?demdno	 +< NNRS[R\] Z'((N)CDNNUV^U_` #/z#AZzH
j)>>&"%%r"   c                   ^^^^^^ S mS m SS jmUUUUU4S jn   SS jm SS jmSU4S jjn[         R                  R                  U[        R                  5      n[
        R                  " US	S
S9nUb  [
        R                  " U5        U" U UUS
S
S9u  pp[        TR                  S5      SS5      (       a"  U" U TR                  S5      R                  5        U U	U
UUS.$ )a[  
Load model checkpoint file and feed the parameters into the model.
Args:
    model_to_load: The model to be load
    model_local_dir: The actual checkpoint dir on local disk.
    default_dtype: Set the default float type by 'torch.set_default_dtype'
    load_state_fn: An optional load_state_fn used to load state_dict into the model.

Returns:

c                 8   [        5       nU R                  5        HX  u  pVXR;   aJ  SR                  X/5      nXdU'   UR                  U5        [	        [        U5      [        U/5      -
  5      nMT  XdU'   MZ     / n[        U5      S:  a  UR                  5       nXHU4$ )N.r   )r   r   joinremovelistsetlencopy)	state_dictshead_prefix!expected_keys_without_head_prefixmissing_keysnew_state_dictrB   r:   name_with_headmissing_head_keyss	            r    _add_head_prefix_to_state_dictBload_task_model_checkpoint.<locals>._add_head_prefix_to_state_dict   s     %'--/LD8!$;*=!>17~.188>#C$5^<L8M$MN'-t$ 0 01A5 A F F H,>>r"   c                 P   / nU(       a  U H  nUn	U(       a  U SU 3n	O*U(       a#  SR                  UR                  S5      SS  5      n	X;   d  ME  X   R                  n
X   R                  nX:w  d  Mh  UR                  XU   R                  X   R                  45        X	 M     U$ )NrX      )rY   splitshapeappend)r_   model_state_dictloaded_keysprefixadd_prefix_to_modelremove_prefix_from_modelignore_mismatched_sizesmismatched_keycheckpoint_key	model_keymodel_shapecheckpoint_shapes               r    _find_mismatched_keys9load_task_model_checkpoint.<locals>._find_mismatched_keys   s     ""-*	+#)(!N+; <I( #)=)=c)B12)F GI0"2"="C"CK'2'B'H'H$'6&--+-H-N-N-8>>@A (7! #." r"   c           	        ^^
^^ / n/ nTR                  5        H`  nS nSU;   a  UR                  SS5      nSU;   a  UR                  SS5      nU(       d  M>  UR                  U5        UR                  U5        Mb     [        XV5       H  u  pTR	                  U	5      TU'   M     [        TSS 5      mTR                  5       mTb  TTl        / m
Ub  U" U TUUS T
S9  T
$ S
S[        R                  4U
UUU4S jjjmT" XS	9  T
$ )Ngammaweightbetabiasr   )ro   head_prefix_keyslocal_metadata
error_msgsr:   c                    > Tc  0 OTR                  US S 0 5      nT	XS/ / T4nU R                  " U6   U R                  R                  5        H  u  pEUc  M
  T" XQU-   S-   5        M     g )NTrX   )rR   _load_from_state_dict_modulesr   )
r:   ro   r   argsrB   childr   rN   metadatar   s
         r    rN   Mload_task_model_checkpoint.<locals>._load_state_dict_into_model.<locals>.load  sv    '/'7X\\3BK>%"FD"b"$,,d3#)??#8#8#:KD(UTMC$78 $;r"   )ro   ) )
keysreplacerl   zippopr   r^   r   r   Module)r#   r   start_prefixr   load_state_fnold_keysnew_keysr   new_keyold_keyr   rN   r   s    `        @@@r    _load_state_dict_into_model?load_task_model_checkpoint.<locals>._load_state_dict_into_model   s    ??$CG#~++gx8}++ff5w$( % !$H 7G",.."9Jw !8 :{D9__&
#+J 
$#!1#%'* 9RYY 9 9 ,r"   c                   >^*^+^, U R                  5       n[        UR                  5       5      n[        UR                  5       5      nU R                  m+[	        T+5      S:  a+  [        U+4S jU 5       5      n[        U+4S jU 5       5      n	OSnSn	U(       + =(       a    U	n
U=(       a    U	(       + nU
(       av  U Vs/ s H  oR                  T+5      (       a  M  UPM     snm*U Vs/ s H>  nUR                  T+5      (       a#  SR                  UR                  S5      SS  5      OUPM@     nnO,U(       a%  U Vs/ s H  nSR                  T+U/5      PM     nn/ m*[        [        U5      [        U5      -
  5      n[        [        U5      [        U5      -
  5      nU R                  n/ n/ n/ n[        5       n[        5       n[	        U5      S:  a  [	        U5      S:  a  [        U[        5      (       a  U/nU H  m,[        U,4S jU 5       5      UT,'   M     U Hd  m,U Vs/ s H>  nUR                  T,5      (       d  M  SR                  UR                  S5      SS  5      PM@     nnUR                  U5        UUT,'   Mf     [        [        U5      [        U5      -
  5      n[        [        U5      [        U5      -
  5      nT0R                  SS 5      nT0R                  S	S 5      nUb5  U H/  nU Vs/ s H  n[         R"                  " UU5      b  M  UPM!     nnM1     Ub5  U H/  nU Vs/ s H  n[         R"                  " UU5      b  M  UPM!     nnM1     U(       a$  T1" U UT+UU
S
9nU H  nU R%                  U5        M     [        5       n[	        U5      S:  a,  U H&  nUU   (       a  M  T-" UUUU   U5      u  nnnUUU'   M(     SnU n[        5       n [	        U R                  5      S:  a1  ['        U U R                  5      (       d  U(       a  U R                  S-   n[	        U R                  5      S:  at  ['        U U R                  5      (       aY  U(       dR  [)        X R                  5      nU H  n[)        U U5      U U'   M     [        U*4S jU 5       5      (       a  [+        S5      eT." UUUT+UU
U5      n!T/" UUUU5      n"[	        U 5      S:  a+  U  H%  n#T/" U U#   UU#S-   U5      n$U"R                  U$5        M'     [	        U"5      S:  a6  SR                  U"5      n%[-        SU R.                  R0                   SU% 35      e[	        U5      S:  a_  [2        R5                  SU R.                  R0                   SU SU R.                  R0                   SU R.                  R0                   S3	5        O[	        U5      S:  aH  [2        R5                  SU R.                  R0                   SU SU R.                  R0                   S35        O-[2        R7                  SU R.                  R0                   S35        [	        U5      S:  a1  [2        R5                  SU R.                  R0                   SU S35        OS[	        U!5      S:X  aD  [2        R7                  SU R.                  R0                   SU R.                  R0                   S35        [	        U!5      S:  ad  S R                  U! V&V'V(s/ s H  u  n&n'n(S!U& S"U' S#U( S$3PM     sn(n'n&5      n)[2        R5                  SU R.                  R0                   S%U) S35        XU!U"4$ s  snf s  snf s  snf s  snf s  snf s  snf s  sn(n'n&f )&Nr   c              3   D   >#    U  H  oR                  T5      v   M     g 7fN
startswith.0sro   s     r    	<genexpr>Gload_task_model_checkpoint.<locals>._load_checkpoint.<locals>.<genexpr>'  s       /D.BV$$.B    c              3   D   >#    U  H  oR                  T5      v   M     g 7fr   r   r   s     r    r   r   )  s      .=.;V$$mr   FrX   ri   c              3   D   >#    U  H  oR                  T5      v   M     g 7fr   r   )r   r   prefix_heads     r    r   r   R  s       >M7K!LL--7Kr   _keys_to_ignore_on_load_missing"_keys_to_ignore_on_load_unexpected)ro   
add_prefixremove_prefixr   c              3   .   >#    U  H
  nUT;   v   M     g 7fr    )r   r   %expected_keys_not_base_model_prefixeds     r    r   r     s      42s ??2s   zjThe state dictionary of the model you are trying to load is corrupted. Are you sure it was properly saved?z
	z#Error(s) in loading state_dict for z:
	zESome weights of the model checkpoint were not used when initializing z: z,
- This IS expected if you are initializing z from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForTokenClassification model from a BertForPreTraining model).
- This IS NOT expected if you are initializing z from the checkpoint of a model that you expect to be exactly identical (initializing a BertForTokenClassification model from a BertForTokenClassification model).z0
- This IS Not expected if you are initializing z from the checkpoint of a model with a same task while the structure is different (e.g. initializing a BertForTokenClassification model from a BertForTokenClassification model).z9All model checkpoint weights were used when initializing z.
zSome weights of zK were not initialized from the model checkpoint and are newly initialized: zo
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.zAll the weights of z were initialized from the model checkpoint If your task is similar to the task the model of the checkpoint was trained on, you can already use z* for predictions without further training.
z- z: found shape z in the checkpoint and z in the model instantiatedzl were not initialized from the model checkpoint and are newly initialized because the shapes did not match:
)r   r[   r   base_model_prefixr]   anyr   rY   rj   r\   r`   r2   r1   strextendr   research_init_weightsr;   r   r0   RuntimeError	__class____name__rP   rQ   info)2r#   r   r   rr   
_fast_initrm   expected_keyskeys_from_pretrainedpretrained_has_prefix_modulemodel_expects_prefix_modulerq   rp   r   rb   unexpected_keysprefix_heads&expected_head_keys_without_head_prefixre   unexpected_head_keyspretrained_has_prefix_headr   ra   r   r   patkuninitialized_modulesr:   missing_head_keys_by_headr`   r   model_to_loadheads_to_loadmismatched_keysr   headlocal_error_msgs	error_msgr   shape1shape2mismatched_warningr   ro   r   rf   rx   r   kwargsretrieve_modules_from_namess2                                             @@@r    _load_checkpoint4load_task_model_checkpoint.<locals>._load_checkpoint  s    !++--2245#JOO$56(( v;?+. /D.B/D ,D(*- .=.;.= +=' ,1(*/''C#C#cHc :^C^?^#(5(aV0D=51
 '&A /0ll6.B.Bab)*I&  M !<IJMqSXXvqk2MMJ461C.5I1JJKs#783};MMN ((13.!%)V"6 |q S%9A%=,,, ,~  ,:= >M7K>M ;M*;7  ,  ,8E58E1||K0 /CHHQWWS\!"-. 2 5 7==57 $E !!  , $(O$<=>$?  #O$<=>?O +1**-t+5'-3ZZ0$.8* +66+ +!ryya/@A|    7
 .99.#.!"))C2CA   # : $?.6%8! 0##F+ 0 %)F! 1$/1+>>B`"K1A+1N$C&?J 1< >O-k:  0 u&&'!+G''5) 5)-I 22S8Lu&&'!+''1) 1)1M#E+B+BCM+-4UK-Hk*  , 424 4 4 &' '
 0 $#
 1
1=}N
 }!%#>!$'TCZ$P !!"23 &
 z?QJ/I5eoo6N6N5OuU^T_`  !#NN!!&!9!9 :"_<M N!!&!9!9 : ; OO,,- .nn %&*NN!!&!9!9 :"=Q<R S!!&!9!9 : ;667 KKKEOOLdLdKeehi |q NN"5??#;#;"< =//;n =nn
 !Q&KK%eoo&>&>%? @88=8P8P7Q R
 !#!%+:,+:'C SEx/FvhNhi+:, " NN"5??#;#;"< =./ 0<<= ozIIc5 K25. #P,sC   <\?\?&A]9]	 ]>']1]])]	]']Fc                    [        U Vs/ s H&  nSR                  UR                  S5      S S 5      PM(     sn5      nUR                  [        U Vs/ s H@  nUS   R	                  5       (       d  M  SR                  UR                  S5      S S 5      PMB     sn5      5      n/ nU R                  5        H  u  pU(       a<  UR                  U5      (       a#  SR                  UR                  S5      SS  5      OUnO*U(       a#  [        U5      S:  a  SR                  X(/5      OUnX;   d  My  UR                  U	5        M     U$ s  snf s  snf )NrX   r   ri   r   )	r\   rY   rj   unionisdigitnamed_modulesr   r]   rl   )
r#   namesro   r   r   r   module_keysretrieved_modulesrB   r:   s
             r    r   ?load_task_model_checkpoint.<locals>.retrieve_modules_from_names  s.   
 EJES388CIIcN3B$78EJK "''9>9>#r7??$ .3,-  !//1LD,0OOF,C,C xxJJsOAB')IM 36t9q=sxx/f"!((0 2 ! - K
s   -EE2'Ec                    U(       a4  [         R                  " UR                  R                  5       5      U l        OUR                  U l        [	        U SS 5      bx  [         R
                  R                  U R                  R                  SU R                  R                  S   U R                  R                  S   -
  4SS5      U R                  l        [        U S5      (       a$  [        US5      (       a  UR                  U l        g g g )Nr~   r   constantout_featuresnum_embeddings)r   	Parameterr|   cloner   
functionalpadr~   datark   r;   r   r   )output_embeddingsinput_embeddingstorchscripts      r    _tie_or_clone_weights9load_task_model_checkpoint.<locals>._tie_or_clone_weights  s     ')|| ''--/(1$ (8'>'>$$fd3?*,--*;*;!&&++%,,2215',,22156
 	+""' $n55' "2;4 ;4-=-L-L*;45r"   c                    > U(       aA  U R                   R                  5       nUb#  U R                  R                  5       nT" X#5        g g g r   )r   get_output_embeddingsencoderget_input_embeddings)r#   tie_word_embeddingsr   r   r   s       r    tie_weights/load_task_model_checkpoint.<locals>.tie_weights  sE     %

 @ @ B ,#(==#E#E#G %&7J - r"   r   TrH   )r   rr   r   r   r   )r#   rb   r   r   r   r   )NFF)F)rK   rL   rY   r   TORCH_MODEL_BIN_FILEr7   rN   set_default_dtyper   rR   r   )r   model_local_dirdefault_dtyper   r   r   r   	ckpt_filer   rb   r   r   r   rf   rx   r   r   r   s       `        @@@@@r    load_task_model_checkpointr      s    "?$F 4lOJ OJf ,0/427	!> +0M2K _i.L.LMIIEMJ .AQ# $B>L? vzz&!#8%@@M6::f#5#I#IJ $**  r"   configc                    [        U[        5      (       a  UR                  5       n[        R                  U;  a&  SU[        R
                     0U[        R                  '   [        R                  " US[        S9n[        R                  R                  U [        R                  5      n[        R                  UR!                  5       U5        g )Nr4      )indentcls)r1   r   to_dictr   pipelinetaskjsondumpsr   rK   rL   rY   r   CONFIGURATIONstorager?   encode)target_folderr   cfg_strconfig_files       r    save_configurationr  >  s    &&!!!F*)/8I8I1J(K|$$%jj/BCG'',,}i.E.EFKMM'.."K0r"   r  save_checkpoint_namesave_functionc                    Ub  [        U[        5      (       d  [        S5      eUb$  [        R                  R                  U5      (       a  [        SU S35      eUc  [        S5      e[        R                  R                  X5      nU/n[        U5      nUR                  [        R                  5        UR                  S5        UR                  S5        [        U S5      (       a`  U R                  bS  [        5       (       aD  [        R                   R"                  S	:  a  [$        nO[&        nU" U R                  U[)        U6 S
S9   U" X40 UD6  g! [         a*  n	[        S[+        U	5      R,                   SU	 S35      eSn	A	ff = f)a  save the pretrained model, its configuration and other related files to a directory, so that it can be re-loaded

Args:
    model (Model): Model whose params are to be saved.

    target_folder (Union[str, os.PathLike]):
    Directory to which to save. Will be created if it doesn't exist.

    save_checkpoint_name (str):
    The checkpoint name to be saved in the target_folder

    save_function (Callable):
    The function to use to save the state dictionary.
Nz'A valid save function must be passed inzProvided path (z#) should be a directory, not a filez6At least pass in one checkpoint name for saving methodz*.safetensorsz.*	model_dir   T)ignoredirs_exist_okz)During saving checkpoints, the error of "z
 with msg z thrown)r1   r   	ExceptionrK   rL   isfiler0   rY   r\   addr   r  r;   r  r   sysversion_infominorr   r   r   r4   r   )
r#   r  r	  r
  r   output_ckpt_pathorigin_file_to_be_ignoredignore_file_setcopytree_funces
             r    save_pretrainedr  H  sy   ( J}h$G$GABB} = =m_,OP
 	
 #DF 	F ww||MH "6 634O	//0(u  % ;	!!Q&$M)MOO"O4		 $e88 $7Q8H8H7I Js'#$ 	$$s   	E 
F%FF)NNNTT)NN)3r<   rK   r   r  r.   collectionsr   shutilr   r   r   typingr   r   r	   r
   r   r7   r   torch.optimr   torch.optim.lr_schedulerr   modelscope.fileior   r   modelscope.utils.configr   r   modelscope.utils.constantr   r   modelscope.utils.file_utilsr   modelscope.utils.loggerr   modelscope.utils.torch_utilsr   rP   r  r!   r   r   r2   boolrF   rU   r   r  PathLiker  r   r"   r    <module>r)     sH   
 	 	 
  # 4 4 2 2    ! 1 0 ? = 5 . 2	
.& 6:;?+/&*'+D+588?? D+!D+'	2D+ #+<"8D+ #4.	D+
  $D+ !%D+ 15D+R ,015&&(&& #/&&V .2-1\~1d 1 15.2;$#(bkk)9#:;$*-;$ $,;$r"   