
    Pi`                        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	 d dl
mZ d dlZ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	lmZ d d
lmZ d dlmZmZmZmZmZm Z  d dl!m"Z" d dl#m$Z$ d dl%m&Z& d dl'm(Z( d dl)m*Z*m+Z+ d dl,m-Z- d dl.m/Z/ d dl0m1Z1m2Z2m3Z3 d dl4m5Z5 d dl6m6Z6  e j7        d          Z8 G d de/          Z9ej:        deddfd            Z;e<dk    r e j=         e;                       dS dS )    N)partial)AnyDictListOptionalUnion)warn)
DictConfig
ListConfig)nn)destroy_process_groupinit_process_group)	Optimizer)StatefulDataLoader)StatefulDistributedSampler)config
generationmodulesrlhftrainingutils)_get_component_from_path)ConcatDataset)generate)batch_shaped_correctness_reward)	GRPOStatsGRPOTrajectory)local_kv_cache)FTRecipeInterface)disable_dropoutDummyProfilerPROFILER_KEY)get_lr)tqdmDEBUGc                      e Zd ZdZdeddfdZdedeeef         fdZ	dedeeef         fd	Z
d
eeef         ddfdZdeddfdZdee         dededee         fdZ	 d2dee         deej        j        ef         fdZ	 d2dedededeeef         deeef         deee                  deej        ej        f         fdZ	 d2dedeeeef                  dee         fdZ	 d2dededed ed!eeeef                  defd"Zd#eddfd$Z d%ej!        d&ee         de"fd'Z#d%ej!        d&ee         de"fd(Z$d)e"d*ede%fd+Z&d3d,Z'd)e"d-e%ddfd.Z(d3d/Z)d)e"d0e*e%         ddfd1Z+dS )4!FullGRPOFinetuneRecipeDistributeda[  
    Full finetuning recipe for dense transformer-based LLMs such as Llama2, trained with GRPO. This recipe supports
    distributed training and can be run on a single node (1 to 8 GPUs).

    Features:
        - FSDP. Supported using PyTorch's FSDP APIs. CPU offload of parameters, gradients, and optimizer states
            is supported via ``fsdp_cpu_offload``. Resharding of parameters after the forward pass is
            disabled for faster generation (corresponding to FULL_SHARD sharding strategy).
            DDP is currently not supported. Training on CPU is not supported.

        - Activation Checkpointing. This can be controlled using the ``enable_activation_checkpointing``
            flag. Activation checkpointing helps reduce the memory footprint since we no longer keep
            activations in memory and instead recompute them during the backward pass. This is especially
            helpful for larger batch sizes when you're memory constrained. But these savings in memory
            come at the cost of training performance. In most cases training can slow-down quite a bit as
            a result of this activation recomputation.

        - Precision. Full fp32 and bf16 training are supported. Precision is controlled using the ``dtype``
            flag. When ``dtype=bf16``, all activations, gradients and optimizer states are in bfloat16. In
            most cases this should halve the memory footprint of full precision (fp32) training, without
            loss in model quality (will depend on the model, training data and other settings). For
            GPUs which do not support bfloat16, we fall back to fp32. Mixed precision training and fp16
            precision are currently not supported.

        - Checkpointing. Model weights are checkpointed both at the end of each epoch and at the end of
            training. Optimizer state and recipe state (seed, total_epochs, number of epochs run etc) are
            only saved at the end of a given epoch and used in case of resuming training.

            Resuming training is controlled by the ``resume_from_checkpoint`` flag. Mid-epoch checkpointing is
            currently not supported.

            For more details on the checkpointer, please take a look at
            our checkpointer deepdive (https://pytorch.org/torchtune/main/deep_dives/checkpointer.html).

        - Logging. Terminal, Disk, WandB and TensorBoard are all supported.

        - Gradient Clipping. Gradient clipping is supported using the ``clip_grad_norm`` flag. By default,
            ``clip_grad_norm`` is set to ``None``. If you only want to log the grad norm, you can set
            ``clip_grad_norm='inf'``.

    For a full list of example configs for this recipe, run ``tune ls`` on the command line. Each config
    has example commands for how to kick-off training.

    Args:
        cfg (DictConfig): OmegaConf object parsed from yaml file

    Raises:
        ValueError: If ``dtype`` is set to fp16.
        RuntimeError: If ``dtype`` is set to bf16 and the hardware does not support bf16.
        RuntimeError: If ``left_pad_sequence`` is set as the data collator.
    cfgreturnNc                 R   t          j        |j                  | _        t	          j        |j        | j                  | _        |j        }| j        t          j	        k    rt          d          |j        | _        |                    dd          | _        |                    dd          | _        | j        r1| j        j        dk    r!t"                              d           d| _        |                    d	d          | _        t	          j        || j        
          | _        t-          | j                   t          j                    \  }}|| _        || _        |dk    | _        |j        | _        |                    dd           | _        |                    dd          | _        t	          j        |j                   | _         |j!        | _"        d| _#        d| _$        d| _%        d| _&        t          j'        | j                  (                    | j                   | _)        d S )NdevicezVfull fp16 training is not supported with this recipe. Please use bf16 or fp32 instead.log_every_n_steps   log_peak_memory_statsFcudazplog_peak_memory_stats was set to True, however, training does not use cuda. Setting log_peak_memory_stats=False.fsdp_cpu_offload)offload_ops_to_cpur   clip_grad_normenable_activation_checkpointing)seed)*r   
get_devicer,   _devicer   	get_dtypedtype_dtypetorchfloat16
ValueError
output_dir_output_dirget_log_every_n_steps_log_peak_memory_statstypeloginfor1   get_distributed_backenddistributed_backendr   get_world_size_and_rankrank
world_size_is_rank_zeroresume_from_checkpoint_resume_from_checkpoint_clip_grad_norm _enable_activation_checkpointingset_seedr5   epochstotal_epochsglobal_step
_steps_run_total_steps_epochs_run	Generatormanual_seed_rng)selfr(   device_typerJ   rI   s        ~/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/recipes/dev/grpo_full_finetune_distributed.py__init__z*FullGRPOFinetuneRecipeDistributed.__init__X   s   'sz:::(4<HHHj;%-''h  
 >"%''*=q"A"A&)gg.Eu&M&M#& 	04<+<+F+FHH C   +0D' #(:E B B#+#CD,A$
 $
 $
  	43444 8::
D	$!QY (+'A$"ww'7>> 14-u1
 1
- %38444	JODL11==diHH			    cfg_checkpointerc                     t          j        || j                  | _        | j                                        }| j        r|                     |           |S )z
        Extract the checkpoint state from file and validate. If resume_from_checkpoint
        is True, this also includes the recipe state.
        rL   )r   instantiaterM   _checkpointerload_checkpoint_update_recipe_state)rZ   r_   checkpoint_dicts      r\   rd   z1FullGRPOFinetuneRecipeDistributed.load_checkpoint   sb    
 $/#'#?
 
 
 ,<<>>' 	7%%o666r^   cfg_ref_checkpointerc                 n    t          j        |d          | _        | j                                        }|S )zP
        Extract the reference checkpoint state from file and validate.
        Fra   )r   rb   _ref_checkpointerrd   )rZ   rg   ref_checkpoint_dicts      r\   load_ref_checkpointz5FullGRPOFinetuneRecipeDistributed.load_ref_checkpoint   s@     "(!3 "
 "
 "
 #4DDFF""r^   	ckpt_dictc                    	 |t           j                 | _        | j                            |t           j                            | j        |t           j                 k    r:t          d|t           j                             |t           j                 | _        | j	        |t           j
                 k    rt          d| j	                    dS dS # t          $ r}t          d          |d}~ww xY w)z;
        Updates the recipe state from checkpoint.
        zWConfig value for seed does not match the checkpoint value, using the checkpoint value: )messagez[Config value for total_epochs does not match the checkpoint value, using the config value: zCheckpoint does not contain the required keys needed for updating recipe state. Are you sure you passed in the right recipe checkpoint?N)r   
EPOCHS_KEYrV   rY   	set_stateRNG_KEYr5   SEED_KEYr	   rR   TOTAL_EPOCHS_KEYKeyError)rZ   rl   es      r\   re   z6FullGRPOFinetuneRecipeDistributed._update_recipe_state   s)   	()<=DI	(*: ;<<< yIh&7888V7@AR7SV V    &h&78	  Ih.G$HHHG373DG G      IH  	 	 	J  	s   C	C 
C.C))C.c           	         | j         rt          j                     | j        r8t	          j        |j                  | _        | j                            |           | 	                    |j
                  }|                     |j                  }|                    dd          | _        |                     |j        | j        |                    dd          | j         |t          j                 |t          j                           \  | _        | _        t	          j        |j                  | _        |                     |j        | j        r|t          j                 nd          | _        t	          j        |j                  | _        | j        r t          j        | j        | j        	           t?          j         tB          d
           |                    dd          }| "                    |j#        |j$        |j%        || j        r|t          j&                 nd          | _'        tQ          | j'                  | _)        | j*        | j)        z  | _+        | ,                    |                    dd          | j-        | j)        z  | j+        dz
            | _.        | /                    |                    t`          d                    | _1        |j2        | _2        |j3        | _4        |j5        | _6        |j7        | _8        |j%        | _%        |j9        | _:        |j;        | _<        |j=        | _>        |j?        | _@        |                    dd          r6|jA        }| j        jB        |vr t          d| j        jB         d| d           n3t          | j        d          st          d           g }n| j        jE        }t          jG        || jH                  | _I        dS )z
        Setup the recipe. This includes training state (if resume_from_checkpoint is True),
        model, tokenizer, loss, optimizer, lr scheduler, sampler, and dataloader.
        )r_   )rg   compileFcustom_sharded_layersN)	cfg_modelr4   rx   r1   model_state_dictref_model_state_dict)cfg_optimizeropt_state_dictverbosezLoss is initialized.
