
    biy                        d dl Z d dlZd dlmZmZ d dlmZ d dlmZ d dl	m
Z
mZmZmZmZmZ d dlZd dlZddlmZmZ dd	lmZ dd
lmZmZ  e       rd dlmZmZ d dlmZ  ee       Z!dZ"dZ#dZ$dZ% G d de&e      Z'e G d d             Z( G d d      Z) G d de      Z* G d de      Z+ G d de      Z, ejZ                  d      dddddddfd ej\                  j^                  d!ee&ejZ                  f   d"ee&ejZ                  f   d#ee&e'f   d$ee0   d%e1d&e1d'e1d(e1d)ee&   d*dfd+Z2d ej\                  j^                  d,e(d*dfd-Z3d ej\                  j^                  d,e(d*dfd.Z4d ej\                  j^                  d,e(d*dfd/Z5d ej\                  j^                  d0e)d,e(d*dfd1Z6d ej\                  j^                  d0e)d,e(d*dfd2Z7d ej\                  j^                  d3ee&   d*eej\                  jp                     fd4Z9d ej\                  j^                  d3ee&   d*eejt                     fd5Z;d6e&d7e
e&ej\                  j^                  f   d*e&fd8Z<d ej\                  j^                  d*dfd9Z=d ej\                  j^                  d*ee*   fd:Z>d ej\                  j^                  d*e1fd;Z?d ej\                  j^                  d*ejZ                  fd<Z@d= ZAd ej\                  j^                  d*dfd>ZBy)?    N)contextmanagernullcontext)	dataclass)Enum)DictListOptionalSetTupleUnion   )
get_loggeris_accelerate_available   )_GO_LC_SUPPORTED_PYTORCH_LAYERS)HookRegistry	ModelHook)AlignDevicesHook
CpuOffload)send_to_devicegroup_offloadinglayer_execution_trackerlazy_prefetch_group_offloading
lazy_leafsc                       e Zd ZdZdZy)GroupOffloadingTypeblock_level
leaf_levelN)__name__
__module____qualname__BLOCK_LEVEL
LEAF_LEVEL     [/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/hooks/group_offloading.pyr   r   .   s    KJr%   r   c                       e Zd ZU ej                  ed<   ej                  ed<   eed<   eed<   eed<   eed<   dZe	e
   ed<   dZe	e   ed	<   dZe	eej                  j                   ej                   f      ed
<   y)GroupOffloadingConfigonload_deviceoffload_deviceoffload_typenon_blockingrecord_streamlow_cpu_mem_usageNnum_blocks_per_groupoffload_to_disk_pathstream)r   r    r!   torchdevice__annotations__r   boolr/   r	   intr0   strr1   r   cudaStreamr$   r%   r&   r(   r(   3   ss    <<LL %%*.(3-.*.(3-.?CFHU5::,,ell:;<Cr%   r(   c                   |   e Zd Z	 	 	 	 	 	 	 	 	 	 ddeej
                  j                     dej                  dej                  dej
                  j                  deej
                  j                     deeej
                  j                        deeej                        d	ed
eej                  j                  ej                  df   dee   dededee   dee   ddfdZd Zed        Zd ZddZd Zd Zd Zd Zej6                  j9                         d        Zej6                  j9                         d        Zy)ModuleGroupNmodulesr*   r)   offload_leaderonload_leader
parametersbuffersr,   r1   r-   r.   onload_selfr0   group_idreturnc                    || _         || _        || _        || _        || _        |xs g | _        |xs g | _        |xs |	d u| _        |	| _        |
| _	        || _
        || _        || _        d| _        | j                  ~||nt        t        |             | _        t#        | j                         }t$        j&                  j)                  | j                  d| d      | _        g }| j                   D ]R  }|j-                  t/        |j                                      |j-                  t/        |j                                      T |j-                  | j
                         |j-                  | j                         t/        t0        j3                  |            }t5        |      D ci c]  \  }}|d|  c}}| _        | j6                  j9                         D ci c]  \  }}||
 c}}| _        i | _        n| j?                         | _        tA        tB        d      r<tE        tB        tB        jF                  jI                         jJ                        | _'        y tB        jL                  | _'        y c c}}w c c}}w )NFgroup_z.safetensorstensor_accelerator)(r<   r*   r)   r=   r>   r?   r@   r,   r1   r-   rA   r.   r0   _is_offloaded_to_diskr7   idrB   _compute_group_hashospathjoinsafetensors_file_pathextendlistdictfromkeys	enumeratetensor_to_keyitemskey_to_tensorcpu_param_dict_init_cpu_param_dicthasattrr2   getattrrG   current_acceleratortyper8   _torch_accelerator_module)selfr<   r*   r)   r=   r>   r?   r@   r,   r1   r-   r.   rA   r0   rB   
