
    +jC                       S SK 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  \(       a  S SKJr  S SKJrJr  S SKrS SKrS SKr " S	 S
\R,                  5      rSS jrSS jrS rSS jrSSS jjrSS jr " S S\R,                  5      r " S S\R,                  5      r " S S\R,                  5      r  " S S\R,                  5      r! " S S\5      r"S S jr#g)!    )annotationsN)cleandoc)TYPE_CHECKING)override)ComfyExtensionio)ModelPatcher)CLIPVAEc                  <    \ rS rSrSr\S 5       r\SS j5       rSrg)MultiGPUCFGSplitNode   z
Prepares model to have sampling accelerated via splitting work units.

Should be placed after nodes that modify the model object itself, such as compile or attention-switch nodes.

Other than those exceptions, this node can be placed in any order.
c                   [         R                  " SSS[        U R                  5      [         R                  R                  S5      [         R                  R                  SSSSS9/[         R                  R                  5       /S	9$ )
NMultiGPU_WorkUnitszMultiGPU CFG Splitadvanced/multigpumodelmax_gpus      defaultminstepnode_iddisplay_namecategorydescriptioninputsoutputs)r   Schemar   __doc__ModelInputIntOutputclss    ;/home/wildlama/comfy/ComfyUI/comfy_extras/nodes_multigpu.pydefine_schema"MultiGPUCFGSplitNode.define_schema   sj    yy(-( -w'ZB
 !
 	
    c                j    [         R                  R                  XSS9n[        R                  " U5      $ )NT)reuse_loaded)comfymultigpucreate_multigpu_deepclonesr   
NodeOutput)r(   r   r   s      r)   executeMultiGPUCFGSplitNode.execute-   s+    99%X\9]}}U##r,    N)r   r	   r   intreturnio.NodeOutput	__name__
__module____qualname____firstlineno__r"   classmethodr*   r3   __static_attributes__r5   r,   r)   r   r      s/     
 
 $ $r,   r   c           	         U R                  5       n[        R                  R                  X!5      nUc  g[        R
                  " SU SU SU S35        U R                  U5        g)zJCast compute dtype to one the device supports; no-op if already supported.NzSelect Model Device: using z compute dtype on z (model weight dtype was z).)model_dtyper/   model_managementunet_manual_castlogginginfoset_model_compute_dtype)patcherdeviceweight_dtype
cast_dtypes       r)   _force_supported_compute_dtyperK   3   sd    &&(L''88NJLL.zl:LVHTmnzm{{}~##J/r,   c                    [        U R                  S5      (       d7  U R                  U R                  l        U R                  U R                  l        gg)aQ  Stash the original load/offload device on the underlying model.

Stored on patcher.model (which is shared with the input patcher), so
later "default" selections can recover the loader's original routing.
Only the first Select on a given chain writes these attrs; subsequent
deepclones inherit them onto their freshly-loaded model below.
_select_base_load_deviceN)hasattrr   load_devicerM   offload_device_select_base_offload_device)rG   s    r)   _remember_base_devicesrR   =   s?     7=="<==181D1D.4;4J4J1 >r,   c                    [        U S5      (       a5  [        US5      (       d#  U R                  Ul        U R                  Ul        ggg)zICarry the loader-original device attrs onto the freshly-deepcloned model.rM   N)rN   rM   rQ   )	src_model	dst_models     r)   _propagate_base_devicesrV   J   sB    y455giQk>l>l-6-O-O	*090U0U	- ?m5r,   c                    U R                   U:X  a  X l        U $ U R                  nU R                  US9n X l        [	        X0R                  5        [        U S5      (       a  U R                  U R                   5        U $ )a=  Return a patcher whose actual model weights live on *target_load_device*.

If *patcher* is already on *target_load_device* we just retarget the
(already-cloned) patcher's metadata in place. Otherwise we call
:meth:`ModelPatcher.deepclone_multigpu` to spawn a fresh model from
the loader's ``cached_patcher_init`` factory -- the only safe way to
move weights that may already be partially loaded onto another device.