collate_fnz)torchtune.dev.grpo.data.padded_collate_rl)cfg_datasetshuffle
batch_sizer   dataloader_state_dictlr_schedulerr.   )cfg_lr_schedulernum_training_steps
last_epochstop_token_idsztokenizer eos_id (z) is not in stop_token_ids (z().This may lead to unexpected behaviour.stop_tokenszkNo stop tokens defined in tokenizer, and no stop_token_ids provided. This may lead to unexpected behaviour.r+   )Jr1   r   set_torch_num_threadsrK   r   rb   metric_logger_metric_logger
log_configrd   checkpointerrk   ref_checkpointerr@   _compile_setup_modelmodelrO   	MODEL_KEY_model
_ref_model	tokenizer
_tokenizer_setup_optimizer	optimizerrM   OPT_KEY
_optimizerloss_loss_fncompile_lossr   log_rank_zerorD   _setup_datadatasetr   r   DATALOADER_KEY_dataloaderlen_steps_per_epochrV   rS   _setup_lr_schedulerrR   _lr_scheduler_setup_profilerr"   	_profilergrpo_samplestemperature_temperaturetop_k_top_kmax_generated_tokens_max_generated_tokensforward_batch_size_forward_batch_size
ppo_epochs_ppo_epochssave_every_n_epochs_save_every_n_epochs	num_stepsrU   r   eos_idr	   hasattrr   r;   tensorr7   _stop_token_ids)rZ   r(   rf   rj   collate_namer   s         r\   setupz'FullGRPOFinetuneRecipeDistributed.setup   s   
   	-*,,, 	0"("4S5F"G"GD **3///..@P.QQ"66!$!5 7 
 
 	511'+'8'8i,0,Q"%''*A4"H"H!2,X-?@!4X5G!H (9 (
 (
$T_ !,S];;//- / 011 0 
 
 *3844= 	M!$-9KLLLLC!7888 wwE
 
  ++K~# / 788 , 

 

& !$D$4 5 5+d.CC "55 WW^T::#043HH'!+ 6 
 
 --cgglD.I.IJJ  ,Oi%(%=".#&#9 >$'$;!M77#U++ 	= /N%^;;=)? = =]k = = =  
 4?M:: = B   "$!%!<$|N4<PPPr^   r   r   r   c                     |#| j         rt                              d           dS | j        }t	          j        ||||          }| j         rt                              d           |S )a  
        Set up the learning rate scheduler based on the provided configuration.
        It supports both standard optimization and optimizer-in-backward cases.

        Args:
            cfg_lr_scheduler (Optional[DictConfig]): The learning rate scheduler configuration.
            num_training_steps (int): The total number of training steps.
            last_epoch (int): The index of the last epoch.

        Returns:
            lr_scheduler (Optional[Optimizer]): The learning rate scheduler.
        NzDNo learning rate scheduler configured. Using constant learning rate.)r   r   z'Learning rate scheduler is initialized.)rK   rD   rE   r   r   rb   )rZ   r   r   r   r   r   s         r\   r   z5FullGRPOFinetuneRecipeDistributed._setup_lr_scheduler;  s    $ #! Z   4O	 )1!	
 
 
  	@HH>???r^   cfg_profilerc                    |t          ddi          }|                    dd          d|d<   n#|                    d          dk    s