short_hashall_tensorsmoduleitensorkvs                         r&   __init__zModuleGroup.__init__A   s   " ,*,*$*}"(>F$,>*&!2$8!%*"$$0(0(<H#bh-DM,T]];J)+d6O6OSYZdYeeqQr)sD&K,, ;""4(9(9(;#<=""4(8#9:; t/t||,t}}[9:KIRS^I_!`IAv&GA3-"7!`D373E3E3K3K3M!N41a!Q$!ND"$D"&";";"=D um, E5,,@@BGGH 	&  	& "a!Ns   (I3I9c                 h   i }| j                   |S | j                  D ]  }|j                         D ]S  }| j                  r|j                  j                         n'|j                  j                         j                         ||<   U |j                         D ]S  }| j                  r|j                  j                         n'|j                  j                         j                         ||<   U  | j                  D ]S  }| j                  r|j                  j                         n'|j                  j                         j                         ||<   U | j                  D ]S  }| j                  r|j                  j                         n'|j                  j                         j                         ||<   U |S N)r1   r<   r?   r.   datacpu
pin_memoryr@   )r^   rW   ra   parambuffers        r&   rX   z ModuleGroup._init_cpu_param_dict|   sn   ;;!!ll 	F**, v<@<R<R

(8X]XbXbXfXfXhXsXsXuu%v ..* )-)?)?FKKOO%V[[__EVEaEaEc v&	 __ 	rE8<8N8NEJJNN$4TYT^T^TbTbTdToToTqN5!	r ll 	uF:>:P:PV[[__%6V\VaVaVeVeVgVrVrVtN6"	u r%   c              #      K   	 | j                   j                         D ci c](  \  }}||j                         s|j                         n|* }}}| d }y c c}}w # d }w xY wwrh   )rW   rU   	is_pinnedrk   )r^   rl   rc   pinned_dicts       r&   _pinned_memory_tensorsz"ModuleGroup._pinned_memory_tensors   sr     	 &*%8%8%>%>%@!E6 &2B2B2Dv((*&PK  K Ks-   A%A -AA A%A A""A%c                     |j                  | j                  | j                        |_        | j                  r4|j                  j	                  | j
                  j                                y y Nr,   )tor)   r,   ri   r-   r]   current_stream)r^   rc   source_tensors      r&   _transfer_tensor_to_devicez&ModuleGroup._transfer_tensor_to_device   sT    #&&t'9'9HYHY&ZKK%%d&D&D&S&S&UV r%   c                    | j                   D ]v  }|j                         D ]'  }|r||   n|j                  }| j                  ||       ) |j	                         D ]'  }|r||   n|j                  }| j                  ||       ) x | j                  D ]'  }|r||   n|j                  }| j                  ||       ) | j                  D ]'  }|r||   n|j                  }| j                  ||       ) y rh   )r<   r?   ri   rx   r@   )r^   pinned_memorygroup_modulerl   sourcerm   s         r&   _process_tensors_from_modulesz)ModuleGroup._process_tensors_from_modules   s     LL 	@L%002 ?1>u-EJJ//v>? '..0 @2?v.V[[//?@		@ __ 	;E-:]5)

F++E6:	; ll 	<F.;]6*F++FF;	<r%   c                 F   | j                   | j                   j                          | j                   
t               n$| j                  j                  | j                         }| j                  r| j                  j                         nd }|5  | j                   t        | j                        nd}t        j                  j                  | j                  |      }| j                   | j                  j                         D ]l  \  }}||   j                         }|j                  | j                  | j                         |_        | j                  sR|j"                  j	                  |       n nt%        | j                  t        j&                        r| j                  j(                  n| j                  }t        j                  j                  | j                  |      }| j                  j                         D ]  \  }}||   |_         d d d        y # 1 sw Y   y xY w)Nrj   r3   rt   )r1   synchronizer   r]   r-   rv   r7   r)   safetensorsr2   	load_filerN   rV   rU   rk   ru   r,   ri   
isinstancer3   r\   )	r^   contextrv   r3   loaded_tensorskey
tensor_objpinned_tensorr)   s	            r&   _onload_from_diskzModuleGroup._onload_from_disk   s   ;;"KK##%#';;#6+-D<Z<Z<a<abfbmbm<nLPL^L^77FFHdh 	:040CS++,F(..889S9S\b8cN{{&'+'9'9'?'?'A FOC$23$7$B$B$DM&3&6&6t7I7IX\XiXi&6&jJO))"55nE	F 0:$:L:Lell/[D&&++aeasas  "-!2!2!<!<T=W=W`m!<!n'+'9'9'?'?'A :OC&4S&9JO:!	: 	: 	:s   CHB;HH c                    | j                   | j                   j                          | j                   
t               n$| j                  j                  | j                         }|5  | j                   +| j	                         5 }| j                  |       d d d        n| j                  d        d d d        y # 1 sw Y   xY w# 1 sw Y   y xY wrh   )r1   r   r   r]   rq   r}   )r^   r   rz   s      r&   _onload_from_memoryzModuleGroup._onload_from_memory   s    ;;"KK##%#';;#6+-D<Z<Z<a<abfbmbm<n 	9{{&002 Fm66}EF F 2248	9 	9F F	9 	9s$   $CB6C6B?	;CCc                    | j                   st        j                  j                  | j                        st        j
                  t        j                  j                  | j                        d       | j                  j                         D ci c]+  \  }}||j                  j                  | j                        - }}}t        j                  j                  || j                         d| _         | j                  j                         D ]2  }t        j                   |j                  | j                        |_	        4 y c c}}w )NT)exist_okr   )rH   rK   rL   existsrN   makedirsdirnamerT   rU   ri   ru   r*   r   r2   	save_filekeys
