Direct Preference Optimization (DPO) trains a language model from pairs of preferred and dispreferred responses to the same prompt. To run DPO efficiently in batches, you need a collate function that packs a list of preference examples into padded tensors and produces masks that mark only the response tokens (so the loss is computed on response tokens, not on the shared prompt or on padding).
Implement collate_preference_batch(batch, pad_token_id=0) where batch is a list of dicts, each with three keys: 'prompt', 'chosen', and 'rejected'. Each value is a list of integer token ids.
For every item, form two full sequences:
Let max_len be the maximum length across all chosen and rejected sequences in the batch. Right-pad every sequence to max_len using pad_token_id.
Also build boolean masks of shape (batch_size, max_len):
chosen_mask[i, t] is True only at positions that belong to item i's chosen response tokens (i.e., positions prompt_len <= t < prompt_len + len(chosen)).rejected_mask[i, t] is True only at positions that belong to item i's rejected response tokens.Return a dict with four keys, all as nested Python lists (use .tolist()):
'chosen_input_ids''rejected_input_ids''chosen_mask''rejected_mask'The order of items in the batch must be preserved.