
    ^j#                         U d dl Z d dlmZ d dlmZmZmZ d dlZd dlm	Z
 ddlmZ e
Zeed<   esej                  j                         rd dlmZ neZ ed      Z G d	 d
      Zy)    N)	timedelta)TYPE_CHECKINGAnyTypeVar   )loggerdist)
DeviceMeshTc                   d   e Zd ZdZdedz  dedz  ddfdZededz  ddfd       Zededz  dedz  fd       Z	de
fd	Zdd
Zdej                  dej                  fdZdededeeef   fdZddej                  de
dej                  fdZdedefdZddZdedz  dej.                  ddfdZy)DistributedHelperzlA helper class to handle distributed-related operations. Notably, it does not crash when distributed is off.device_meshNcpu_group_timeoutreturnc                 Z   t         j                         xr t         j                         | _        || _        | j                  | j                         | j                  | j                        }|| j                  st        d|d      | j                  rt         j                         nd| _	        | j                  rt         j                         nd| _        ||j                         | _        |j                         | _        t         j!                  | j                  d      | _        |j%                         | _        t         j)                  | j                        }|d nt+        |      }t         j-                  |d|      | _        n#d| _        d | _        d| _        d| _        d | _        | j1                         | _        | j                  | j                  z  | _        | j                  | j                  z  | _        t9        j:                  ddgt8        j<                  d	      | _        y )
Nz.Distributed is off but received device_mesh = .r   r   )secondsgloo)ranksbackendtimeoutcpudtypedevice) r	   is_availableis_initializeddist_onr   check_device_mesh_for_cbextract_tp_mesh
ValueErrorget_rankglobal_rankget_world_size
world_sizesizetp_size	get_grouptp_groupget_global_ranktp_root_global_rankget_local_ranktp_local_rankget_process_group_ranksr   	new_groupcpu_comm_groupinfer_if_tp_driveris_tp_driverdp_rankdp_sizetorchtensorint64_cpu_int_acc)selfr   r   tp_meshtp_ranksr   s         /var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/generation/continuous_batching/distributed.py__init__zDistributedHelper.__init__)   s   ((*Dt/B/B/D& 	%%d&6&67&&t'7'78t||N?OqQRR /3ll4==?37<<$--/Q "<<>DL#--/DM'+';';DMM1'MD$!(!7!7!9D33DMMBH/7dYO`=aG"&..xY`."aDDL DM'(D$!"D"&D !335 ''4<<7$,,6 "LL!Qu{{5Q    c                     | y| j                   yd| j                   v r&| d   j                         dkD  rt        d| d      yy)z?Checks the validity of the device mesh for continuous batching.Nfsdpr   zFFSDP is not compatible with continuous batching but got device_mesh = r   )mesh_dim_namesr&   r!   r   s    r<   r   z*DistributedHelper.check_device_mesh_for_cbT   sa     %%-[///K4G4L4L4NQR4RfXcWgghijj 5S/r>   c                     | y| j                   | j                         dkD  r| S dS d| j                   v r| d   j                         dkD  r| d   S y)zJExtracts the TP mesh from the device mesh if it exists and is non-trivial.Nr   tp)rA   r&   rB   s    r<   r    z!DistributedHelper.extract_tp_mesha   se     %%-"-"2"2"4q"8;BdB;---+d2C2H2H2JQ2Nt$$r>   c                      | j                   dk(  S )Nr   )r-   r9   s    r<   r1   z$DistributedHelper.infer_if_tp_drivern   s    !!Q&&r>   c                 j    | j                   't        j                  | j                          d| _         yy)zDestroys the CPU comm group.N)r0   r	   destroy_process_grouprF   s    r<   destroy_cpu_comm_groupz(DistributedHelper.destroy_cpu_comm_groupq   s/    *&&t':':;"&D +r>   valuec                 ~    | j                   dkD  r-t        j                  || j                  d| j                         |S )zPInside each TP group, broadcasts the given value from rank 0 to all other ranks.r   F)srcasync_opgroup)r'   r	   	broadcastr+   r)   )r9   rJ   s     r<   tp_broadcast_from_rank_0z*DistributedHelper.tp_broadcast_from_rank_0w   s4    <<!NN5d&>&>VZVcVcNdr>   payload_sizestop_statusc                 (   | j                   dkD  r|| j                  d<   || j                  d<   t        j                  | j                  t        j                  j
                  d| j                         | j                  j                         \  }}||fS )zBroadcasts two information: 1. the size of the payload held by the TP driver (all other rank broadcast 0) and
        2. the requested stop status (all to all). These information are broadcasted through a MAX-reduce operation.r   r   F)oprM   rN   )r'   r8   r	   
all_reduceReduceOpMAXr0   tolist)r9   rQ   rR   s      r<   tp_all_reduce_statez%DistributedHelper.tp_all_reduce_state}   s     <<!#/Da #.Da OOD--$--2C2Ce[_[n[nOo(,(9(9(@(@(B%L+[((r>   on_cpuc                     | j                   dkD  rJ|r| j                  n| j                  }t        j	                  |t        j
                  j                  |       |S )zInside each TP group, all-reduces a tensor with the MIN op. No-op when TP is off. If the tensor is on CPU,
        it is all-reduced on the CPU comm group.r   )rT   rN   )r'   r0   r)   r	   rU   rV   MIN)r9   rJ   rZ   rN   s       r<   tp_all_reduce_minz#DistributedHelper.tp_all_reduce_min   sD     <<!+1D''t}}EOOEdmm&7&7uOEr>   objc                     | j                   dk  r|S | j                  r|gndg}t        j                  || j                  | j
                  t        j                  d             |d   S )aI  Inside each TP group, broadcasts an arbitrary picklable Python object from TP-rank 0 to all other ranks.
        Used to keep request ingress and cancellations consistent across TP workers without requiring all ranks to
        receive the same external request stream. Uses a dedicated CPU (gloo) `cpu_comm_group` for broadcast.r   Nr   )rL   rN   r   r   )r'   r2   r	   broadcast_object_listr+   r0   r5   r   )r9   r^   holders      r<   tp_broadcast_object_from_rank_0z1DistributedHelper.tp_broadcast_object_from_rank_0   si     <<1J++#$""008K8KTYT`T`afTg 	# 	
 ayr>   c                     | j                   dkD  }t        j                  j                  d      dk7  }|r|rt	        j
                  d       yyy)a  Throws a warning if TP is on and NCCL's graph mixing support was supposed to be disabled but isn't. That can
        happen if the distributed group is created before graph mixing is disabled. Typically, if the model is
        initialized before the ContinuousBatchingConfig is created.r   NCCL_GRAPH_MIXING_SUPPORT0a  NCCL_GRAPH_MIXING_SUPPORT was not set to '0' before init_process_group: performance will be harmed. Construct your `ContinuousBatchingConfig(...)` BEFORE calling `from_pretrained(tp_plan='auto')`, or set NCCL_GRAPH_MIXING_SUPPORT=0 in the launch environment.N)r'   osenvirongetr   warning)r9   tp_ongraph_mixing_not_disableds      r<   maybe_warn_nccl_graph_mixingz.DistributedHelper.maybe_warn_nccl_graph_mixing   sK     q $&JJNN3N$OSV$V!.NNM /5r>   seedmodel_devicec                    |)t        j                  dddt         j                  |      }n&t        j                  |t         j                  |      }| j	                  |      }|j                         }| j                  dk(  r|t        j                  d| d       t        j                  || j                  z          y )Nr   l    )r   r   zHFound no user-specified seed in the config. Setting the config seed to: r   )r5   randintr7   r6   rP   itemr#   r   infomanual_seedr3   )r9   rm   rn   tp_seed_tensortp_seeds        r<   set_tp_seedzDistributedHelper.set_tp_seed   s    <"]]1iU[[YefN"\\$ekk,WN66~F %%'q T\KKbcjbkklmn'DLL01r>   )r   N)F)__name__
__module____qualname____doc__r
   floatr=   staticmethodr   r    boolr1   rI   r5   TensorrP   inttuplerY   r]   r   rb   rl   r   rv    r>   r<   r   r   &   s3   v)RJ$5 )R%RV, )R[_ )RV 
kj4.? 
kD 
k 
k 
Z$%6 
:;L 
 
'D ''ell u|| ) )# )%PSUXPX/ )u|| T ell 
1 
 
2d
 2%,, 24 2r>   r   )rf   datetimer   typingr   r   r   r5   torch.distributeddistributed_distrequestsr   r	   __annotations__r   torch.distributed.device_meshr
   objectr   r   r   r>   r<   <module>r      s]    
  . .  ! 
 c  E%%2248J CLN2 N2r>   