empty_like)r^   rc   r   tensors_to_saver   s        r&   _offload_to_diskzModuleGroup._offload_to_disk   s     ))"''..A[A[2\KK(B(BCdS[_[m[m[s[s[uvKFTWsFKKNN43F3F$GGvOv''9S9ST &*" ,,113 	\J#..ztGZGZ[JO	\ ws   0Ec                    | j                   | j                  s(| j                  j                         j	                          | j
                  D ]+  }|j                         D ]  }| j                  |   |_         - | j                  D ]  }| j                  |   |_         | j                  D ]  }| j                  |   |_         y | j
                  D ]  }|j                  | j                  d       ! | j                  D ].  }|j                  j                  | j                  d      |_        0 | j                  D ].  }|j                  j                  | j                  d      |_        0 y )NFrt   )r1   r-   r]   rv   r   r<   r?   rW   ri   r@   ru   r*   )r^   r{   rl   rm   s       r&   _offload_to_memoryzModuleGroup._offload_to_memory   sL   ;;"%%..==?KKM $ <)446 <E!%!4!4U!;EJ<<  8!007
8,, :"11&9: !% I 3 3%HI T"ZZ]]4+>+>U]S
T,, V$kknnT-@-@unUVr%   c                 ^    | j                   | j                          y| j                          y)z5Onloads the group of parameters to the onload_device.N)r0   r   r   r^   s    r&   onload_zModuleGroup.onload_   s(     $$0""$$$&r%   c                 ^    | j                   r| j                          y| j                          y)z7Offloads the group of parameters to the offload_device.N)r0   r   r   r   s    r&   offload_zModuleGroup.offload_  s%     $$!!###%r%   )
NNNFNFFTNNrh   )r   r    r!   r   r2   nnModuler3   r	   	ParameterTensorr5   r   r8   r9   r7   r6   rf   rX   r   rq   rx   r}   r   r   r   r   compilerdisabler   r   r$   r%   r&   r;   r;   @   s    489=04"?C(-"' .2"&9
ehhoo&9
 9
 ||	9

 9
  09
 T%(("4"4569
 $u||,-9
 9
 ejj''t;<9
  ~9
  9
 9
 'sm9
 3-9
  
!9
v*  W
<":69\$V( ^^' ' ^^& &r%   r;   c                       e Zd ZdZdZdededdfdZdej                  j                  dej                  j                  fd	Zdej                  j                  fd
Zdej                  j                  fdZy)GroupOffloadingHooka  
    A hook that offloads groups of torch.nn.Module to the CPU for storage and onloads to accelerator device for
    computation. Each group has one "onload leader" module that is responsible for onloading, and an "offload leader"
    module that is responsible for offloading. If prefetching is enabled, the onload leader of the previous module
    group is responsible for onloading the current module group.
    FgroupconfigrC   Nc                .    || _         d | _        || _        y rh   )r   
