-
Notifications
You must be signed in to change notification settings - Fork 295
feat: Enable simulated user for multi-turn GRPO #1412
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ahmadki
wants to merge
22
commits into
main
Choose a base branch
from
ahmadki/simulated-user-rec
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
38d6a69
ini
jialei777 9f86537
add unit test
jialei777 6c9c7b7
dependency
jialei777 fca937e
address comments
jialei777 6facb1c
address comments
jialei777 b4496af
add gemma support
jialei777 9e96011
typo
jialei777 183ff48
address comments
jialei777 68c8027
merge main
jialei777 c114e6b
Merge branch 'main' into ahmadki/simulated-user-rec
ahmadki 0eb88cb
Fixes after merging main
ahmadki 3b80f4b
Merge branch 'main' into ahmadki/simulated-user-rec
ahmadki bae577f
froze versions in adk dependencies and added google-genai
ahmadki d5e9f46
fixed pyrefly errors
ahmadki 700e89c
Merge branch 'main' into ahmadki/simulated-user-rec
ahmadki de04f1c
Merge branch 'main' into ahmadki/simulated-user-rec
ahmadki b4ab3b5
cleanup
ahmadki adb1d3c
Added copyright notice
mrm-196 e495cb8
updated doc
ahmadki a5731b0
code cleanup and yaml documentation
ahmadki 04050bf
factored out format_and_tokenize_env_observation, added tests
ahmadki d0d4629
Merge branch 'main' into ahmadki/simulated-user-rec2
ahmadki 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| # GRPO configuration for unique numbers environment | ||
| defaults: "grpo_math_8B.yaml" | ||
|
|
||
| grpo: | ||
| num_prompts_per_step: 32 | ||
| num_generations_per_prompt: 16 | ||
| max_rollout_turns: 20 | ||
| max_num_steps: 100 | ||
| val_at_start: false | ||
|
|
||
| data: | ||
| add_system_prompt: false | ||
| shuffle: false | ||
|
|
||
| checkpointing: | ||
| enabled: false | ||
| checkpoint_dir: "results/grpo-adk" | ||
| metric_name: "val_reward" | ||
| higher_is_better: true | ||
| keep_top_k: 3 | ||
| save_period: 10 | ||
|
|
||
| env: | ||
| unique_numbers: | ||
| cfg: | ||
| # Maximum number of conversation turns before episode terminates | ||
| max_turns: 15 | ||
| # Minimum length of the randomly generated number list | ||
| min_length: 5 | ||
| # Maximum length of the randomly generated number list | ||
| max_length: 10 | ||
| # Maximum value for integers in the list (range: 0 to max_integer) | ||
| max_integer: 15 | ||
|
|
||
| logger: | ||
| wandb_enabled: True | ||
| wandb: | ||
| project: "grpo-simulated-adk" | ||
| name: "gemma-4b-__NOW__" | ||
|
|
||
|
|
||
| policy: | ||
| train_global_batch_size: 512 | ||
| logprob_batch_size: 1 | ||
| model_name: google/gemma-3-4b-it | ||
| dynamic_batching: | ||
| enabled: True | ||
| sequence_packing: | ||
| enabled: False | ||
| tokenizer: | ||
| name: google/gemma-3-4b-it | ||
| chat_template: "{%- if add_bos_token|default(false) %}{{ bos_token }}{% endif %}{% for message in messages %}{% set role = 'model' if message['role'] == 'assistant' else message['role'] %}{{ '<start_of_turn>' + role + '\n' + message['content'] | trim + '<end_of_turn>\n' }}{% endfor %}{% if add_generation_prompt %}{{ '<start_of_turn>model\n' }}{% endif %}" | ||
|
|
||
| cluster: | ||
| gpus_per_node: 8 | ||
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,49 @@ | ||
| # GRPO configuration for unique numbers environment | ||
| defaults: "grpo_math_8B.yaml" | ||
|
|
||
| grpo: | ||
| num_prompts_per_step: 32 | ||
| num_generations_per_prompt: 16 | ||
| max_rollout_turns: 20 | ||
| max_num_steps: 100 | ||
| val_at_start: false | ||
|
|
||
| data: | ||
| add_system_prompt: false | ||
| shuffle: false | ||
|
|
||
| checkpointing: | ||
| enabled: false | ||
| checkpoint_dir: "results/grpo-adk" | ||
| metric_name: "val_reward" | ||
| higher_is_better: true | ||
| keep_top_k: 3 | ||
| save_period: 10 | ||
|
|
||
| env: | ||
| unique_numbers: | ||
| cfg: | ||
| # Maximum number of conversation turns before episode terminates | ||
| max_turns: 15 | ||
| # Minimum length of the randomly generated number list | ||
| min_length: 5 | ||
| # Maximum length of the randomly generated number list | ||
| max_length: 10 | ||
| # Maximum value for integers in the list (range: 0 to max_integer) | ||
| max_integer: 15 | ||
|
|
||
ahmadki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| logger: | ||
| wandb_enabled: True | ||
| wandb: | ||
| project: "grpo-simulated-adk" | ||
| name: "llama-8b-__NOW__" | ||
|
|
||
| policy: | ||
| train_global_batch_size: 512 | ||
| dynamic_batching: | ||
| enabled: False | ||
| tokenizer: | ||
| chat_template: '{%- if add_bos_token|default(false) %}{{ bos_token }}{% endif %}{% for message in messages %}{{ "<|start_header_id|>" + message.role + "<|end_header_id|>\n\n" + message.content | trim + "<|eot_id|>" }}{% endfor %}{% if add_generation_prompt %}{{ "<|start_header_id|>assistant<|end_header_id|>\n\n" }}{% endif %}' | ||
|
|
||
| cluster: | ||
| gpus_per_node: 8 | ||
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,273 @@ | ||
| # Copyright (c) 2025, 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. | ||
|
|
||
| """Run GRPO with the Unique Numbers Simulator using ADK. | ||
|
|
||
| This script sets up and executes the Group Relative Policy Optimization (GRPO) algorithm | ||
| in a multi-turn conversational environment powered by the ADK framework. | ||
|
|
||
| ### Task Overview | ||
| The objective is to train an agent to guess the number of unique integers in a list generated by a simulated user. | ||
| The interaction is structured as a turn-based dialogue: | ||
| - The user generates a list of integers. | ||
| - The agent queries specific positions in the list (by index). | ||
| - The user replies with the value at that index (if available). | ||
| - The agent continues the interaction until it makes a final guess at the number of unique integers. | ||
|
|
||
| ### Environment Details | ||
| The environment is a simulated user that: | ||
| - Randomly generates a list of integers at setup. | ||
| - Responds to the agent's queries using an LLM via the ADK endpoint. | ||
| - Optionally evaluates the agent's final guess using an LLM-based grader (included for extensibility, though not essential for this task). | ||
|
|
||
| ### Example Usage | ||
| uv run --extra adk --extra automodel python examples/run_grpo_unique_numbers_w_adk.py | ||
|
|
||
| ### Requirements | ||
| - A working ADK environment with access to a compatible LLM endpoint. | ||
| For the default Gemini endpoint, the following environment variables must be set: | ||
| - `GOOGLE_GENAI_USE_VERTEXAI=1` | ||
| - `GOOGLE_CLOUD_PROJECT="your-project-id"` | ||
| - `GOOGLE_CLOUD_LOCATION="your-location"` | ||
|
|
||
| - A properly configured GRPO YAML file. | ||
| By default, the script uses: | ||
| `examples/configs/grpo_adk_llama8b.yaml` | ||
| """ | ||
ahmadki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| import argparse | ||
| import itertools | ||
| import os | ||
| import pprint | ||
| import random | ||
| from datetime import datetime, timedelta | ||
| from typing import Iterator | ||
|
|
||
| from omegaconf import OmegaConf | ||
| from torch.utils.data import IterableDataset | ||
| from transformers import AutoTokenizer | ||
|
|
||
| from nemo_rl.algorithms.grpo import MasterConfig, grpo_train, setup | ||
| from nemo_rl.algorithms.utils import get_tokenizer | ||
| from nemo_rl.data.interfaces import DatumSpec, LLMMessageLogType | ||
| from nemo_rl.distributed.ray_actor_environment_registry import ( | ||
| get_actor_python_env, | ||
| ) | ||
| from nemo_rl.distributed.virtual_cluster import init_ray | ||
| from nemo_rl.environments.simulated_user.prompt import starting_user_prompt | ||
| from nemo_rl.environments.simulated_user.unique_numbers import ( | ||
| UniqueNumbersEnv, | ||
| UniqueNumbersMetadata, | ||
| ) | ||
| from nemo_rl.models.generation import configure_generation_config | ||
| from nemo_rl.utils.config import load_config, parse_hydra_overrides | ||
| from nemo_rl.utils.logger import get_next_experiment_dir | ||
|
|
||
| OmegaConf.register_new_resolver("mul", lambda a, b: a * b) | ||
|
|
||
|
|
||
| def parse_args(): | ||
| parser = argparse.ArgumentParser( | ||
| description="Run GRPO with unique numbers simulator" | ||
| ) | ||
| parser.add_argument( | ||
| "--config", type=str, default=None, help="Path to YAML config file" | ||
| ) | ||
| args, overrides = parser.parse_known_args() | ||
| return args, overrides | ||
|
|
||
|
|
||
| def generate_datum( | ||
| tokenizer: AutoTokenizer, | ||
| env_cfg: dict, | ||
| task_name: str, | ||
| idx: int, | ||
| add_system_prompt: bool, | ||
| ) -> DatumSpec: | ||
| # please check the specific chat_template in the yaml file | ||
| formatted_prompt = tokenizer.apply_chat_template( | ||
| [{"role": "user", "content": starting_user_prompt}], | ||
| tokenize=False, | ||
| add_system_prompt=add_system_prompt, | ||
| add_bos_token=True, | ||
| add_generation_prompt=True, | ||
| add_special_tokens=False, | ||
| ) | ||
ahmadki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| token_ids = tokenizer( | ||
| formatted_prompt, return_tensors="pt", add_special_tokens=False | ||
| )["input_ids"][0] | ||
|
|
||
| def _generate_numbers( | ||
| min_length, max_length, max_integer, default_max_turns | ||
| ) -> UniqueNumbersMetadata: | ||
| length = random.randint(min_length, max_length) | ||
| numbers = [random.randint(0, max_integer) for _ in range(length)] | ||
| return UniqueNumbersMetadata( | ||
| numbers=numbers, | ||
| unique_count=len(set(numbers)), | ||
| turn=0, | ||
| max_turns=default_max_turns, | ||
| ) | ||
|
|
||
| metadata = _generate_numbers( | ||
| min_length=env_cfg["cfg"]["min_length"], | ||
| max_length=env_cfg["cfg"]["max_length"], | ||
| max_integer=env_cfg["cfg"]["max_integer"], | ||
| default_max_turns=env_cfg["cfg"]["max_turns"], | ||
| ) | ||
|
|
||
| message_log: LLMMessageLogType = [ | ||
| {"role": "user", "content": formatted_prompt, "token_ids": token_ids} | ||
| ] | ||
| return { | ||
| "message_log": message_log, | ||
| "length": len(token_ids), | ||
| "extra_env_info": metadata, | ||
| "loss_multiplier": 1.0, | ||
| "idx": idx, | ||
| "task_name": task_name, | ||
| } | ||
|
|
||
|
|
||
| class IterableNumbersDataset(IterableDataset): | ||
| def __init__(self, tokenizer, env_cfg, task_name, add_system_prompt, length): | ||
| super().__init__() | ||
| self.tokenizer = tokenizer | ||
| self.env_cfg = env_cfg | ||
| self.task_name = task_name | ||
| self.add_system_prompt = add_system_prompt | ||
| self.length = length | ||
|
|
||
| def __iter__(self) -> Iterator[DatumSpec]: | ||
| for i in itertools.count(): | ||
| yield generate_datum( | ||
| tokenizer=self.tokenizer, | ||
| env_cfg=self.env_cfg, | ||
| task_name=self.task_name, | ||
| idx=i, | ||
| add_system_prompt=self.add_system_prompt, | ||
| ) | ||
|
|
||
| def __len__(self): | ||
| return self.length | ||
|
|
||
|
|
||
| def setup_data(tokenizer, env_cfg, task_name, length, val_length, add_system_prompt): | ||
| env_config = env_cfg[task_name] | ||
| env = UniqueNumbersEnv.options( # type: ignore # it's wrapped with ray.remote | ||
| num_gpus=0, | ||
| runtime_env={ | ||
| "py_executable": get_actor_python_env( | ||
| "nemo_rl.environments.simulated_user.unique_numbers.UniqueNumbersEnv" | ||
| ), | ||
| "env_vars": dict(os.environ), # Pass thru all user environment variables | ||
| }, | ||
| ).remote(cfg=dict(env_config["cfg"])) | ||
|
|
||
ahmadki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| task_to_env = {task_name: env} | ||
|
|
||
| train_ds = IterableNumbersDataset( | ||
| tokenizer=tokenizer, | ||
| env_cfg=env_config, | ||
| task_name=task_name, | ||
| add_system_prompt=add_system_prompt, | ||
| length=length, | ||
| ) | ||
| val_ds = IterableNumbersDataset( | ||
| tokenizer=tokenizer, | ||
| env_cfg=env_config, | ||
| task_name=task_name, | ||
| add_system_prompt=add_system_prompt, | ||
| length=val_length, | ||
| ) | ||
| val_task_to_env = task_to_env | ||
| return train_ds, val_ds, task_to_env, val_task_to_env | ||
|
|
||
|
|
||
| def main(): | ||
| args, overrides = parse_args() | ||
| if not args.config: | ||
| args.config = os.path.join( | ||
| os.path.dirname(__file__), "configs", "grpo_adk_llama8b.yaml" | ||
| ) | ||
| config = load_config(args.config) | ||
| if overrides: | ||
| config = parse_hydra_overrides(config, overrides) | ||
| config: MasterConfig = OmegaConf.to_container(config, resolve=True) | ||
|
|
||
| now_pst = datetime.utcnow() + timedelta(hours=-7) | ||
| config["logger"]["wandb"]["name"] = config["logger"]["wandb"]["name"].replace( | ||
| "__NOW__", now_pst.strftime("%m/%d-%H:%M") | ||
| ) | ||
|
|
||
| config["logger"]["log_dir"] = get_next_experiment_dir(config["logger"]["log_dir"]) | ||
| if config["checkpointing"]["enabled"]: | ||
| print( | ||
| f"\U0001f4ca Using checkpoint directory: {config['checkpointing']['checkpoint_dir']}" | ||
| ) | ||
|
|
||
| pprint.pprint(config) | ||
|
|
||
| init_ray() | ||
|
|
||
| tokenizer = get_tokenizer(config["policy"]["tokenizer"]) | ||
| config["policy"]["generation"] = configure_generation_config( | ||
| config["policy"]["generation"], tokenizer | ||
| ) | ||
|
|
||
| ds_length = ( | ||
| config["grpo"]["num_prompts_per_step"] | ||
| * config["grpo"]["num_generations_per_prompt"] | ||
| * config["grpo"]["max_num_steps"] | ||
| ) | ||
| dataset, val_dataset, task_to_env, val_task_to_env = setup_data( | ||
| tokenizer=tokenizer, | ||
| env_cfg=config["env"], | ||
| task_name="unique_numbers", | ||
| length=ds_length, | ||
| val_length=config["grpo"]["max_val_samples"], | ||
| add_system_prompt=config["data"]["add_system_prompt"], | ||
| ) | ||
|
|
||
| ( | ||
| policy, | ||
| policy_generation, | ||
| cluster, | ||
| dataloader, | ||
| val_dataloader, | ||
| loss_fn, | ||
| logger, | ||
| checkpointer, | ||
| grpo_state, | ||
| master_config, | ||
| ) = setup(config, tokenizer, dataset, val_dataset) | ||
|
|
||
| grpo_train( | ||
| policy, | ||
| policy_generation, | ||
| dataloader, | ||
| val_dataloader, | ||
| tokenizer, | ||
| loss_fn, | ||
| task_to_env, | ||
| val_task_to_env, | ||
| logger, | ||
| checkpointer, | ||
| grpo_state, | ||
| master_config, | ||
| ) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
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
Oops, something went wrong.
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.