66import wandb
77from coati .distributed .consumer import BaseConsumer
88from coati .distributed .loss import PolicyLoss
9- from coati .distributed .utils import memory_efficient_logprob
9+ from coati .distributed .utils import entropy_from_logits , memory_efficient_logprob
1010from coati .trainer .utils import all_reduce_mean , all_reduce_sum
1111from transformers import AutoModelForCausalLM , AutoTokenizer
1212
@@ -75,6 +75,7 @@ def __init__(
7575 self .optimizer = HybridAdam (self .policy_model .parameters (), lr = grpo_config .get ("lr" , 1e-6 ))
7676 self .accum_loss = torch .zeros (1 , device = self .device )
7777 self .accum_kl = torch .zeros (1 , device = self .device )
78+ self .accum_entropy = torch .zeros (1 , device = self .device )
7879 self .accum_advantages = torch .zeros (1 , device = self .device )
7980 self .raw_train_batch_reward = []
8081 self .raw_train_batch_format_acc = []
@@ -257,6 +258,7 @@ def step(self, step_idx: int, pbar: Any, **kwargs) -> Optional[float]:
257258 else self .booster .no_sync (self .policy_model , self .optimizer )
258259 )
259260 with ctx :
261+ mini_batch_entropies = []
260262 for forward_micro_batch_start in range (0 , data ["input_ids" ].size (0 ), train_microbatch_size ):
261263 input_ids_forward_micro_batch = data ["input_ids" ][
262264 forward_micro_batch_start : forward_micro_batch_start + train_microbatch_size
@@ -323,9 +325,11 @@ def step(self, step_idx: int, pbar: Any, **kwargs) -> Optional[float]:
323325 data_policy_forward ["reference_action_log_probs" ] = reference_action_log_probs
324326
325327 kl = []
328+ policy_model_logits = torch .empty_like (input_ids_forward_micro_batch , device = self .device )
326329
327330 def _criterion (outputs , inputs ):
328331 action_logits = outputs .logits
332+ policy_model_logits .copy_ (action_logits )
329333 action_log_probs = memory_efficient_logprob (
330334 action_logits / self .generate_config ["temperature" ],
331335 inputs ["input_ids" ],
@@ -372,6 +376,20 @@ def _criterion(outputs, inputs):
372376 kl = all_reduce_mean (torch .mean (torch .stack (kl )).to (loss .device ), self .plugin ).data
373377 mean_kl .append (kl )
374378 mean_loss .append (all_reduce_mean (loss , self .plugin ).data )
379+ mini_batch_entropies .append (
380+ all_reduce_mean (
381+ (
382+ (
383+ (
384+ entropy_from_logits (policy_model_logits [:, - num_action :])
385+ * action_mask_forward_micro_batch
386+ ).sum (- 1 )
387+ )
388+ / action_mask_forward_micro_batch .sum (- 1 )
389+ ).detach (),
390+ self .plugin ,
391+ )
392+ )
375393 else :
376394 policy_model_logits = self .policy_model (
377395 input_ids = input_ids_forward_micro_batch ,
@@ -425,6 +443,20 @@ def _criterion(outputs, inputs):
425443 kl = all_reduce_mean (kl .mean (), self .plugin )
426444 mean_kl .append (kl .data )
427445 mean_loss .append (loss .data )
446+ mini_batch_entropies .append (
447+ all_reduce_mean (
448+ (
449+ (
450+ (
451+ entropy_from_logits (policy_model_logits [:, - num_action :])
452+ * action_mask_forward_micro_batch
453+ ).sum (- 1 )
454+ )
455+ / action_mask_forward_micro_batch .sum (- 1 )
456+ ).detach (),
457+ self .plugin ,
458+ )
459+ )
428460 if not self .plugin .pp_size > 1 or (
429461 self .plugin .pp_size > 1
430462 and self .booster .plugin .stage_manager .is_last_stage ()
@@ -436,7 +468,9 @@ def _criterion(outputs, inputs):
436468 ans_acc = all_reduce_mean (ans_acc .mean (), self .plugin )
437469 advantages = all_reduce_mean (advantages .mean (), self .plugin )
438470 response_length = all_reduce_mean (response_length .mean (), self .plugin )
471+ entropy = torch .cat (mini_batch_entropies , dim = 0 ).mean ()
439472 self .accum_loss .add_ (sum (mean_loss ) / len (mean_loss ))
473+ self .accum_entropy .add_ (entropy .data )
440474 if self .policy_loss_fn .beta > 0 :
441475 self .accum_kl .add_ (sum (mean_kl ) / len (mean_kl ))
442476 self .accum_advantages .add_ (advantages .data )
@@ -478,7 +512,8 @@ def _criterion(outputs, inputs):
478512 f"Advantages: { self .accum_advantages .item () / self .accum_count :.4f} " ,
479513 f"Response Length: { raw_batch_response_len_mean :.4f} " ,
480514 f"Sample_utilization: { sample_utilization :.4f} " ,
481- f"Percentage of overlength samples: { overlength_samples_percentage :.4f} " ,
515+ f"Overlength samples ratio: { overlength_samples_ratio :.4f} " ,
516+ f"Entropy: { self .accum_entropy .item () / self .accum_count :.4f} " ,
482517 ] + ([f"KL: { self .accum_kl .item () / self .accum_count :.4f} " ] if self .policy_loss_fn .beta > 0 else [])
483518 print ("\n " .join (to_log_msg ))
484519 metrics = {
@@ -490,7 +525,8 @@ def _criterion(outputs, inputs):
490525 "train/advantages" : self .accum_advantages .item () / self .accum_count ,
491526 "train/learning_rate" : self .lr_scheduler .get_last_lr ()[0 ],
492527 "train/sample_utilization" : sample_utilization ,
493- "train/percentage_overlength_samples" : overlength_samples_percentage ,
528+ "train/entropy" : self .accum_entropy .item () / self .accum_count ,
529+ "train/overlength_samples_ratio" : overlength_samples_ratio ,
494530 "rollout/temperature" : data ["temperature" ].cpu ().numpy ()[0 ][0 ],
495531 }
496532 if self .policy_loss_fn .beta > 0 :
@@ -499,6 +535,7 @@ def _criterion(outputs, inputs):
499535 self .wandb_run .log (metrics )
500536 self .accum_loss .zero_ ()
501537 self .accum_kl .zero_ ()
538+ self .accum_entropy .zero_ ()
502539 self .accum_advantages .zero_ ()
503540 self .accum_count = 0
504541 return loss_scalar
0 commit comments