NOTE: reusing the input patcher's model when the requested device
matches its current load_device is a deliberate fast path. Anything
that has already mutated the original model (e.g. a prior KSampler
invocation on the same model) will be observed here. This is by
design and documented on the SelectXDeviceNode docstrings -- placing
Select X Device after a node that consumes the same model is not
recommended.
)new_load_deviceregister_load_device)rO   rP   r   deepclone_multigpurV   rN   rY   )rG   target_load_devicetarget_offload_devicerT   s       r)   _retarget_patcherr]   Q   st    " 00!6I((9K(LG2I}}5w.//$$W%8%89Nr,   c                4   [        U 5        U R                  R                  nUb  UOU R                  R                  nUc  [	        XU5      $ UR
                  S:X  a2  U R                  5       (       a  U R                  SS9n Xl        Xl	        U $ [	        XU5      $ )a  Resolve the requested device and produce a patcher routed there.

For "default" we restore the loader's original load/offload pair.
For CPU we pin both load and offload to CPU (and, on a dynamic
patcher, downgrade to a plain ModelPatcher so the dynamic-only
code paths are bypassed).
For an explicit GPU we keep the loader's original offload but
target the requested load device; if that differs from the current
load device the patcher is deepcloned onto the new device.
cpuT)disable_dynamic)
rR   r   rM   rQ   r]   type
is_dynamicclonerO   rP   )rG   resolvedbase_offload_override	base_loadbase_offloads        r)   _apply_patcher_devicerh   o   s     7#66I,A,M(SZS`S`S|S|L \BB}}
 mmDm9G&!)W==r,   c                T   U R                  S5      nU(       d  gU Vs/ s H  o3R                  U:w  d  M  UPM     nn[        U5      [        U5      :w  aO  [        R                  " SU S35        U R                  SU5        [        U S5      (       a  U R                  5         gggs  snf )a9  Drop any multigpu clone whose load_device matches *primary_device*.

Without pruning, MultiGPU CFG Split would have stacked a clone on
the same device the primary now occupies (i.e. the workflow places
MultiGPU CFG Split before Select Model Device). Keeps the clone set
consistent with the new primary placement.
r0   Nz/Select Model Device: pruning MultiGPU clone on z* that now collides with the primary model.match_multigpu_clones)get_additional_models_with_keyrO   lenrD   rE   set_additional_modelsrN   rj   )r   primary_devicemultigpu_modelsmfiltereds        r)   _prune_multigpu_collisionrr      s     :::FO*N?amm~.M?HN
8}O,,F~FV  WA  B  	C##J95122'') 3 - Os
   B%B%c                  T    \ rS rSrSr\S 5       r\SS j5       r\SS	S jj5       rSr	g)
SelectModelDeviceNode   a  
Place the diffusion model on a specific device (default / cpu / gpu:N).

- "default" restores the device assigned by the loader (even after a
  prior Select Model Device call).
- "cpu" pins both the load and offload device to CPU.
- "gpu:N" pins the load device to the Nth available GPU; the offload
  device is restored to the loader's original choice.

When the requested device differs from the device the input model is
already on, a fresh model is spawned via the loader's reload factory
(cached_patcher_init) so the new patcher owns independent weights on
the new device. Loaders that don't support multigpu (no factory) will
cause the node to pass through unchanged with a warning.

If the workflow already has MultiGPU CFG Split applied and the chosen
GPU collides with one of the existing multigpu clones, that clone is
dropped so two patchers don't end up bound to the same device.

When the selected device does not exist on the current machine
(e.g. a workflow built on a 2-GPU box opened on a 1-GPU box),
the node passes the model through unchanged and logs a message
instead of failing.