J d            t          j        |          \  }}t	          j        t          d|            | j        rJ|                    dd          | _        |d         r'|d	         | _	        |d
         | _
        |d         | _        |S )a  
        Parses the `profiler` section of top-level `cfg` and sets up profiler

        Args:
            cfg_profiler (Optional[DictConfig]): ``profiler`` section of the top-level ``cfg`` (the main config passed to
                `recipe.main`). Default None.

        Returns:
            profiler: Union[torch.profiler.profile, DummyProfiler] - DummyProfiler is a nullcontext with no-op methods
            for `start`, `stop`, and `step` that can be used in place of `torch.profiler.profile` if profiler is not enabled such
            that the instrumented training loop does not need to be changed profiling is disabled.

        The profiler config can be provided in configs under the `profiler` key with the following layout:

        .. code-block:: yaml
            profiler:
                enabled: bool

                #Output directory of trace artifacts
                output_dir: str

            #`torch.profiler.ProfilerActivity` types to trace
            cpu: bool
            cuda: bool

                #Trace options
                profile_memory: bool
                with_stack: bool
                record_shapes: bool
                with_flops: bool

            # `torch.profiler.schedule` options:
            # wait_steps -> wait, warmup_steps -> warmup, active_steps -> active, num_cycles -> repeat
            wait_steps: int
            warmup_steps: int
            active_steps: int
            num_cycles: int
        NenabledF_component_z'torchtune.training.setup_torch_profilerzdOnly torch profiler supported currently: component must be `torchtune.training.setup_torch_profiler`z& Profiler config after instantiation: profile_memory
