o
    }o™iQ  ã                   @   sP   d dl mZ d dlZdd„ Zdd„ Zdd„ Zdejfd	d
„Zdej	fdd„Z
dS )é    Nc                 C   sN   i }| D ] \}}t |dƒr|j||< qt |dƒr$t |jdƒr$|jj||< q|S )zw
    Extracts dtype from the input iterator
    ckpt can be module.named_parameters or module.state_dict().items()
    ÚdtypeÚdata)Úhasattrr   r   )ÚckptÚdtypesÚkeyÚval© r	   úP/home/ubuntu/.local/lib/python3.10/site-packages/nemo/lightning/pytorch/utils.pyÚextract_dtypes   s   
€r   c                 C   s0   t | tƒsJ ‚| dv rtjS | dv rtjS tjS )z<
    Convert a str precision to equivalent torch dtype.
    )Úfloat16Úfp16Ú16z16-mixed)Úbfloat16z
bf16-mixed)Ú
isinstanceÚstrÚtorchr   r   Úfloat32)r   r	   r	   r
   Údtype_from_str"   s   r   c                 C   sB   t | dƒs	J dƒ‚| j}t|tjƒr|S t|tƒrt|ƒS tdƒ‚)z/
    Extracts torch dtype from a HF config
    Útorch_dtypez*Expected config to have attr `torch_dtype`z*torch_dtype is not of type str/torch.dtype)r   r   r   r   r   r   r   Ú
ValueError)Úconfigr   r	   r	   r
   Údtype_from_hf/   s   
r   Úmodelc                 C   s
   t | dƒS )z8
    Returns true if trainer is attached to a model
    Útrainer)r   )r   r	   r	   r
   Úis_trainer_attached=   s   
r   r   c                 C   sD   t | jddƒdkr| jS t| jdƒr t | jjddƒdkr | jjS dS )aÚ  
    Extracts the automodel from a PyTorch Lightning trainer instance.

    This function checks whether the `trainer.model` is an automodel (e.g. `HFAutoModelForCausalLM`).
    It handles different distributed training strategies:

    - If no DistributedDataParallel (DDP) or Fully Sharded Data Parallel (FSDP) is used,
    `trainer.model` directly holds the automodel.
    - If DDP is used, `trainer.model.module` contains the actual automodel.
    - If FSDP is used, `trainer.model` still holds the automodel wrapped inside an FSDP structure.

    Args:
        trainer (lightning.pytorch.Trainer): The PyTorch Lightning trainer instance.

    Returns:
        nn.Module or None: The automodel if found, otherwise `None`.
    Úis_hf_modelFTÚmoduleN)Úgetattrr   r   r   )r   r	   r	   r
   Úget_automodel_from_trainerD   s
    r   )Úlightning.pytorchÚpytorchÚplr   r   r   r   ÚLightningModuler   ÚTrainerr   r	   r	   r	   r
   Ú<module>   s   