o
    oi                     @   s   d dl mZmZmZ d dlmZmZmZmZm	Z	m
Z
 dedefddZdedeee ef fddZd	ed
ee dedefddZdS )    )AnyListTuple)SUPPORTED_NODESLeafSpecPyTreeTreeSpec_get_node_typetree_unflattenpytreereturnc                 C   sD   t | tv}|r
dS t | }t| j}|| \}}tdd |D S )z]Customized :func:`torch.utils._pytree._is_leaf` to avoid flattening containers of primitives.Tc                 s   s     | ]}t |tttfV  qd S )N)
isinstanceintfloatstr).0child r   W/home/ubuntu/.local/lib/python3.10/site-packages/lightning/pytorch/utilities/_pytree.py	<genexpr>   s    z2_is_leaf_or_primitive_container.<locals>.<genexpr>)r	   r   
flatten_fnall)r   is_leaf	node_typer   child_pytrees_r   r   r   _is_leaf_or_primitive_container   s   
r   c           
      C   sr   t | r
| gt fS t| }t| j}|| \}}g }g }|D ]}t|\}}	||7 }||	 q|t|||fS )zPCopy of :func:`torch.utils._pytree.tree_flatten` using our custom leaf function.)r   r   r	   r   r   _tree_flattenappendr   )
r   r   r   r   contextresultchildren_specsr   flat
child_specr   r   r   r      s   
r   fnvaluesspecc                    s   t  fdd|D |S )z6Utility function to apply a function and unflatten it.c                    s   g | ]} |qS r   r   )r   ir$   r   r   
<listcomp>'   s    z&_map_and_unflatten.<locals>.<listcomp>)r
   )r$   r%   r&   r   r(   r   _map_and_unflatten%   s   r*   N)typingr   r   r   torch.utils._pytreer   r   r   r   r	   r
   boolr   r   r*   r   r   r   r   <module>   s
     "