wait_stepswarmup_stepsactive_steps)r
   r@   r   rb   r   r   rD   rK   profiler_profile_memoryprofiler_wait_stepsprofiler_warmup_stepsprofiler_active_steps)rZ   r   profilerprofiler_cfgs       r\   r   z1FullGRPOFinetuneRecipeDistributed._setup_profilerc  s   T %y%&899L M4008*SL''   //<= = =u= = = "(!3L!A!A,H,HH	
 	
 	
  	J+7+;+;<Le+T+TD(I& J+7+E(-9.-I*-9.-I*r^   ry   r4   r1   rz   r{   rx   c                    t          j        t          d           t          j                    }t          j        | j                  5  t          j	        d          5  t          j        |          }t          j        |          }	ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   |	                                 |	                                D ]	}
d|
_        
| j        r6t          j        || j                   t          j        |	| j                   |r!t          j        |t&          j        h           t+          t
          j        |          g}t          j        |||d           t          j        |	||d	           t          j        | j                  5  | j        5  |                                D ]&}t3          |d
          r|                                 '|	                                D ]&}t3          |d
          r|                                 '	 ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   t          j        ||| j        d	|           t          j        |	|| j        d	|           t          j        |           t          j        |	           t          j        t          dt          j                    |z
  dd           | j        r.t          j        | j                  }t          j        |           t?          |           t?          |	           t          j         !                                 ||	fS )aX  
        Model initialization has some important considerations:
           a. To minimize GPU peak memory, we initialize the model on meta device with
              the right dtype
           b. All ranks calls ``load_state_dict`` without peaking CPU RAMs since
              full state dicts are loaded with ``torch.load(mmap=True)``
        zIFSDP is enabled. Instantiating model and loading checkpoint on Rank 0 ...metaNFr~   )auto_wrap_policy)names_to_match)r   shard_conditionscpu_offloadreshard_after_forwardT	rope_init)strictr   z0Instantiating model and loading checkpoint took .2f secsr+   )"r   r   rD   timeperf_counterr   set_default_dtyper:   r;   r,   r   rb   eval
