feat(trainer): Support multi-role & consecutive turns in DataCollatorForCompletionOnlyLM (#3223) #3224
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What does this PR do?
This PR refactors the masking logic in
DataCollatorForCompletionOnlyLM
to correctly handle conversations with multiple instruction roles (e.g., user, tool) and consecutive assistant/question turns. This enables the collator's use for more complex dialogue formats like agent trajectories.Motivation & Context:
Previously, the collator assumed a strict alternation of a single instruction template and a response template (e.g., User -> Assistant). This limitation prevented its use for common scenarios in modern LLM fine-tuning:
<|im_start|>tool
).This addresses the need for better support for agent tuning data and multi-turn formats, as mentioned in issues #1994 and #2545.
Changes Implemented:
This commit addresses the limitations by:
DataCollatorForCompletionOnlyLM.__init__
to accept a list of strings or pre-tokenized IDs forinstruction_template
, allowing multiple distinct instruction roles to be specified.torch_call
:<|im_start|>assistant\n
) of subsequent responses remain masked, while their content is unmasked for loss calculation.test_masking_*
intest_data_collator_completion_only.py
) covering:This update significantly increases the flexibility of
DataCollatorForCompletionOnlyLM
, making it suitable for processing conversational data commonly found in ChatML formats and agent fine-tuning datasets.My guess is that it can be done more efficiently (harder to understand tho), but the amounts of special tokens does not seem that high to me to optimise it further.
Related: #1994, #2545
Fixes #3223
Before submitting
to it if that's the case. (Fixes Support masking of different and repeating roles DataCollatorForCompletionOnlyLM #3223)
documentation guidelines. (Docstring updated for
instruction_template
, tests serve as examples).Who can review?
Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.