Implement a custom collate function used to batch variable-length tokenized examples for instruction-style language model finetuning.
Given a batch (list of token ID lists), produce padded inputs and targets tensors (as nested Python lists) following this procedure:
batch_max_length = max(len(item) + 1 for item in batch). The +1 reserves room for an appended end-of-text/pad token.item in the batch:
pad_token_id to a copy of item.pad_token_id until its length equals batch_max_length.inputs as padded[:-1] and targets as padded[1:] (targets are inputs shifted right by one position).targets, locate every occurrence of pad_token_id. Keep the FIRST such occurrence as-is (so the model learns to predict one end-of-text token) and replace every subsequent pad_token_id in targets with ignore_index (so the loss ignores those positions).allowed_max_length is not None, truncate BOTH inputs and targets to the first allowed_max_length tokens (apply this AFTER the ignore-index replacement).{'inputs': [...], 'targets': [...]} where each value is a list of lists (one per example in the batch order).Parameters:
batch: list of lists of intspad_token_id: int, default 50256ignore_index: int, default -100allowed_max_length: optional int, default None