parametersrequires_gradr   compile_modelrK   set_activation_checkpointingr   TransformerSelfAttentionLayerr   get_shard_conditionsshard_modelr7   r   r   load_from_full_model_state_dict!validate_no_params_on_meta_deviceget_memory_statslog_memory_statsr    distributedbarrier)rZ   ry   r4   r1   rz   r{   rx   
init_startr   	ref_modelpfsdp_shard_conditionsmmemory_statss                 r\   r   z.FullGRPOFinetuneRecipeDistributed._setup_model  s   " 	W	
 	
 	
 &((
'44 	6 	6el66J6J 	6 	6&y11E*955I	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	%%'' 	$ 	$A#AOO= 	J"5$2DEEEE"9d6HIIII* 	1)N(O    -4  !
 	2("'		
 	
 	
 	
 	2("&		
 	
 	
 	
 '44 	" 	"dl 	" 	"]]__ " "1k** "KKMMM&&(( " "1k** "KKMMM"	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	0L(	
 	
 	
 	
 	0 L(	
 	
 	
 	
 	2599929===jt?P?R?RU_?_jjjj	
 	
 	
  	4#4DLIIIL%l333	""" 	!!###ism   B()BB(B	B(B	B((B,/B,*I2A7H6*I6H:	:I=H:	>IIIr|   r}   c                     t          j        || j                                                  }|r!t	          j        | j        ||| j                   t          j        t          d           |S )NzOptimizer is initialized.)
r   rb   r   r   r   #load_from_full_optimizer_state_dictr7   r   r   rD   )rZ   r|   r}   r   s       r\   r   z2FullGRPOFinetuneRecipeDistributed._setup_optimizer  sm    
 &}dk6L6L6N6NOO	 	8	   	C!<===r^   r   r   r   r   r   c           	          t          |t                    r fd|D             }t          |          }nt          j        | j                  }t          |          }t          | j         j	        | j
                  }t          |||t          | j        j                  d          }	|$|	                    |           t          |	           |	S )z
        All data related setup happens here. Currently this recipe only supports the
        DistributedSamplers with Map-style Datasets which fit into memory. Other samplers,
        iterable datasets and streaming datasets are not supported.
        c                 D    g | ]}t          j        |j                  S  )r   rb   r   ).0single_cfg_datasetrZ   s     r\   
