
    sg*                        d dl Z d dlZd dlZd dlZd dlmZ d dlmZmZmZm	Z	m
Z
mZmZmZ d dlmZ d dlmZmZ d dlmZmZmZmZmZmZmZ dej6                  deeef   de
ej6                     d	e
ej8                     d
eeef   defdZdej6                  fdZde
eej6                        fdZ dej6                  de
ej6                     d	e
ej8                     de!fdZ"dej6                  de	eeej6                  f      fdZ#dej6                  d	e
ej8                     de
ej6                     dedeej8                  ef   f
dZ$y)    N)partial)AnyCallableDictListSetTupleTypeUnion)_get_module_fsdp_state _override_module_mixed_precision)_construct_wrap_fn
_or_policy_Policy_post_order_apply_recursive_wrap$_run_mixed_precision_override_policy_wrap_module_cls_individuallyroot_modulepolicyignored_modulesignored_paramsroot_kwargsfsdp_fnc                    |d   }t        j                  |      }t        |        t        |t              rd||rdnd<   |j                  | ||      }|:t        | |j                  |||      }t        | |j                        }	t        |	       |j                  dd      }
t        | t        |j                               ||
       t        | ||      }t        | |       y| ||||dd}|\t        | |j                        }	t!        j"                  t$        |t#        t&        |j                  	      g
      }||d<   t        |	       t)        di || y)a?  
    Auto wraps modules in ``root_module`` 's tree according to ``policy``
    following a post-order traversal.

    Precondition: ``root_kwargs`` should contain all arguments except
    ``module``. This function accepts the kwargs dict directly since it gets
    forwarded into the post-order traversal function.
    mixed_precisionNauto_wrap_policyr   use_orig_paramsFT)moduler   wrapper_clsr   r   only_wrap_children)module_classes)policies )inspectisclass_check_nested_wrapping
isinstancer   _run_policyr   _module_classes_to_ignorer   #_warn_on_overridden_mixed_precisionget_validate_frozen_paramssetkeysr   r   	functoolsr   r   r   r   )r   r   r   r   r   r   r   
is_wrappertarget_module_to_kwargsoverridden_module_classesr   wrap_fnrecursive_wrap_kwargss                U/var/www/html/venv/lib/python3.12/site-packages/torch/distributed/fsdp/_wrap_utils.py
_auto_wrapr7      s     ""34O)J ;'&'"FJ*&(C"("4"4+#
 &&J99''# )I_FF)% 00IJ%//*;UC',,./		
 %[2I7S+w/ "*(" " %EBB%
! ""1#2#L#L	
 5;01+,EF;+;{;    c                 l    | j                         D ]!  \  }}t        |      t        d| d|         y )NzOFSDP auto wrapping requires modules to not already have FSDP applied but found z in
)named_modulesr   
ValueError)r   module_namer   s      r6   r'   r'   h   sM    *88: V!&)5**5eK=J r8   r3   c                 T    t        |       dk(  ry t        j                  d|  d       y )Nr   zvBoth mixed precision and an auto_wrap_policy were specified to FSDP, where the wrapped module has submodules of type:
zX
These modules will be wrapped as separate FSDP instacnes with mixed precision disabled.)lenwarningswarn)r3   s    r6   r+   r+   q   s7     $%*MM	==V<W X	r8   modules_to_wrapr   c                 .   t        |       }t               }|D ]  \  }}||v st        ||||      }g }	d}
g }d}|j                         D ]Z  \  }}|j                  r%|j                  |       ||j                         z  }7|	j                  |       |
|j                         z  }
\ t        |	      dkD  st        |      dkD  s| d}|r|
|z   }|d| d| dz  }n|dz  }|dz  }|d| d	|	 z  }|rt        j                  |       t        |       y
)a$  
    This checks that, given ``modules_to_wrap``, each module would manage
    parameters that are uniformly frozen or non-frozen. This uniformity
    requirement is strict for ``use_orig_params=False`` (hard error) and highly
    recommended for ``use_orig_params=True`` (user warning).
    r   z7 has both parameters with requires_grad=True and False.zi We do not recommend wrapping such modules since the gradient memory usage will be higher than expected (z numel instead of z, numel before sharding via reduce-scatter). zI FSDP does not support wrapping such modules when use_orig_params=False. z>If possible, wrap the frozen parameters with FSDP separately.