next_groupr   )r^   r   r   s      r&   rf   zGroupOffloadingHook.__init__  s    
15r%   ra   c                 l    | j                   j                  |k(  r| j                   j                          |S rh   r   r=   r   )r^   ra   s     r&   initialize_hookz#GroupOffloadingHook.initialize_hook   )    ::$$.JJ!r%   c                     | j                   j                  || j                   _        | j                   j                  |k(  r| j                   j                  r| j                   j                          | j                  d uxr | j                  j                   }|r| j                  j                          | j                   j                   xr | j                   j
                  d uxr | }|r$| j                   j
                  j                          t        || j                   j                  | j                   j                        }t        || j                   j                  | j                   j                        }||fS rs   )
r   r>   rA   r   r   r1   r   r   r)   r,   )r^   ra   argskwargsshould_onload_next_groupshould_synchronizes         r&   pre_forwardzGroupOffloadingHook.pre_forward%  s$    ::##+'-DJJ$
 ::##v-zz%%

""$'+d'B'f4??KfKfGf$''') JJ***mtzz/@/@/LmUmQm  " 

!!--/dDJJ$<$<4::KbKbc

(@(@tzzOfOfgV|r%   c                 l    | j                   j                  |k(  r| j                   j                          |S rh   r   )r^   ra   outputs      r&   post_forwardz GroupOffloadingHook.post_forwardF  r   r%   )r   r    r!   __doc___is_statefulr;   r(   rf   r2   r   r   r   r   r   r$   r%   r&   r   r     sv     Lk 6K PT 
ehhoo %((// 
%((// B588?? r%   r   c                   &    e Zd ZdZdZd Zd Zd Zy)LazyPrefetchGroupOffloadingHooka  
    A hook, used in conjunction with GroupOffloadingHook, that applies lazy prefetching to groups of torch.nn.Module.
    This hook is used to determine the order in which the layers are executed during the forward pass. Once the layer
    invocation order is known, assignments of the next_group attribute for prefetching can be made, which allows
    prefetching groups in the correct order.
    Fc                 0    g | _         t               | _        y rh   )execution_orderset%_layer_execution_tracker_module_namesr   s    r&   rf   z(LazyPrefetchGroupOffloadingHook.__init__V  s    BD58U2r%   c                 h     fd}|j                         D ]  \  }}|dk(  st        |d      st        j                  |      }|j	                  t
              }|Ed|j                  _        t         |||            }|j                  |t                j                  j                  |        |S )Nc                       fd}|S )Nc                      t         j                  j                         st        j	                  d  d       j
                  j                   f       y )NzAdding z to the execution order)r2   r   is_compilingloggerdebugr   append)current_namecurrent_submoduler^   s   r&   callbackzoLazyPrefetchGroupOffloadingHook.initialize_hook.<locals>.make_execution_order_update_callback.<locals>.callback\  sC    ~~224LL7<.8O!PQ$$++\;L,MNr%   r$   )r   r   r   r^   s   `` r&   $make_execution_order_update_callbackz]LazyPrefetchGroupOffloadingHook.initialize_hook.<locals>.make_execution_order_update_callback[  s    O
 Or%    _diffusers_hookF)named_modulesrY   r   check_if_exists_or_initializeget_hook_GROUP_OFFLOADINGr   r,   LayerExecutionTrackerHookregister_hook_LAYER_EXECUTION_TRACKERr   add)r^   ra   r   name	submoduleregistrygroup_offloading_hooklayer_tracker_hooks   `       r&   r   z/LazyPrefetchGroupOffloadingHook.initialize_hookZ  s    	  &335 	EOD)rz4E!F#AA)LH$,$5$56G$H!$0;@%++8%>?cdhjs?t%u"&&'9;ST::>>tD	E r%   c                 f   t        | j                        }| j                  D ch c]  \  }}|	 }}}|| j                  k7  rNt        | j                  |z
        }t        j
                  j                         st        j                  d|       |j                  }| j                  D 	cg c]  \  }}	|	j                   }
}}	|
D cg c]  }|j                  t               }}t        |      D ]  }|
|   j                  t        d        |j                  t        d       |D ]  }d|j                   _         |dkD  r:|j                  t              }|d   j                   |_        d|j$                  _        t        |dz
        D ]  }| j                  |   \  }}| j                  |dz      \  }}t        j
                  j                         st        j)                  d| d|        ||dz      j                   ||   _        d||   j$                  _         |S c c}}w c c}	}w c c}w )	NaB  It seems like some layers were not executed during the forward pass. This may lead to problems when applying lazy prefetching with automatic tracing and lead to device-mismatch related errors. Please make sure that all layers are executed during the forward pass. The following layers were not executed:
unexecuted_layers=FrecurseTr   r   z-Applying lazy prefetch group offloading from z to )lenr   r   rP   r2   r   r   r   warningr   r   r   rangeremove_hookr   _LAZY_PREFETCH_GROUP_OFFLOADINGr   r,   r   rA   r   )r^   ra   r   num_executedr   _execution_order_module_namesunexecuted_layersbase_module_registryr   
registriesr   group_offloading_hooksrb   hook!base_module_group_offloading_hookname1name2s                     r&   r   z,LazyPrefetchGroupOffloadingHook.post_forwardv  s6    4//0<@<P<P'Qq'Q$'Q (4+U+UU $T%O%ORn%n o>>..0* )*,  &55DHDXDXYLAyi//Y
YWa!b8("3"34E"F!b!b|$ 	OAqM%%&>%N	O 	(()HRW(X
 + 	+D&*DJJ#	+ !0D0M0MN_0`-;QRS;T;Z;Z-8GL-88D|a'( 	EA++A.HE1++AE2HE1>>..0LUGSWX]W^_`3I!a%3P3V3V"1%0?D"1%00<	E _ (R$ Z!bs   H",H(	H.N)r   r    r!   r   r   rf   r   r   r$   r%   r&   r   r   L  s     L;84r%   r   c                        e Zd ZdZdZd Zd Zy)r   z
    A hook that tracks the order in which the layers are executed during the forward pass by calling back to the
    LazyPrefetchGroupOffloadingHook to update the execution order.
    Fc                     || _         y rh   execution_order_update_callback)r^   r   s     r&   rf   z"LayerExecutionTrackerHook.__init__  s
    /N,r%   c                 *    | j                          ||fS rh   r   )r^   ra   r   r   s       r&   r   z%LayerExecutionTrackerHook.pre_forward  s    ,,.V|r%   N)r   r    r!   r   r   rf   r   r$   r%   r&   r   r     s    
 LOr%   r   rj   r   Fra   r)   r*   r+   r/   r,   