<listcomp>zAFullGRPOFinetuneRecipeDistributed._setup_data.<locals>.<listcomp>9  s9       & "#5tGG  r^   )datasets)num_replicasrI   r   r5   )padding_idxT)r   r   samplerr   	drop_last)
isinstancer   r   r   rb   r   r   r   rJ   rI   r5   r   r   pad_idload_state_dictlist)
rZ   r   r   r   r   r   r   dsr   
dataloaders
   `         r\   r   z-FullGRPOFinetuneRecipeDistributed._setup_data*  s    k:.. 	B   *5  H 111BB#KAAB .j99
,
 
 
 (! $ 6   
 
 

 !,&&'<=== r^   epochc                    i }|dz   | j         k     }t          j        t          d           t	          j                    }t          j        | j        | j	        | j
                  }t          j        t          dt	          j                    |z
  dd           |rt	          j                    }t          j        t          d           t          j        | j        | j        | j	        | j
                  }t          j        t          dt	          j                    |z
  dd           nd	}| j	        r t	          j                    }|                    t          j        |i           |r|                    t          j        |t          j        | j        t          j        | j        t          j        | j         t          j        | j                                        t          j        | j                                        i           | j                            |||
           t                              dt	          j                    |z
  dd           t<          j                                          d	S )a  
        Checkpoint the state of the recipe. The constructed checkpoint state dict
        contains the following information:
        - Model weights with key training.MODEL_KEY
        - Relevant recipe state if training is not complete

        Checkpointer will save the model weights and recipe state in
        different checkpoint files. To correctly resume training from an intermediate checkpoint,
        the model weights and recipe state must be provided.
        r.   zOSaving checkpoint. This may take some time. Retrieving full model state dict...r+   z#Getting full model state dict took r   r   zGetting optimizer state dict...z"Getting optimizer state dict took N)r  intermediate_checkpointzSaving checkpoint took )!rR   r   r   rD   r   r   r   gather_cpu_state_dictr   rK   r7   get_full_optimizer_state_dictr   updater   r   rr   r5   ro   rV   rs   rq   rY   	get_stater   r   
state_dictrc   save_checkpointrE   r;   r   r   )rZ   r  rf   r  startcpu_state_dictr}   s          r\   r  z1FullGRPOFinetuneRecipeDistributed.save_checkpoint_  sp    "'!)d.?"?]	
 	
 	
 !## "7K<
 
 
 	X$2C2E2E2MXXXX	
 	
 	

 # 	"%''E%FGGG%C"|	  N [T5F5H5H55P[[[[   
 "N
  	W%''E""H$6#GHHH ' 
&& (. )49 +T-= 143D ($)*=*=*?*? /1A1L1L1N1N	 	 	 ..(? /   
 HHUt/@/B/BU/JUUUUVVV!!#####r^   	input_idsanswersc                 v   |j         \  }}| j        }|dddddf                             d|d          }|                    ||z  d          }t	          | j        ||z  | j        | j        || j        z             5  t          | j        || j        | j
        | j        | j        j        | j        | j        j        d	  	        \  }}ddd           n# 1 swxY w Y   t           j                                         t&          j                            | j                   t           j                                         |dd|df                                         }	|| j        j        k    }
t3          j        |
          }t3          j        |
          }~
|                     |||          }|dd|dz
  df         }t9          j        ||	| j
                  }~t           j                                         |                     |||          }t9          j        ||          }t9          j        ||	| j
                  }~t           j                                         t9          j         |	| j!        | j        j                  \  }}	|	                    ||d          }	tE          | j        |	|          \  }}|#                    | j                  }|#                    | j                  }||$                    dd	          z
  |%                    dd	          d
z   z  }|                    ||z            }~	t           j                                         t'          j&        |          }d||<   d||<   tO          ||||                    ||z            |                    ||z            |||||
  
        S )a  
        Generates a trajectory given the current policy model, the reference policy model, the reward function,
        and batch of inputs. This is done over the following steps:

        1: Generate responses, and logits corresponding to the responses using the current policy,
            generating (query, response) pairs.
        2. Estimate logprobs of the generated responses using the current policy.
        3. Compute rewards and successes for the generated responses.
        4. Estimate advantages using GRPO.
        5. Replace any tokens in the response after the first stop token (usually EOS token) with padding,
            producing truncated responses.

        Args:
            input_ids (torch.Tensor): tensor of input token IDs with shape [b, seq_length]
            answers (List[str]): list of answers corresponding to the input_ids

        Returns:
            Trajectory: An instance of :class:`~torchtune.rlhf.GRPOTrajectory` comprising
                the current trajectory.
        N)r   r   r,   r9   decoder_max_seq_lenF)	r   promptr   r   r   r   rngr   return_logits	input_posmaskr.   T)keepdimg-C6?      ?)
query_responseslogprobsref_logprobsrewards	successes
advantagesmasksposition_idsresponse_padding_masksseq_lens)(shaper   expandreshaper   r   r7   r:   r   r   r   r   r   r   rY   r   r;   r   r   r   _distributedrecursive_reshardr0   empty_cachecloner   !get_causal_mask_from_padding_mask"get_position_ids_from_padding_maskr   batched_logits_to_logprobsr   truncate_sequence_for_logprobs%truncate_sequence_at_first_stop_tokenr   r   tomeanstdget_unmasked_sequence_lengthsr   )rZ   r  r  r   context_length	grpo_sizebatch_input_idsr  _	responsesquery_response_padding_masksr!  r"  logitsr  
ref_logitsr  r#  r  r  r   r$  s                         r\   generate_trajectoryz5FullGRPOFinetuneRecipeDistributed.generate_trajectory  s#   . &/_"
N%	#AAAtQQQJ/66r9bII)11*y2H"MM +!I-<+ .1K K
 
 
 	 	 "*k&%)%? -k-I O7#
" 
" 
"OQ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	& 	!!###//<<<
   #AAA~$67==??	'6$/:P'P$ <(
 
 "D(
 
 )_5QQ >A-///0269dFWXX
    __|% % 
 

 8^TT
6	4#4
 
 
    6t+T_-C
 
	
" %%j)R@@	<OY
 
 **T\**LL..	Q = ==KK4K((4/

  ''
Y(>??

   9:PQQ ,/'(/2+,+%OOJ$:;;''
Y(>??!%#9
 
 
 	
s   =A	CCCc                    g }t          j                    5  t          d| j        | j                  D ]}|||| j        z            }|||| j        z            }t           j                                         |                    |                     ||                     t           j                                         	 ddd           n# 1 swxY w Y   t          t          t           j        t          |            S )a  
        Generates a ``self.batch_size`` batch of trajectories using `self._forward_batch_size` batch sizes.
        See ``generate_trajectory`` for more details.

        Args:
            input_ids (torch.Tensor): tensor of input token IDs with shape [b, seq_length]
            answers: (List[str]): list of answers corresponding to the input_ids

        Returns:
            Trajectory: An instance of :class:`~torchtune.rlhf.Trajectory`, comprising
                the current trajectory.
        r   N)r;   no_gradranger   r   r0   r*  appendr=  r   mapcatzip)rZ   r  r  trajectoriesbatch_startr7  batch_answerss          r\   generate_trajectory_batchedz=FullGRPOFinetuneRecipeDistributed.generate_trajectory_batched9  s=    .0]__ 	) 	)$Q9QRR ) )"++0H"HH# !(+0H"HH! 
&&(((##,,_mLL   
&&(((()	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) s59c<.@AABBs   B(CCC
trajectoryr5  c                    t           j                                         |                     |j        |j        |j                  }t          j        ||          }t          j	        ||j        dd|df         | j
        d          }d||j        <   ~t           j                                         |                     |j        ||j        |j        |j                   \  }}}}}	t           j                                         |                                 t          j                    5  d||j        z
                      d          z                                  }
ddd           n# 1 swxY w Y   t)          |||||	|
          S )	a  
        Perform a single GRPO optimization step over a batch of trajectories and corresponding advantages and returns.

        Args:
            trajectory (Trajectory): a batch of trajectories
            context_length (int): input ids sequence length

        Returns:
            GRPOStats: An instance of :class:`~torchtune.rlhf.PPOStats`, a NamedTuple containing:
               - loss (torch.Tensor): The total PPO loss.
               - ratios (torch.Tensor): The ratio between the current and old policy probabilities.
               - clipfrac (torch.Tensor): The fraction of ratios that were clipped.
               - approx_policy_kls: Average estimated KL divergence between the policy before and after the optimisation step.

        r  Nr.   )
chunk_sizer  )padding_masksg      ?   )r;   r0   r*  r   r  r"  r!  r   r/  r.  r   r#  r   r  r  r   backwardr?  powr2  r   )rZ   rI  r5  	pi_logitspi_logprobsr   policy_losskl_lossratiosclipfracapprox_policy_klss              r\   	grpo_stepz+FullGRPOFinetuneRecipeDistributed.grpo_stepX  s   , 	
   KK& -!   
 
	 7	>RR	5&qqq.//'9:	
 
 
 :=J56
    8<}}#!%<< 8E 8
 8
4k7FH 	
   ]__ 	 	{Z%88==a@@@dff 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	
 
 
 	
s   ,3E++E/2E/c                 z   t          j                     | j                                         d}d}| j                                         t          | j        | j                  D ]<}t          | j
        | j                   }| j        j                            |           t          | j                  D ]\  }}| j        rC|dk    r=| j        r6|| j        | j        z   k    r#t&          j        j                                         |d         }|d         }|                    | j                  }|j        \  }	}
|                     ||          }t&          j                                         g }t          | j                  D ]$}	|                     ||
          }|                    |           | j         Ot&          j!        j"        #                    | j$        %                                tM          | j                             }t&          j                                         | j        '                                 | j                            d	           t&          j                                         | xj(        d
z  c_(        | j)        | j)        '                                 &| xj*        d
z  c_*        | j*        | j+        z  dk    rUi }tY          | j                  |d<   |||d<    | j-        |t]          t_          t&          j0        tc          |            fi | | 2                    ||           |3                    d
           | j*        | j4        k    rd} n| xj        d
z  c_        | j        | j5        z  dk    r| 6                    |           |r dS >| j        7                                 dS )z)
        The core training loop.
        NF)totaldisabler   tokensr  )max_normT)set_to_noner.   lr	grad_norm)8r   cleanup_before_trainingr   	zero_gradr   r  r@  rV   rR   r$   r   rK   r   r   	set_epoch	enumerater   r   r   r;   r0   memory_record_memory_historyr1  r7   r%  rH  r   r   r   rW  rA  rN   r   r   clip_grad_norm_r   r   floatsteprS   r   rT   rA   r#   log_metricsr   rB  stackrD  cleanup_after_stepr  rU   r   r  stop)rZ   r_  training_completed
curr_epochpbaridxbatchr[  r  r8  r5  rI  
grpo_stats
step_statsextra_metricss                  r\   trainz'FullGRPOFinetuneRecipeDistributed.train  s   
 	(*** 	!!### 	" 0$2CDD E	 E	Jd3AS=STTTD$..z:::'(899 < <
U &?"a4 (t7$:TTTTJ%<<>>>x	*4<00$*L!>!==fgNN
!))+++.0
t/00 2 2A!%
N!K!KJ%%j111+7$)HN$B$B K2244%*4+?%@%@ %C % %	 %--///O((***O--$-???%--///$$)$$)5*//1111$?T%<<AA$&M*0*A*AM$' ,5>k2$D$"!3u{C4D#E#EF  (   ''
J???A?d&777)-&E 8 !$";;q@@$$Z000!  	r^   rr  c                    |j                                         }t          j                            |dt          j        j        j                   |j                                        }t          j                            |dt          j        j        j                   |||j        	                    d          
                                |j                                        |j                                        |j                                        |j                                        |j                                        |j                                        |j                                                                        d
|}| j        j        dk    r4| j        r-|                    t/          j        | j                             | j        r#| j                            || j                   dS dS )	zW
        Log metrics and statistics for the current step to the metric logger.
        r   )dstopr  )
r  r  num_stop_tokensr   rR  rS  rU  rT  approx_policy_klresponse_lengthsr0   r+   )rh  N)r  r2  r;   r   reduceReduceOpAVGr  r#  anysumr   rR  rS  rU  rT  rV  r$  rg  r7   rC   rB   r  r   r   rK   r   log_dictrS   )rZ   rI  rr  extrasr  r  r  s          r\   ri  z-FullGRPOFinetuneRecipeDistributed.log_metrics  s    $))++  aE4E4N4R SSS(--//	  e6G6P6T UUU ")@DDRHHLLNNO((**%16688!)..00"+0022 ',,.. * < A A C C * 3 9 9 ; ; @ @ B B
 
 
 <&&4+F&OOH5T\JJJKKK 	J((8H(IIIII	J 	Jr^   c                 b    | j         r| j                                         t                       d S N)rK   r   closer   )rZ   s    r\   cleanupz)FullGRPOFinetuneRecipeDistributed.cleanup  s4     	(%%'''r^   l_grpo_statsc                 .    |D ]}~~|D ]	}|D ]}~~
~d S r  r   )rZ   rI  r  vgs        r\   rk  z4FullGRPOFinetuneRecipeDistributed.cleanup_after_step  sJ    
  	 	A 	 	A  ALLr^   r  )r)   N),__name__
__module____qualname____doc__r
   r]   r   strr   rd   rk   re   r   r   intr   r   r   r;   r   profiler!   r   boolr   tupler   Moduler   r   r   r   r  Tensorr   r=  rH  r   rW  ru  ri  r  r   rk  r   r^   r\   r'   r'   #   s:       2 2h2IJ 2I4 2I 2I 2I 2Ih
 tCH~    
#
 
#tCQTH~ 
# 
# 
# 
#d38n     BqQ qQ qQ qQ qQ qQf&":.&  & 	&
 
)	& & & &R 48B B$Z0B	u~%}4	5B B B BV 6:p  p p  *.p  	p 
 sCx.p  #38np   (S	2p  
ry")#	$p  p  p  p j 48 ! !c3h0 
)		   . ;?3 33 3 	3
 3  (S#X73 
3 3 3 3jS$S$ 
S$ S$ S$ S$jC
C
04S	C
	C
 C
 C
 C
JCC04S	C	C C C C>C
"C
 C
 
	C
 C
 C
 C
JW W W WrJ(J6?J	J J J J>       
" 9o 
	     r^   r'   r(   r)   c                     t          |           }t          j        d|            |                    |            |                                 |                                 dS )z
    Entry point for the recipe.

    Configurable parameters are read in the following order:
        - Parameters specified in config (see available configs through ``tune ls``)
        - Overwritten by arguments from the command-line
    )r(   r'   )recipe_namer(   N)r'   r   r   r   ru  r  )r(   recipes     r\   recipe_mainr  )  sb     /3777F
"E3OOOO
LLSL
LLNNN
NNr^   __main__)>sysr   	functoolsr   typingr   r   r   r   r   warningsr	   r;   	omegaconfr
   r   r   torch.distributedr   r   torch.optimr   torchdata.stateful_dataloaderr   %torchdata.stateful_dataloader.samplerr   	torchtuner   r   r   r   r   r   torchtune.config._utilsr   torchtune.datasetsr   torchtune.dev.grpo.generationr   torchtune.dev.grpo.rewardsr   torchtune.dev.grpo.typesr   r   torchtune.modulesr   torchtune.recipe_interfacesr   torchtune.trainingr    r!   r"    torchtune.training.lr_schedulersr#   r$   
get_loggerrD   r'   parser  r  exitr   r^   r\   <module>r     s   


        3 3 3 3 3 3 3 3 3 3 3 3 3 3        , , , , , , , ,       G G G G G G G G ! ! ! ! ! ! < < < < < < L L L L L L H H H H H H H H H H H H H H H H < < < < < < , , , , , , 2 2 2 2 2 2 F F F F F F > > > > > > > > , , , , , , 9 9 9 9 9 9 K K K K K K K K K K 3 3 3 3 3 3      ewC C C C C(9 C C CL  Z D      zCH[[]] r^   