o
    ̳i                  	   @   sl   d dl mZmZ d dlmZ d dlmZmZ d dl	m
Z
 dd Zdejded	eeeef  d
dfddZdS )    )OptionalUnion)nn)checkpoint_wrapperCheckpointImpl)
checkpointc                 C   s   |dkrt | tjtdddS |dkrE	 t|}|dks"td| tjdd t j	d7  _	|r9tj	| dkrCt | tjtdddS | S t
d	)
NfullF)checkpoint_implcheckpoint_fnuse_reentrantpreserve_rng_state	selectiver   zOSelective layer AC policy (every_x_layer) expects a positive integer, received _count   z]Unknown AC type or AC config. Only selective op and selective layer ac implemented currently.)ptd_checkpoint_wrapperr   NO_REENTRANTr   int
ValueErrorr   __dict__
setdefaultr   NotImplementedError)moduleac_modeac_styleevery_x_layer r   R/home/ubuntu/.local/lib/python3.10/site-packages/torchtune/training/activations.pyr      s:   		r   modelr   	ac_optionreturnNc                 C   s6   t | jD ]\}}|dv rt|||}|| j|< qdS )ac  Utility to setup activation checkpointing and wrap the model for checkpointing.

    Args:
        model (nn.Module): Model to setup activation checkpointing.
        ac_mode (str): Activation checkpointing mode. ['none', 'full', 'selective']
        ac_option (Optional[Union[int, str]]): Activation checkpointing option. If ac_mode is
            "selective", ac_option can be an integer or a string representing the number of layers
            to checkpoint. If ac_mode is "selective" and ac_option is "op", then selective op ac is run.
            If ac_mode is "none" or "full", ac_option is ignored.
    )r   r   N)	enumeratelayersr   )r   r   r   layer_idtransformer_blockr   r   r   (apply_selective_activation_checkpointingB   s   r$   )typingr   r   torchr   ;torch.distributed.algorithms._checkpoint.checkpoint_wrapperr   r   r   torch.utils.checkpointr   Modulestrr   r$   r   r   r   r   <module>   s   /