use_streamr-   r.   r0   rC   c
                    t        |t              rt        j                  |      n|}t        |t              rt        j                  |      n|}t	        |      }d}
|rt        j
                  j                         rt        j
                  j                         }
nNt        t        d      r3t        j                  j                         rt        j                         }
nt        d      |s|rt        d      |t        j                  k(  r|t        d      t        |        t        ||||||
|||		      }t        | |       y)a  
    Applies group offloading to the internal layers of a torch.nn.Module. To understand what group offloading is, and
    where it is beneficial, we need to first provide some context on how other supported offloading methods work.

    Typically, offloading is done at two levels:
    - Module-level: In Diffusers, this can be enabled using the `ModelMixin::enable_model_cpu_offload()` method. It
      works by offloading each component of a pipeline to the CPU for storage, and onloading to the accelerator device
      when needed for computation. This method is more memory-efficient than keeping all components on the accelerator,
      but the memory requirements are still quite high. For this method to work, one needs memory equivalent to size of
      the model in runtime dtype + size of largest intermediate activation tensors to be able to complete the forward
      pass.
    - Leaf-level: In Diffusers, this can be enabled using the `ModelMixin::enable_sequential_cpu_offload()` method. It
      works by offloading the lowest leaf-level parameters of the computation graph to the CPU for storage, and
      onloading only the leafs to the accelerator device for computation. This uses the lowest amount of accelerator
      memory, but can be slower due to the excessive number of device synchronizations.

    Group offloading is a middle ground between the two methods. It works by offloading groups of internal layers,
    (either `torch.nn.ModuleList` or `torch.nn.Sequential`). This method uses lower memory than module-level
    offloading. It is also faster than leaf-level/sequential offloading, as the number of device synchronizations is
    reduced.

    Another supported feature (for CUDA devices with support for asynchronous data transfer streams) is the ability to
    overlap data transfer and computation to reduce the overall execution time compared to sequential offloading. This
    is enabled using layer prefetching with streams, i.e., the layer that is to be executed next starts onloading to
    the accelerator device while the current layer is being executed - this increases the memory requirements slightly.
    Note that this implementation also supports leaf-level offloading but can be made much faster when using streams.

    Args:
        module (`torch.nn.Module`):
            The module to which group offloading is applied.
        onload_device (`torch.device`):
            The device to which the group of modules are onloaded.
        offload_device (`torch.device`, defaults to `torch.device("cpu")`):
            The device to which the group of modules are offloaded. This should typically be the CPU. Default is CPU.
        offload_type (`str` or `GroupOffloadingType`, defaults to "block_level"):
            The type of offloading to be applied. Can be one of "block_level" or "leaf_level". Default is
            "block_level".
        offload_to_disk_path (`str`, *optional*, defaults to `None`):
            The path to the directory where parameters will be offloaded. Setting this option can be useful in limited
            RAM environment settings where a reasonable speed-memory trade-off is desired.
        num_blocks_per_group (`int`, *optional*):
            The number of blocks per group when using offload_type="block_level". This is required when using
            offload_type="block_level".
        non_blocking (`bool`, defaults to `False`):
            If True, offloading and onloading is done with non-blocking data transfer.
        use_stream (`bool`, defaults to `False`):
            If True, offloading and onloading is done asynchronously using a CUDA stream. This can be useful for
            overlapping computation and data transfer.
        record_stream (`bool`, defaults to `False`): When enabled with `use_stream`, it marks the current tensor
            as having been used by this stream. It is faster at the expense of slightly more memory usage. Refer to the
            [PyTorch official docs](https://pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html) more
            details.
        low_cpu_mem_usage (`bool`, defaults to `False`):
            If True, the CPU memory usage is minimized by pinning tensors on-the-fly instead of pre-pinning them. This
            option only matters when using streamed CPU offloading (i.e. `use_stream=True`). This can be useful when
            the CPU memory is a bottleneck but may counteract the benefits of using streams.

    Example:
        ```python
        >>> from diffusers import CogVideoXTransformer3DModel
        >>> from diffusers.hooks import apply_group_offloading

        >>> transformer = CogVideoXTransformer3DModel.from_pretrained(
        ...     "THUDM/CogVideoX-5b", subfolder="transformer", torch_dtype=torch.bfloat16
        ... )

        >>> apply_group_offloading(
        ...     transformer,
        ...     onload_device=torch.device("cuda"),
        ...     offload_device=torch.device("cpu"),
        ...     offload_type="block_level",
        ...     num_blocks_per_group=2,
        ...     use_stream=True,
        ... )
        ```
    NxpuzOUsing streams for data transfer requires a CUDA device, or an Intel XPU device.z7`record_stream` cannot be True when `use_stream=False`.zO`num_blocks_per_group` must be provided when using `offload_type='block_level'.)	r)   r*   r+   r/   r,   r1   r-   r.   r0   )r   r7   r2   r3   r   r8   is_availabler9   rY   r   
ValueErrorr"   ;_raise_error_if_accelerate_model_or_sequential_hook_presentr(   _apply_group_offloading)ra   r)   r*   r+   r/   r,   r   r-   r.   r0   r1   r   s               r&   apply_group_offloadingr     s	   r 4>mS3QELL/WdM5?PS5TU\\.1ZhN&|4LF::""$ZZ&&(FUE"uyy'='='?\\^Fnoo-RSS*666;O;Wjkk?G"#%!1!#+1
F FF+r%   r   c                     |j                   t        j                  k(  rt        | |       y |j                   t        j                  k(  rt        | |       y J rh   )r+   r   r"   #_apply_group_offloading_block_levelr#   "_apply_group_offloading_leaf_level)ra   r   s     r&   r   r   8  sE    1===+FF;			 3 > >	>*66:ur%   c                    |j                   9|j                  dk7  r*t        j                  d|j                  d       d|_        t	               }g }g }| j                         D ]`  \  }}t        |t        j                  j                  t        j                  j                  f      s%|j                  ||f       |j                  |       jt        dt        |      |j                        D ]  }||||j                  z    }| d| d|t        |      z   dz
   }	t        ||j                   |j"                  |j$                  |d   |d   |j&                  |j                   |j(                  |j*                  d|		      }