z2The following parameters have requires_grad=True:
z4
The following parameters have requires_grad=False:
N)_get_post_order_named_modulesr.   _get_managed_param_to_fqnitemsrequires_gradappendnumelr>   r?   r@   r;   )r   rA   r   r   post_order_named_modulesvisited_modulesr<   r   param_to_fqnfrozen_param_fqnsfrozen_param_numelnonfrozen_param_fqnsnonfrozen_param_numelparamfqnmsgtotal_param_numels                    r6   r-   r-   ~   s     =[I&)eO7 $*V_$4L ,.!".0 $%!*002 8
s&&(//4)U[[]:)%,,S1&%++-7&8 $%)c2F.G!.K$%\]"(:=R(R%-..@AV@W X@@C ffCXXIJ^I_ `KK\J]_ #MM#&$S/)I$*r8   returnc                 :   | h}d| fg}g }|rz|j                         \  }}|j                  ||f       |j                         D ]>  \  }}|	||vs|j                  |       |dk7  r|dz   |z   }|j                  ||f       @ |rzt	        t        |            }|S )a  
    This returns the named modules following a post-order traversal, which is a
    valid reverse topological sort. We achieve this using the reverse of a
    stack-based DFS order instead of reversing ``root_module.named_modules()``
    since the former gives the modules in registration order at each level in
    the module tree (as opposed to the reverse), which allows us to error/warn
    on the first registered module that violates the condition.

    For example, consider the following module structure:
        M(
          S1(),
          S2(
            SS1(),
            SS2(),
          ),
          S3(),
        )
    The reverse DFS order is [S1, SS1, SS2, S2, S3, M], while the reverse
    ``named_modules()`` order is [S3, SS2, SS1, S2, S1, M].
     .)poprG   named_childrenaddlistreversed)	r   rJ   stack reverse_post_order_named_modulesr<   r   child_module_namechild_modulerI   s	            r6   rC   rC      s    . #mO+EDF$
#iikV(//f0EF/5/D/D/F 	@+|#?2##L1"$(3c(9<M(M%/>?	@   $H-M$NO##r8   module_to_wraprJ   root_prefixc                    i }t        j                  | |fg      }|j                  |        |r|j                         \  }}|j	                  d      D ]  \  }}	|	|vs|dk(  r|n|dz   |z   }
|
||	<     |j                         D ]@  \  }}|	||vs|j                  |       |dk(  r|n|dz   |z   }|j                  ||f       B |r|S )a&  
    This returns a dict that maps managed parameter to its FQN for the given
    ``module_to_wrap``. The dict's keys are exactly the parameters that would
    be managed by the module, where this is achieved by calling this function
    on the modules to wrap in reverse topological order, destructively updating
    ``visited_modules``, and not traversing into those modules. The FQNs are
    prefixed from the root (via ``root_prefix``) to be more informative.

    NOTE: This function is meant to be called pre-wrapping and iteratively in
    reverse topological order to cover the full module tree. This differs from
    the ``_get_param_to_fqn()`` function meant to be called post-wrapping and
    on the full module tree in one shot. Given those differences, we do not try
    to unify the two.
    F)recurserV   rW   )collectionsdequerZ   popleftnamed_parametersrY   rG   )ra   r   rJ   rb   rK   queuer   prefix
param_namerP   rQ   r_   r`   child_prefixs                 r6   rD   rD      s
   ( -/L<=>E'
!'!8!8!8!G 	*JN*$*bLjfslZ6O&)U#	* 06/D/D/F 
	;+|#?2##L1 | &#(99 
 lL9:
	; " r8   )%re   r0   r%   r?   r   typingr   r   r   r   r   r	   r
   r   torch.nnnn$torch.distributed.fsdp._common_utilsr   r   torch.distributed.fsdp.wrapr   r   r   r   r   r   r   Module	Parameterstrr7   r'   r+   boolr-   rC   rD   r$   r8   r6   <module>rv      s        E E E   L<L<(G#$L< ^L< %	L<
 c3hL< L<^		 
"4		?3
2*2*^2* %2* 	2*j'$'$	%RYY
 '$T)II)%) ^) 	)
 
",,
)r8   