This repository was archived by the owner on Nov 19, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 104
feat: support new DPO data format and update SFT config to use override API #405
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
0d3b8ee
feat: dpo dataset new openai chat completion format
terrykong db3eb40
Update test_datasets.py
arendu adb8130
updated to use importskip
arendu 1d732ad
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 613a63a
Merge branch 'main' into adithyare/dpo_data_refac
terrykong a76c29a
fix for batch size misconfiguration
arendu e3d1192
Merge branch 'adithyare/dpo_data_refac' of https://github.com/NVIDIA/…
arendu db1d5f1
Update gpt_sft.yaml removed comment
arendu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
arendu marked this conversation as resolved.
Show resolved
Hide resolved
arendu marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,13 +15,19 @@ | |
| """Custom datasets for RLHF training""" | ||
|
|
||
| import os | ||
| from typing import Dict, List | ||
|
|
||
| import numpy as np | ||
| import scipy | ||
| import torch | ||
| from omegaconf import OmegaConf | ||
|
|
||
| from nemo.collections.nlp.data.language_modeling.megatron.gpt_dataset import _create_ltor_masks_and_position_ids | ||
| from nemo.collections.nlp.data.language_modeling.megatron.gpt_sft_chat_dataset import GPTSFTChatDataset | ||
| from nemo.collections.nlp.data.language_modeling.megatron.gpt_sft_chat_dataset import ( | ||
| GPTSFTChatDataset, | ||
| _get_header_conversation_type_mask_role, | ||
| get_prompt_template_example, | ||
| ) | ||
| from nemo.core import Dataset | ||
| from nemo.utils import logging | ||
|
|
||
|
|
@@ -344,16 +350,97 @@ def encode(self, text, append_eod=False): | |
|
|
||
| return text_ids, len(text_ids) | ||
|
|
||
| @staticmethod | ||
| def _convert_messages( | ||
| input_list: List[Dict[str, str]] | ||
| ) -> Dict: # TODO: (@adithyare) this method should live elsewhare.. | ||
| """ | ||
| args: | ||
| input_list: is a list of dicts in the openai format | ||
| for example: | ||
| [{"role": "system", "content": "you are helpful}, | ||
| {"role": "user", "content": "Why is the sky blue?"}, | ||
| {"role": "assistant", "content": "Because blablabla"}, | ||
| ...] | ||
| returns: | ||
| output_dict: a dict in nemo's format {"system": "sytem prompt", | ||
| "conversation": [], | ||
| ... | ||
| } | ||
| """ | ||
| output_dict = { | ||
| "system": "", | ||
| "conversations": [], | ||
| "mask": "User", | ||
| "type": "VALUE_TO_TEXT", | ||
| } | ||
|
|
||
| # Extract the system message | ||
| num_system_msg = 0 | ||
| for msg in input_list: | ||
| if msg["role"] == "system": | ||
| output_dict["system"] = msg["content"] | ||
| num_system_msg += 1 | ||
| if num_system_msg > 1: | ||
| raise RuntimeError("Multiple system messages seen, please consolidate into a single system message.") | ||
|
|
||
| # Build the conversations list | ||
| for msg in input_list: | ||
| if msg["role"] != "system": | ||
| conversation_entry = { | ||
| "from": msg["role"].capitalize(), # Capitalize 'user' and 'assistant' | ||
| "value": msg["content"], | ||
| "label": None, | ||
| } | ||
| output_dict["conversations"].append(conversation_entry) | ||
|
|
||
arendu marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return output_dict | ||
|
|
||
| def convert(self, messages): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do you think it can support |
||
| """ | ||
| args: | ||
| messages: is a list of dicts in the openai format | ||
| for example: | ||
| [{"role": "system", "content": "you are helpful}, | ||
| {"role": "user", "content": "Why is the sky blue?"}, | ||
| {"role": "assistant", "content": "Because blablabla"}, | ||
| ...] | ||
| returns: | ||
| conversation: is a string formatted with the chat template | ||
| """ | ||
| if OmegaConf.select(self.cfg, "data.chat_prompt_tokens") is None: | ||
| raise RuntimeError( | ||
| "You don't have a model (model_config.yaml) which has chat_prompt_tokens, are you sure this is a Chat/Instruction model?" | ||
| ) | ||
| special_tokens = self.cfg.data.chat_prompt_tokens | ||
| nemo_source = self._convert_messages(messages) | ||
| header, conversation, data_type, mask_role = _get_header_conversation_type_mask_role( | ||
| nemo_source, special_tokens | ||
| ) | ||
| return conversation | ||
|
|
||
| def __getitem__(self, idx): | ||
| """Returns a pair of chosen/rejected pairs, their respective lengths, and labels.""" | ||
| payload = self.data[idx] | ||
| prompt, prompt_len = self.encode(payload["prompt"], append_eod=False) | ||
| chosen, chosen_len = self.encode( | ||
| payload["prompt"] + payload["chosen_response"], append_eod=self.cfg.data.get("append_eod", False) | ||
| ) | ||
| reject, reject_len = self.encode( | ||
| payload["prompt"] + payload["rejected_response"], append_eod=self.cfg.data.get("append_eod", False) | ||
| ) | ||
|
|
||
| if isinstance(payload["prompt"], str): | ||
| # (@adithyare) format with hardcoded chat tokens | ||
| # will allow this for the time being. | ||
| prompt_fmtd = payload["prompt"] | ||
| chosen_fmtd = payload["prompt"] + payload["chosen_response"] | ||
| rejected_fmtd = payload["prompt"] + payload["rejected_response"] | ||
| logging.warning( | ||
| "Pre-formatting chat conversation as string with hardcoded chat tokens will be deprecated." | ||
| ) # (@adithyare) this will spam the console for now. | ||
| else: | ||
| prompt_fmtd = self.convert(payload["prompt"]) # (@adithyare) read var as "prompt formatted" | ||
| chosen_fmtd = self.convert(payload["prompt"] + [payload["chosen_response"]]) | ||
| rejected_fmtd = self.convert(payload["prompt"] + [payload["rejected_response"]]) | ||
|
|
||
| prompt, prompt_len = self.encode(prompt_fmtd, append_eod=False) | ||
| chosen, chosen_len = self.encode(chosen_fmtd, append_eod=self.cfg.data.get("append_eod", False)) | ||
| reject, reject_len = self.encode(rejected_fmtd, append_eod=self.cfg.data.get("append_eod", False)) | ||
|
|
||
| # chosen_response_only, chosen_response_len = self.encode(payload['chosen_response']) | ||
| # reject_response_only, reject_response_len = self.encode(payload['rejected_response']) | ||
| chosen_labels = ([-100] * prompt_len) + chosen[prompt_len:] | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """Script to remove special tokens from dpo datasets | ||
| and convert them into list of messages format""" | ||
|
|
||
| import argparse | ||
| import json | ||
| import re | ||
|
|
||
|
|
||
| def format_conversation(input_string): | ||
| # Define roles and patterns | ||
| role_patterns = {"<extra_id_0>System": "system", "<extra_id_1>User": "user", "<extra_id_1>Assistant": "assistant"} | ||
|
|
||
| # Initialize an empty output list | ||
| conversation = [] | ||
|
|
||
| # Use regex to find each segment's role and content | ||
| segments = re.findall(r"(<extra_id_[0-1]>[^\n]+)\n(.*?)((?=<extra_id_)|$)", input_string, re.DOTALL) | ||
|
|
||
| for segment in segments: | ||
| role_tag, content, _ = segment | ||
| role = role_patterns.get(role_tag.strip(), "unknown") | ||
| conversation.append({"role": role, "content": content.strip()}) | ||
|
|
||
| return conversation | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| parser = argparse.ArgumentParser(description="Process a JSONL file.") | ||
| parser.add_argument("input_jsonl", type=str, help="Path to the input JSONL file.") | ||
| # Parse the arguments | ||
| args = parser.parse_args() | ||
|
|
||
| input_jsonl = args.input_jsonl | ||
| output_jsonl = input_jsonl.replace(".jsonl", ".no_special_toks.jsonl") | ||
|
|
||
| with open(input_jsonl, "r") as f, open(output_jsonl, "w") as w: | ||
| for line in f: | ||
| j = json.loads(line) | ||
| prompt = j["prompt"] | ||
| undo_spl_prompt = format_conversation(prompt) | ||
| empty_assistant = undo_spl_prompt.pop() | ||
| chosen, rejected = j["chosen_response"], j["rejected_response"] | ||
| chosen = chosen.split("\n<extra_id_1>")[0] | ||
| rejected = rejected.split("\n<extra_id_1>")[0] | ||
| chosen_message = {"role": empty_assistant["role"], "content": chosen} | ||
| rejected_message = {"role": empty_assistant["role"], "content": rejected} | ||
| j_out = { | ||
| "prompt": undo_spl_prompt, | ||
| "chosen_response": chosen_message, | ||
| "rejected_response": rejected_message, | ||
| "chosen_reward": j["chosen_reward"], | ||
| "rejected_reward": j["rejected_reward"], | ||
| } | ||
| w.write(json.dumps(j_out) + "\n") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| Jinja2~=3.1.4 | ||
| jsonlines | ||
| megatron_core>=0.8 | ||
| nemo_toolkit[nlp] | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.