|j                  |
       t        ||t        |      z         D ]  }|j                  | d
|          c t-        |      D ]$  \  }}
|
j.                  D ]  }t1        ||
|        & t3        | |      }t5        | |      }|D cg c]  \  }}|	 }}}|D cg c]  \  }}|	 }}}|D cg c]  \  }}|	 }}}t        ||j                   |j"                  |j$                  | | ||dddd| j6                  j8                   d      }|j                   t1        | ||       yt;        | ||       yc c}}w c c}}w c c}}w )z
    This function applies offloading to groups of torch.nn.ModuleList or torch.nn.Sequential blocks. In comparison to
    the "leaf_level" offloading, which is more fine-grained, this offloading is done at the top-level blocks.
    Nr   z\Using streams is only supported for num_blocks_per_group=1. Got config.num_blocks_per_group=z. Setting it to 1.r   r   Tr<   r*   r)   r0   r=   r>   r,   r1   r-   r.   rA   rB   .r   F_unmatched_group)r<   r*   r)   r0   r=   r>   r?   r@   r,   r1   r-   rA   rB   )r1   r/   r   r   r   named_childrenr   r2   r   
ModuleList
Sequentialr   r   r   r   r;   r*   r)   r0   r,   r-   r.   rS   r<   _apply_group_offloading_hook2_gather_parameters_with_no_group_offloading_parent/_gather_buffers_with_no_group_offloading_parent	__class__r   !_apply_lazy_group_offloading_hook)ra   r   modules_with_group_offloadingunmatched_modulesmatched_module_groupsr   r   rb   current_modulesrB   r   jr{   r?   r@   r   rl   rm   unmatched_moduleunmatched_groups                       r&   r   r   A  s    }} V%@%@A%EkvOjOjNll~	
 '(# %(E!!002 Ai)ehh&9&9588;N;N%OP$$dI%67)--d3q#i.&*E*EF 	AA'A0K0K,KLOq1Q_)=%=%A$BCH'%44$22%+%@%@.r2-a0#00}}$22"(":": !E "((/1a#o"667 A-11TF!A3-@A%	AA8 34 M5!MM 	ML(uVL	MM DFLijJ=fFcdG(23HAu%3J3'./)!Vv/G/ FWW.Aa1A)WW!!,,**#88$$--..>?O }}$V_VL)&/&Q1 4/ Xs   K+K?Kc                    t               }| j                         D ]  \  }}t        |t              st	        |g|j
                  |j                  |j                  |||j                  |j                  |j                  |j                  d|      }t        |||       |j                  |        t        | j                               }t        | |      }t!        | |      }i }	|D ]0  \  }}
