
    ;i                        S SK r S SKJr  S SKJrJrJr  SSKJr  SSK	J
r
JrJrJrJrJrJrJr   SS\S\\   4S	 jjrS
 rS rS r      SS\\\\\   4      S\\\      S\\\      S\\\\4      S\\   S\\   4S jjrg)    N)
MethodType)AnyOptionalUnion   )PartialState)calculate_maximum_sizesconvert_bytescopy_tensor_to_devicesignorant_find_batch_sizeinfer_auto_device_mapis_pippy_availablepad_input_tensorssend_to_devicenum_processes
max_memoryc                 @   US:X  a
  [        XSS9$ Ucy  [        U 5      u  pEXES   -   U-  n[        U5      nUR                  S5      u  px[        R
                  " [        U5      5      S-  nU SU 3n[        U5       V	s0 s H  oU_M     nn	[        U UUSS9n
U
$ s  sn	f )z@
Calculates the device map for `model` with an offset for PiPPy
r   F)no_split_module_classesclean_resultr    g?)r   r   r   )r   r	   r
   splitmathceilfloatrange)modelr   r   r   
model_sizesharedmemoryvalueendingi
device_maps              d/home/dmtnaga/Documents/work/airagagent/rag_env/lib/python3.13/site-packages/accelerate/inference.pygenerate_device_mapr%      s     $Ujopp4U;
 ay(M9v&S) 5<(3.81VH%).})=>)=Ai)=
>& 7	J  ?s   ?Bc                     S nU b  U  H  n[        U5      nUc  M    O   Ub+  Uc(  UR                  5        H  n[        U5      nUc  M    U$    U$ N)r   values)argskwargsfound_batch_sizeargkwargs        r$   find_pippy_batch_sizer.   <   sl    C7<+  .6]]_E7>+	 %     c                     SSK JnJnJn  [	        5       nU V	s0 s H  oUR
                  _M     n
n	U" U UUU
S9nUR                  UR                  UR                  S9nU" X5      nU$ s  sn	f )a.  
Attaches the split points to the model based on `self.device_map` and generates a `PipelineStage`. Requires passing
in needed `args` and `kwargs` as the model needs on the CPU.

Users can pass in custom `num_chunks` as an optional hyper-parameter. By default will use
`AcceleratorState.num_processes`
r   )ScheduleGPipe
SplitPointpipeline)mb_args	mb_kwargs
split_spec)device)	torch.distributed.pipeliningr1   r2   r3   r   	BEGINNINGbuild_stagelocal_process_indexr7   )r   split_pointsr)   r*   
num_chunksr1   r2   r3   statesplit_pointr6   pipestageschedules                 r$   build_pipelinerC   K   s}     QP NEGST|z333|JT	D U66u||LEU/HO Us   A(c                 T   [        5       nS nUR                  S:X  a	  U " U0 UD6nOpUR                  (       a?  [        X45      nUc  [	        S5      eXq:w  a  [        X7U5      n[        XGU5      nU " U0 UD6  O UR                  (       a  U " 5       nOU " 5         U(       a  [        U5      nU$ )Nr   z-Could not find batch size from args or kwargs)r   r   is_local_main_processr.   
ValueErrorr   is_last_processr   )forwardr=   gather_outputr)   r*   r>   outputr+   s           r$   pippy_forwardrK   e   s    NEFa$)&)		$	$0>#LMM-(L*6ZP  				'/Mr/   r<   r   example_argsexample_kwargsr=   rI   c                   ^^^^ [        5       (       d  [        S5      e[        5       n[        US5      n[        US5      nTc  UR                  mUS:X  aR  [        U TUS9n/ n[        ST5       H5  mUR                  [        U4S jUR                  5        5       5      5        M7     Xl
        [        XX4T5      mU R                  U l        U R                  U l        TU l        Xl
        UUU4S jn	[#        X5      n
Xl        Xl        U $ )a  
Wraps `model` for pipeline parallel inference.

Args:
    model (`torch.nn.Module`):
        A model we want to split for pipeline-parallel inference
    split_points (`str` or `List[str]`, defaults to 'auto'):
        How to generate the split points and chunk the model across each GPU. 'auto' will find the best balanced
        split given any model. Should be a list of layer names in the model to split by otherwise.
    no_split_module_classes (`List[str]`):
        A list of class names for layers we don't want to be split.
    example_args (tuple of model inputs):
        The expected inputs for the model that uses order-based inputs for a *single process*. Recommended to use
        this method if possible.
    example_kwargs (dict of model inputs)
        The expected inputs for the model that uses dictionary-based inputs for a *single process*. This is a
        *highly* limiting structure that requires the same keys be present at *all* inference calls. Not
        recommended unless the prior condition is true for all cases.
    num_chunks (`int`, defaults to the number of available GPUs):
        The number of different stages the Pipeline will have. By default it will assign one chunk per GPU, but
        this can be tuned and played with. In general one should have num_chunks >= num_gpus.
    gather_output (`bool`, defaults to `False`):
        If `True`, the output from the last GPU (which holds the true outputs) is sent across to all GPUs.
zEUsing `torch.distributed.pipelining` requires PyTorch 2.4.0 or later.cpuauto)r   r   c              3   <   >#    U  H  u  pUT:X  d  M  Uv   M     g 7fr'    ).0kvr"   s      r$   	<genexpr> prepare_pippy.<locals>.<genexpr>   s     $P3E41aQQ3Es   	c                  :   > [        TR                  TT/U Q70 UD6$ r'   )rK   step)r)   r*   rI   r=   rA   s     r$   rH   prepare_pippy.<locals>.forward   s     UZZ]TTTVTTr/   )r   ImportErrorr   r   r   r%   r   appendnextitemshf_split_pointsrC   rH   _original_forward__call___original_callpippy_stager   __wrapped__)r   r<   r   rL   rM   r=   rI   r>   r#   rH   model_forwardr"   rA   s        ``    @@r$   prepare_pippyrf   ~   s    B abbNE!,6L#NE:N((
v(
Tkl
q*%A$P:3C3C3E$P PQ &(5jYE#mmE >>EE(U
 w.M'MLr/   )r   NN)rP   NrR   NNF)r   typesr   typingr   r   r   r>   r   utilsr	   r
   r   r   r   r   r   r   intdictr%   r.   rC   rK   strlisttupleboolrf   rR   r/   r$   <module>rp      s      ' ' 	 	 	 _cMUVZ^:46 5;37)+/3 $$)<5d3i01< &d3i0< 5:&	<
 T#s(^,< < D><r/   