NOTE: Placing Select Model Device *after* a node that has already
consumed the same model (e.g. a KSampler that ran on this model on
the original device) is not recommended -- any state the prior
consumer mutated on the original model will be observed when the
selected device matches the original (fast path). Place Select Model
Device before any consumer of the model.
c                B   [         R                  " SSS[        U R                  5      [         R                  R                  S5      [         R                  R                  S[        R                  R                  5       S9/[         R                  R                  5       /S9$ )NSelectModelDevicezSelect Model Devicer   r   rH   optionsr   )r   r!   r   r"   r#   r$   Combor/   rB   get_gpu_device_optionsr&   r'   s    r)   r*   #SelectModelDeviceNode.define_schema   su    yy'.( -w'x1G1G1^1^1`a
 !
 	
r,   c                    gNTr5   r(   rH   s     r)   validate_inputs%SelectModelDeviceNode.validate_inputs   s     r,   c                   UR                  5       n[        R                  R                  U5      nUc6  US;  a0  [        R
                  " SU S35        [        R                  " U5      $  [        X5      nUb   [        X5        [        XR                  5        [        R                  " U5      $ ! [         a:  n[        R                  " SU S35        [        R                  " U5      s S nA$ S nAff = f)NNr   z'Select Model Device: requested device '+' not available, passing through unchanged.zHSelect Model Device: cannot retarget model, passing through unchanged. ())rc   r/   rB   resolve_gpu_device_optionrD   rE   r   r2   rh   RuntimeErrorwarningrK   rr   rO   )r(   r   rH   rd   es        r)   r3   SelectModelDeviceNode.execute   s    ))CCFK.? ?LLB6(Juvw==''	()%:E *5;%e->->?}}U##  	(OOfghfiijkl==''	(s   *B. .
C28/C-'C2-C2r5   Nr   )r   r	   rH   strr7   r8   
r:   r;   r<   r=   r"   r>   r*   r   r3   r?   r5   r,   r)   rt   rt      sD    @ 
 
  
 $ $r,   rt   c                  T    \ rS rSrSr\S 5       r\SS j5       r\SS	S jj5       rSr	g)
SelectCLIPDeviceNode   a  
Place the CLIP text encoder on a specific device (default / cpu / gpu:N).

- "default" restores the device assigned by the loader.
- "cpu" pins both the load and offload device to CPU.
- "gpu:N" pins the load device to the Nth available GPU.

When the selected device does not exist on the current machine
(e.g. a workflow built on a 2-GPU box opened on a 1-GPU box),
the node passes the CLIP through unchanged and logs a message
instead of failing.
c                B   [         R                  " SSS[        U R                  5      [         R                  R                  S5      [         R                  R                  S[        R                  R                  5       S9/[         R                  R                  5       /S9$ )NSelectCLIPDevicezSelect CLIP Devicer   cliprH   rx   r   )r   r!   r   r"   Clipr$   rz   r/   rB   r{   r&   r'   s    r)   r*   "SelectCLIPDeviceNode.define_schema   su    yy&-( -f%x1G1G1^1^1`a
  
 	
r,   c                    gr~   r5   r   s     r)   r   $SelectCLIPDeviceNode.validate_inputs      r,   c                   UR                  5       n[        R                  R                  U5      nUc6  US;  a0  [        R
                  " SU S35        [        R                  " U5      $  [        UR                  U5      Ul	        [        R                  " U5      $ ! [         a$  n[        R                  " SU S35         S nAN?S nAff = f)Nr   z&Select CLIP Device: requested device 'r   zFSelect CLIP Device: cannot retarget CLIP, passing through unchanged. (r   )rc   r/   rB   r   rD   rE   r   r2   rh   rG   r   r   )r(   r   rH   rd   r   s        r)   r3   SelectCLIPDeviceNode.execute  s    zz|))CCFK.? ?LLA&Ituv==&&	k0xHDL }}T""  	kOOdefdgghijj	ks   *B 
C	%CC	r5   Nr   )r   r
   rH   r   r7   r8   r   r5   r,   r)   r   r      sC     
 
   
# 
#r,   r   c                  T    \ rS rSrSr\S 5       r\SS j5       r\SS	S jj5       rSr	g)
SelectVAEDeviceNodei  a  
Place the VAE on a specific device (default / gpu:N).

- "default" restores the device assigned by the loader.
- "gpu:N" pins the load device to the Nth available GPU; the offload
  device is set to the standard VAE offload device.

CPU is intentionally not exposed in the UI for the VAE; if a workflow
supplies "cpu" anyway (e.g. opened from another machine), the request
is dropped with a log message and the VAE is passed through unchanged.

When the selected device does not exist on the current machine
(e.g. a workflow built on a 2-GPU box opened on a 1-GPU box),
the node passes the VAE through unchanged and logs a message
instead of failing.
c                B   [         R                  " SSS[        U R                  5      [         R                  R                  S5      [         R                  R                  S[        R                  R                  5       S9/[         R                  R                  5       /S9$ )NSelectVAEDevicezSelect VAE Devicer   vaerH   rx   r   )r   r!   r   r"   Vaer$   rz   r/   rB   get_gpu_device_options_no_cpur&   r'   s    r)   r*   !SelectVAEDeviceNode.define_schema,  st    yy%,( -U#x1G1G1e1e1gh
 
 	
r,   c                    gr~   r5   r   s     r)   r   #SelectVAEDeviceNode.validate_inputs<  r   r,   c                h   [         R                   " U5      nUR                  R                  5       Ul        [        R                  R                  U5      nUc6  US;  a0  [        R                  " SU S35        [        R                  " U5      $ Ub<  UR                  S:X  a,  [        R                  " S5        [        R                  " U5      $ [        US5      (       d  UR                  Ul         [        UR                  U[        R                  R                  5       S9Ul        UR                  R$                  Ul        Uc  UR                  OUUl        [        R                  " U5      $ ! [          a:  n[        R"                  " SU S	35        [        R                  " U5      s S nA$ S nAff = f)
Nr   z%Select VAE Device: requested device 'r   r_   zLSelect VAE Device: CPU is not a supported choice, passing through unchanged._select_base_device)re   zDSelect VAE Device: cannot retarget VAE, passing through unchanged. (r   )copyrG   rc   r/   rB   r   rD   rE   r   r2   ra   rN   rH   r   rh   vae_offload_devicer   r   r   first_stage_model)r(   r   rH   rd   r   s        r)   r3   SelectVAEDeviceNode.execute@  sS    iinkk'')))CCFK.? ?LL@Hstu==%%HMMU$:LLgh==%%s122&)jjC#	&/X&+&<&<&O&O&QCK !$ 1 1080@S,,h
}}S!!  	&OObcdbeefgh==%%	&s   06E- -
F17/F,&F1,F1r5   Nr   )r   r   rH   r   r7   r8   r   r5   r,   r)   r   r     sC    " 
 
   " "r,   r   c                  @    \ rS rSrSr\S 5       r\SSS jj5       rSrg)	MultiGPUOptionsNodei^  a   
Select the relative speed of GPUs in the special case they have significantly different performance from one another.

NOTE (not registered yet, see MultiGPUExtension.get_node_list below):
The output GPUOptionsGroup is plumbed through create_multigpu_deepclones() and stored on
model.model_options['multigpu_options'] via GPUOptionsGroup.register(), but the cond
scheduler in comfy/samplers.py (calc_cond_batch_outer_multigpu) does NOT yet consult
relative_speed when distributing conds across devices; it uses a uniform conds_per_device
round-robin via next_available_device(). Before re-enabling this node, wire its
relative_speed into the scheduler (e.g. via comfy.multigpu.load_balance_devices(),
which already implements the proportional split) so the input actually affects work
distribution.
c                b   [         R                  " SSS[        U R                  5      [         R                  R                  SSSSS9[         R                  R                  SS	S
SS9[         R                  " S5      R                  SSS9/[         R                  " S5      R                  5       /S9$ )NMultiGPU_OptionszMultiGPU Optionsr   device_indexr   @   )r   r   maxrelative_speedg      ?g        g{Gz?r   GPU_OPTIONSgpu_optionsT)optionalr   )	r   r!   r   r"   r%   r$   FloatCustomr&   r'   s    r)   r*   !MultiGPUOptionsNode.define_schemam  s    yy&+( -^QA2F/#DQ		-(..}t.L 		-(//1
 	
r,   Nc                    U(       d  [         R                  R                  5       nOUR                  5       n[         R                  R	                  XS9nUR                  U5        [        R                  " U5      $ )N)r   r   )r/   r0   GPUOptionsGrouprc   
GPUOptionsaddr   r2   )r(   r   r   r   opts        r)   r3   MultiGPUOptionsNode.execute~  sW    ..88:K%++-Knn''\'a}}[))r,   r5   N)r   r6   r   floatr   zcomfy.multigpu.GPUOptionsGroupr7   r8   r9   r5   r,   r)   r   r   ^  s/     
 
  	* 	*r,   r   c                  (    \ rS rSr\SS j5       rSrg)MultiGPUExtensioni  c                6   #    [         [        [        [        /$ 7fr   )r   rt   r   r   )selfs    r)   get_node_listMultiGPUExtension.get_node_list  s      !! 	
 	
s   r5   N)r7   zlist[type[io.ComfyNode]])r:   r;   r<   r=   r   r   r?   r5   r,   r)   r   r     s    
 
r,   r   c                    #    [        5       $ 7fr   )r   r5   r,   r)   comfy_entrypointr     s     s   )rG   r	   rH   ztorch.device)rG   r	   r   )r   r	   )r7   r   )$
__future__r   r   rD   inspectr   typingr   typing_extensionsr   comfy_api.latestr   r   comfy.model_patcherr	   comfy.sdr
   r   torchcomfy.model_managementr/   comfy.multigpu	ComfyNoder   rK   rR   rV   r]   rh   rr   rt   r   r   r   r   r   r5   r,   r)   <module>r      s    "      & /0"   $2<< $>0
KV<>>*&F$BLL F$R-#2<< -#`A"",, A"H**",, **Z	
 	
r,   