t#        ||      }||	v r|	|   j%                  |
       +|
g|	|<   2 i }|D ]0  \  }}t#        ||      }||v r||   j%                  |       +|g||<   2 t        |	j'                               t        |j'                               z  }|D ]  }|	j)                  |g       }|j)                  |g       }||   }t	        g |j
                  |j                  |||j                  |||j                  |j                  |j                  |j                  d|      }t        |||        |j                  Tt	        g |j
                  |j                  |j                  | | ddddd|j                  dt*              }t-        | ||       yy)a  
    This function applies offloading to groups of leaf modules in a torch.nn.Module. This method has minimal memory
    requirements. However, it can be slower compared to other offloading methods due to the excessive number of device
    synchronizations. When using devices that support streams to overlap data transfer and computation, this method can
    reduce memory usage without any performance degradation.
    Tr   r   )r<   r*   r)   r=   r>   r0   r?   r@   r,   r1   r-   r.   rA   rB   NF)r<   r*   r)   r0   r=   r>   r?   r@   r,   r1   r-   r.   rA   rB   )r   r   r   r   r;   r*   r)   r0   r,   r1   r-   r.   r  r   rQ   r  r  "_find_parent_module_in_module_dictr   r   get_GROUP_ID_LAZY_LEAFr  )ra   r   r	  r   r   r   module_dictr?   r@   parent_to_parametersrl   parent_nameparent_to_buffersrm   parent_namesparent_moduler  s                    r&   r   r     s    %(E!!//1 0i)%DEK!00 ..!'!<!<$#,,== ..$66
 	%YfE%))$/%0, v++-.KCFLijJ=fFcdG ! 8e8{K.. -44U;16 -8  6f8{K++k*11&9.4Xk*6 +0023c:K:P:P:R6SSL J)--dB7
#''b1#D)!00 ..('!'!<!<!,,== ..$66
  	%]E&I)J, }}  &!00 ..!'!<!<! $66(
  	*&/&Q) !r%   r   c                    t        j                  |       }|j                  t              $t	        ||      }|j                  |t               y y Nr   )r   r   r   r   r   r   )ra   r   r   r   r   s        r&   r  r    sJ     99&AH *+3"58t%67 4r%   c                    t        j                  |       }|j                  t              #t	        ||      }|j                  |t               t               }|j                  |t               y r  )r   r   r   r   r   r   r   r   )ra   r   r   r   r   lazy_prefetch_hooks         r&   r  r    s`     99&AH *+3"58t%678:-/NOr%   r	  c                    g }| j                         D ]s  \  }}d}|j                  d      }t        |      dkD  r7dj                  |      }||v rd}n|j	                          t        |      dkD  r7|ra|j                  ||f       u |S NFr   r   T)named_parameterssplitr   rM   popr   )ra   r	  r?   r   	parameter has_parent_with_group_offloadingatomsr  s           r&   r  r    s     J!224 
