Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 36 additions & 9 deletions swift/rlhf_trainers/dpo_trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,23 +130,20 @@ def concatenated_forward(
all_logits, labels, label_pad_token_id=self.label_pad_token_id)
origin_per_token_logps = per_token_logps

loss_types = self.loss_type if isinstance(self.loss_type, list) else [self.loss_type]
if 'ipo' in loss_types:
size_completion = loss_mask.sum(dim=-1)
per_token_logps = per_token_logps / size_completion

output = {}
if self.template.padding_free:
cu_seqlens = self.get_cu_seqlens(text_position_ids, batch.get('logits_to_keep'))
num_examples = (cu_seqlens.shape[0] - 1) // 2
all_logps = per_token_logps.new_zeros((num_examples * 2, ))
completion_token_counts = loss_mask.new_zeros((num_examples * 2, ), dtype=torch.long)
completion_lengths = (cu_seqlens[1:] - cu_seqlens[:-1])
chosen_lengths = completion_lengths[:num_examples]
rejected_lengths = completion_lengths[num_examples:]
public_lengths = torch.min(chosen_lengths, rejected_lengths) # l_p in the paper

for i in range(cu_seqlens.shape[0] - 1):
start, end = cu_seqlens[i], cu_seqlens[i + 1]
completion_token_counts[i] = loss_mask[:, start:end].sum()
length = end - start
public_length = public_lengths[i % num_examples]
if self.args.ld_alpha is not None and not is_ref_model and length > public_length:
Expand All @@ -160,10 +157,13 @@ def concatenated_forward(
output['nll_loss'] = -origin_per_token_logps[:, :num_tokens][loss_mask[:, :num_tokens]].mean()
output['chosen_logps'] = all_logps[:num_examples]
output['rejected_logps'] = all_logps[num_examples:]
output['chosen_completion_token_counts'] = completion_token_counts[:num_examples]
output['rejected_completion_token_counts'] = completion_token_counts[num_examples:]
output['mean_chosen_logits'] = mean_all_logits[:, :num_tokens][loss_mask[:, :num_tokens]].mean()
output['mean_rejected_logits'] = mean_all_logits[:, num_tokens:][loss_mask[:, num_tokens:]].mean()
else:
num_examples = labels.shape[0] // 2
completion_token_counts = loss_mask.sum(dim=1)
if not is_ref_model:
output['nll_loss'] = -origin_per_token_logps[:num_examples][loss_mask[:num_examples]].mean()
if self.args.ld_alpha is not None and not is_ref_model:
Expand Down Expand Up @@ -191,6 +191,8 @@ def concatenated_forward(
all_logps = per_token_logps.sum(-1)
output['chosen_logps'] = all_logps[:num_examples]
output['rejected_logps'] = all_logps[num_examples:]
output['chosen_completion_token_counts'] = completion_token_counts[:num_examples]
output['rejected_completion_token_counts'] = completion_token_counts[num_examples:]
output['mean_chosen_logits'] = mean_all_logits[:num_examples][loss_mask[:num_examples]].mean()
output['mean_rejected_logits'] = mean_all_logits[num_examples:][loss_mask[num_examples:]].mean()
if self.aux_loss_enabled:
Expand All @@ -208,6 +210,10 @@ def compute_ref_log_probs(self, batch):
ref_model_output = self.concatenated_forward(self.ref_model, batch, is_ref_model=True)
return ref_model_output['chosen_logps'], ref_model_output['rejected_logps']

@staticmethod
def _get_ipo_sequence_logps(sequence_logps, completion_token_counts):
return sequence_logps / completion_token_counts.to(sequence_logps).clamp_min(1)

def dpo_loss(
self,
chosen_logps: torch.FloatTensor,
Expand Down Expand Up @@ -365,11 +371,23 @@ def get_batch_loss_metrics(
loss_types = self.loss_type if isinstance(self.loss_type, list) else [self.loss_type]
loss_weights = self.loss_weights if hasattr(self, 'loss_weights') and self.loss_weights else None
for idx, loss_type in enumerate(loss_types):
chosen_logps = model_output['chosen_logps']
rejected_logps = model_output['rejected_logps']
current_ref_chosen_logps = ref_chosen_logps
current_ref_rejected_logps = ref_rejected_logps
if loss_type == 'ipo':
chosen_token_counts = model_output['chosen_completion_token_counts']
rejected_token_counts = model_output['rejected_completion_token_counts']
chosen_logps = self._get_ipo_sequence_logps(chosen_logps, chosen_token_counts)
rejected_logps = self._get_ipo_sequence_logps(rejected_logps, rejected_token_counts)
current_ref_chosen_logps = self._get_ipo_sequence_logps(current_ref_chosen_logps, chosen_token_counts)
current_ref_rejected_logps = self._get_ipo_sequence_logps(current_ref_rejected_logps,
rejected_token_counts)
_losses, _chosen_rewards, _rejected_rewards = self.dpo_loss(
model_output['chosen_logps'],
model_output['rejected_logps'],
ref_chosen_logps,
ref_rejected_logps,
chosen_logps,
rejected_logps,
current_ref_chosen_logps,
current_ref_rejected_logps,
loss_type,
model_output,
)
Expand Down Expand Up @@ -399,6 +417,15 @@ def get_batch_loss_metrics(
self.accelerator.gather_for_metrics(model_output['chosen_logps']).detach().mean().item())
metrics[f'{prefix}logps/rejected'] = (
self.accelerator.gather_for_metrics(model_output['rejected_logps']).detach().mean().item())
if 'ipo' in loss_types:
chosen_mean_logps = self._get_ipo_sequence_logps(model_output['chosen_logps'],
model_output['chosen_completion_token_counts'])
rejected_mean_logps = self._get_ipo_sequence_logps(model_output['rejected_logps'],
model_output['rejected_completion_token_counts'])
metrics[f'{prefix}logps_mean/chosen'] = (
self.accelerator.gather_for_metrics(chosen_mean_logps).detach().mean().item())
metrics[f'{prefix}logps_mean/rejected'] = (
self.accelerator.gather_for_metrics(rejected_mean_logps).detach().mean().item())
metrics[f'{prefix}logits/chosen'] = (
self.accelerator.gather_for_metrics(model_output['mean_chosen_logits']).detach().mean().item())
metrics[f'{prefix}logits/rejected'] = (
Expand Down
Loading