Update rl_replacements.py

This commit is contained in:
Daniel Han 2025-02-16 17:13:24 -08:00
commit fc5a3a04ac

View file

@ -177,6 +177,7 @@ def grpo_trainer__get_per_token_logps(function_name, function):
if function_name != "_get_per_token_logps": return function
def _get_per_token_logps(self, model, input_ids, attention_mask, logits_to_keep):
return None
if not hasattr(self, '_autocast_dtype'):
self._autocast_dtype = torch.float16 if os.environ.get('ACCELERATE_MIXED_PRECISION', 'fp16') == 'fp16' else torch.bfloat16
with torch.amp.autocast(device_type = 'cuda', dtype = self._autocast_dtype):
@ -201,6 +202,8 @@ RL_FUNCTIONS["grpo_trainer"].append(grpo_trainer__get_per_token_logps)
grpo_compute_loss = RL_REPLACEMENTS["grpo_compute_loss"]
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(grpo_compute_loss))
global INPUTS
# Edit _get_per_token_logps to handle mixed precision
def grpo_trainer_compute_loss(function_name, function):
if function_name != "compute_loss": return function
@ -229,10 +232,15 @@ def grpo_trainer_compute_loss(function_name, function):
# per_token_loss = -(per_token_loss - self.beta * per_token_kl)
# loss = ((per_token_loss * completion_mask).sum(dim=1) / completion_mask.sum(dim=1)).mean()
input_ids = input_ids[:, -logits_to_keep:]
print(input_ids.shape, ref_per_token_logps.shape, per_token_logps.shape, completion_mask.shape, advantages.shape)
loss, completion_length, mean_kl = grpo_compute_loss(
ref_per_token_logps, per_token_logps, input_ids, completion_mask, self.beta, advantages,
)
global INPUTS
INPUTS = (
ref_per_token_logps, per_token_logps, input_ids, completion_mask, self.beta, advantages,
loss, completion_length, mean_kl,
)
raise
# Log the metrics
# completion_length = self.accelerator.gather_for_metrics(completion_mask.sum(1)).float().mean().item()
self._metrics["completion_length"].append(completion_length.item())