1i+0(

3%j1n((5/K;;370IIK %j1n 0tY/0
1 r%   c                    g }| j                         D ]s  \  }}d}|j                  d      }t        |      dkD  r7dj                  |      }||v rd}n|j	                          t        |      dkD  r7|ra|j                  ||f       u |S r  )named_buffersr!  r   rM   r"  r   )ra   r	  r@   r   rm   r$  r%  r  s           r&   r  r  &  s     G,,. 
+f+0(

3%j1n((5/K;;370IIK %j1n 0NND&>*
+ Nr%   r   r  c                     | j                  d      }t        |      dkD  r6dj                  |      }||v r|S |j                          t        |      dkD  r6y)Nr   r   r   )r!  r   rM   r"  )r   r  r%  r  s       r&   r  r  8  sP    JJsOE
e*q.hhuo+%			 e*q.
 r%   c           	          t               sy | j                         D ]M  \  }}t        |d      st        |j                  t
        t        f      s4t        d| dt        |       d       y )N_hf_hookzCannot apply group offloading to a module that is already applying an alternative offloading strategy from Accelerate. If you want to apply group offloading, please disable the existing offloading strategy first. Offending module: z ())	r   r   rY   r   r*  r   r   r   r\   )ra   r   r   s      r&   r   r   B  s{    "$!//1 iy*-i((+;Z*HIUUYTZZ\]abk]l\mmnp 	r%   c                     | j                         D ]4  }t        |d      s|j                  j                  t              }|2|c S  y )Nr   )r<   rY   r   r   r   )ra   r   r   s      r&   !_get_top_level_group_offload_hookr-  P  sL    ^^% -	9/0$-$=$=$F$FGX$Y!$0,,	-
 r%   c                      t        |       }|d uS rh   )r-  ra   top_level_group_offload_hooks     r&   _is_group_offload_enabledr1  Y  s    #DV#L 't33r%   c                 ^    t        |       }||j                  j                  S t        d      )Nz8Group offloading is not enabled for the provided module.)r-  r   r)   r   r/  s     r&   _get_group_onload_devicer3  ^  s1    #DV#L #/+22@@@
O
PPr%   c                 p    t        j                  | j                  d            j                         }|d d S )Nzutf-8   )hashlibsha256encode	hexdigest)rB   	hashed_ids     r&   rJ   rJ   e  s.    xw78BBDISb>r%   c                     t        |       }|yt        j                  |       }|j                  t        d       |j                  t
        d       |j                  t        d       t        | |j                         y)a|  
    Removes the group offloading hook from the module and re-applies it. This is useful when the module has been
    modified in-place and the group offloading hook references-to-tensors needs to be updated. The in-place
    modification can happen in a number of ways, for example, fusing QKV or unloading/loading LoRAs on-the-fly.

    In this implementation, we make an assumption that group offloading has only been applied at the top-level module,
    and therefore all submodules have the same onload and offload devices. If this assumption is not true, say in the
    case where user has applied group offloading at multiple levels, this function will not work as expected.

    There is some performance penalty associated with doing this when non-default streams are used, because we need to
    retrace the execution order of the layers with `LazyPrefetchGroupOffloadingHook`.
    NTr   )	r-  r   r   r   r   r   r   r   r   )ra   r0  r   s      r&   *_maybe_remove_and_reapply_group_offloadingr<  k  sv     $EV#L #+99&AH*D914@8$GF$@$G$GHr%   )Cr6  rK   
contextlibr   r   dataclassesr   enumr   typingr   r   r	   r
   r   r   safetensors.torchr   r2   utilsr   r   _commonr   hooksr   r   accelerate.hooksr   r   accelerate.utilsr   r   r   r   r   r   r  r7   r   r(   r;   r   r   r   r3   r   r   r6   r5   r   r   r   r   r  r  r   r  r   r  r  r   r-  r1  r3  rJ   r<  r$   r%   r&   <module>rG     s    	 2 !  : :   7 4 * =/ 
H	 ' 4 "B " #t 
 	D 	D 	DN& N&b8) 8v^i ^B	 & 0<u||E/B4A*.#*.x,HHOOx,ell*+x, #u||+,x, 001	x,
 #3-x, x, x, x, x, #3-x, 
x,vEHHOO =R W[ MR MRI^ MRcg MR`_Ruxx _RH] _Rbf _RD8HHOO88 "	8
 
8PHHOOPP "	P
 
P$HHOO<?H	%((

$HHOO<?H	%,,$S tCDX?Y ^a  \` ehhoo (K^B_ 4ehhoo 4$ 4
QUXX__ Q QIuxx I4 Ir%   