Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Arbor GRPO Async Rollouts Update (#8939)

Noah Ziems1df5984007b7
diff --git a/docs/docs/tutorials/rl_multihop/index.ipynb b/docs/docs/tutorials/rl_multihop/index.ipynb
index b2757b0a9..73112e221 100644
--- a/docs/docs/tutorials/rl_multihop/index.ipynb
+++ b/docs/docs/tutorials/rl_multihop/index.ipynb
@@ -227,7 +227,6 @@
"outputs": [],
"source": [
"from dspy.teleprompt.grpo import GRPO\n",
- "from dspy.clients.utils_finetune import MultiGPUConfig\n",
"\n",
"program = ResearchHop(num_docs=4, num_hops=2)\n",
"program.set_lm(local_lm)\n",
@@ -261,7 +260,6 @@
" num_steps_for_val=10,\n",
" train_kwargs=train_kwargs,\n",
" report_train_scores=False,\n",
- " gpu_config=MultiGPUConfig(num_inference_gpus=1, num_training_gpus=1),\n",
")\n",
"\n",
"optimized_program = compiler.compile(\n",
diff --git a/docs/docs/tutorials/rl_papillon/index.ipynb b/docs/docs/tutorials/rl_papillon/index.ipynb
index 5049924dc..5ab652805 100644
--- a/docs/docs/tutorials/rl_papillon/index.ipynb
+++ b/docs/docs/tutorials/rl_papillon/index.ipynb
@@ -256,7 +256,6 @@
"outputs": [],
"source": [
"from dspy.teleprompt.grpo import GRPO\n",
- "from dspy.clients.utils_finetune import MultiGPUConfig\n",
"\n",
"papillon = PAPILLON(untrusted_model=openai_lm)\n",
"papillon.set_lm(local_lm)\n",
@@ -291,7 +290,6 @@
" num_steps_for_val=10,\n",
" train_kwargs=train_kwargs,\n",
" report_train_scores=False,\n",
- " gpu_config=MultiGPUConfig(num_inference_gpus=2, num_training_gpus=2),\n",
")\n",
"\n",
"optimized_papillon = compiler.compile(\n",
diff --git a/dspy/clients/lm.py b/dspy/clients/lm.py
index 1705ab7be..366dd227f 100644
--- a/dspy/clients/lm.py
+++ b/dspy/clients/lm.py
@@ -13,7 +13,7 @@ import dspy
from dspy.clients.cache import request_cache
from dspy.clients.openai import OpenAIProvider
from dspy.clients.provider import Provider, ReinforceJob, TrainingJob
-from dspy.clients.utils_finetune import MultiGPUConfig, TrainDataFormat
+from dspy.clients.utils_finetune import TrainDataFormat
from dspy.dsp.utils.settings import settings
from dspy.utils.callback import BaseCallback
@@ -229,7 +229,7 @@ class LM(BaseLM):
return job
def reinforce(
- self, train_kwargs, gpu_config: MultiGPUConfig = MultiGPUConfig(num_inference_gpus=1, num_training_gpus=1)
+ self, train_kwargs
) -> ReinforceJob:
# TODO(GRPO Team): Should we return an initialized job here?
from dspy import settings as settings
@@ -237,7 +237,7 @@ class LM(BaseLM):
err = f"Provider {self.provider} does not implement the reinforcement learning interface."
assert self.provider.reinforceable, err
- job = self.provider.ReinforceJob(lm=self, train_kwargs=train_kwargs, gpu_config=gpu_config)
+ job = self.provider.ReinforceJob(lm=self, train_kwargs=train_kwargs)
job.initialize()
return job
diff --git a/dspy/clients/lm_local_arbor.py b/dspy/clients/lm_local_arbor.py
index c4c6fd992..dd2e12308 100644
--- a/dspy/clients/lm_local_arbor.py
+++ b/dspy/clients/lm_local_arbor.py
@@ -1,6 +1,7 @@
+import json
import time
from datetime import datetime
-from typing import TYPE_CHECKING, Any, TypedDict
+from typing import TYPE_CHECKING, Any
from urllib.parse import urljoin
import openai
@@ -8,16 +9,12 @@ import requests
import dspy
from dspy.clients.provider import Provider, ReinforceJob, TrainingJob
-from dspy.clients.utils_finetune import GRPOGroup, MultiGPUConfig, TrainDataFormat, TrainingStatus, save_data
+from dspy.clients.utils_finetune import GRPOGroup, GRPOStatus, TrainDataFormat, TrainingStatus, save_data
if TYPE_CHECKING:
from dspy.clients.lm import LM
-class GRPOTrainKwargs(TypedDict):
- num_generations: int
-
-
class ArborTrainingJob(TrainingJob):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -48,7 +45,7 @@ class ArborTrainingJob(TrainingJob):
class ArborReinforceJob(ReinforceJob):
DEFAULT_TRAIN_KWARGS = { # noqa: RUF012
- "temperature": 0.9,
+ "temperature": 1.0,
"beta": 0.04,
"num_iterations": 1,
"per_device_train_batch_size": 8,
@@ -57,6 +54,7 @@ class ArborReinforceJob(ReinforceJob):
# This is false by default in TRL, but I think it makes sense to be true for us
"gradient_checkpointing": True,
"lr_scheduler_type": "constant_with_warmup",
+ "warmup_steps": 10,
"max_prompt_length": None,
"max_completion_length": None,
"gradient_checkpointing_kwargs": None,
@@ -65,13 +63,13 @@ class ArborReinforceJob(ReinforceJob):
"max_grad_norm": 1.0,
"report_to": "none",
"log_completions": True,
- "logging_steps": 100,
+ "logging_steps": 10,
# By default, none is the model's max context length
"max_context_length": None,
"lora": False,
}
- def __init__(self, lm: "LM", train_kwargs: GRPOTrainKwargs, gpu_config: MultiGPUConfig = MultiGPUConfig(num_inference_gpus=1, num_training_gpus=1)):
+ def __init__(self, lm: "LM", train_kwargs: dict[str, Any]):
# The teleprompter must ensure that this is set
if "num_generations" not in train_kwargs:
raise ValueError("num_generations must be set in the training kwargs")
@@ -81,7 +79,6 @@ class ArborReinforceJob(ReinforceJob):
self.provider_job_id = None
self.checkpoints = {}
self.last_checkpoint = None
- self.gpu_config = gpu_config
def initialize(self):
# TODO(GRPO Team): Set provider job ID
@@ -100,6 +97,7 @@ class ArborReinforceJob(ReinforceJob):
"gradient_checkpointing", self.DEFAULT_TRAIN_KWARGS["gradient_checkpointing"]
)
lr_scheduler_type = self.train_kwargs.get("lr_scheduler_type", self.DEFAULT_TRAIN_KWARGS["lr_scheduler_type"])
+ warmup_steps = self.train_kwargs.get("warmup_steps", self.DEFAULT_TRAIN_KWARGS["warmup_steps"])
max_prompt_length = self.train_kwargs.get("max_prompt_length", self.DEFAULT_TRAIN_KWARGS["max_prompt_length"])
max_completion_length = self.train_kwargs.get(
"max_completion_length", self.DEFAULT_TRAIN_KWARGS["max_completion_length"]
@@ -116,43 +114,54 @@ class ArborReinforceJob(ReinforceJob):
max_context_length = self.train_kwargs.get(
"max_context_length", self.DEFAULT_TRAIN_KWARGS["max_context_length"]
)
- lora = self.train_kwargs.get("lora", self.DEFAULT_TRAIN_KWARGS["lora"])
+ max_steps = self.train_kwargs.get("max_steps",500)
+ # lora = self.train_kwargs.get("lora", self.DEFAULT_TRAIN_KWARGS["lora"])
api_base = self.lm.kwargs["api_base"]
finetune_model = ArborProvider._remove_provider_prefix(self.lm.model)
- # Only multi-GPU is supported for now
- gpu_config_type = "multi"
data = {
"model": finetune_model,
- "num_generations": num_generations,
- "temperature": temperature,
- "beta": beta,
- "num_iterations": num_iterations,
- "per_device_train_batch_size": per_device_train_batch_size,
- "learning_rate": learning_rate,
- "gradient_accumulation_steps": gradient_accumulation_steps,
- "gradient_checkpointing": gradient_checkpointing,
- "lr_scheduler_type": lr_scheduler_type,
- "max_prompt_length": max_prompt_length,
- "max_completion_length": max_completion_length,
- "bf16": bf16,
- "scale_rewards": scale_rewards,
- "gradient_checkpointing_kwargs": gradient_checkpointing_kwargs,
- "max_grad_norm": max_grad_norm,
- "report_to": report_to,
- "log_completions": log_completions,
- "logging_steps": logging_steps,
- "max_context_length": max_context_length,
- "lora": lora,
+ "trainer_config": {
+ "num_generations": num_generations,
+ "temperature": temperature,
+ "beta": beta,
+ "per_device_train_batch_size": per_device_train_batch_size,
+ "learning_rate": learning_rate,
+ "gradient_accumulation_steps": gradient_accumulation_steps,
+ "gradient_checkpointing": gradient_checkpointing,
+ "lr_scheduler_type": lr_scheduler_type,
+ "warmup_steps": warmup_steps,
+ "max_prompt_length": max_prompt_length,
+ "max_completion_length": max_completion_length,
+ "bf16": bf16,
+ "scale_rewards": scale_rewards,
+ "gradient_checkpointing_kwargs": gradient_checkpointing_kwargs,
+ "max_grad_norm": max_grad_norm,
+ "report_to": report_to,
+ "log_completions": log_completions,
+ "logging_steps": logging_steps,
+ # "max_context_length": max_context_length,
+ # "max_seq_len": max_context_length,
+ "max_steps": max_steps,
+ # "lora": lora,
+ },
+ "inference_config": {
+ "model": finetune_model,
+ "max_context_length": max_context_length,
+ },
"gpu_config": {
- "type": gpu_config_type,
- gpu_config_type: self.gpu_config,
+ "type": "multi",
+ "multi": {
+ "num_inference_gpus": 1,
+ "num_training_gpus": 1,
+ },
},
}
- url = urljoin(api_base, "fine_tuning/grpo/initialize")
+ url = f"{api_base}fine_tuning/grpo/initialize"
headers = {"Content-Type": "application/json"}
response = requests.post(url=url, headers=headers, json=data)
- assert response.status_code == 200, f"Failed to initialize GRPO: {response}"
+ print(json.dumps(response.json(), indent=2))
+ response.raise_for_status()
response = response.json()
self.lm.model = ArborProvider._add_provider_prefix(response["current_model"])
self.provider_job_id = response.get("job_id")
@@ -165,8 +174,8 @@ class ArborReinforceJob(ReinforceJob):
# api_key = self.lm.kwargs["api_key"]
finetune_model = ArborProvider._remove_provider_prefix(self.lm.model)
- data = {"job_id": self.provider_job_id, "model": finetune_model, "batch": train_group}
- url = urljoin(api_base, f"fine_tuning/grpo/{self.provider_job_id}/step")
+ data = {"job_id": self.provider_job_id, "model": finetune_model, "batch": train_group["group"], "batch_id": train_group["batch_id"]}
+ url = urljoin(api_base, "fine_tuning/grpo/step")
headers = {"Content-Type": "application/json"}
response = requests.post(url, headers=headers, json=data)
assert response.status_code == 200, f"Failed to run a GRPO step: {response.text}"
@@ -190,6 +199,15 @@ class ArborReinforceJob(ReinforceJob):
for group in train_data:
self._run_grpo_step_one_group(group, train_data_format)
+ def get_status(self) -> GRPOStatus:
+ api_base = self.lm.kwargs["api_base"]
+ url = f"{api_base}fine_tuning/grpo/status"
+ headers = {"Content-Type": "application/json"}
+ body = {"job_id": self.provider_job_id}
+ response = requests.post(url, headers=headers, json=body)
+ assert response.status_code == 200, f"Failed to get GRPO status: {response.text}"
+ return GRPOStatus(**response.json())
+
def save_checkpoint(self, checkpoint_name: str, score: float | None = None):
api_base = self.lm.kwargs["api_base"]
url = urljoin(api_base, f"fine_tuning/grpo/{self.provider_job_id}/checkpoint")
@@ -222,15 +240,14 @@ class ArborReinforceJob(ReinforceJob):
self.lm.model = ArborProvider._add_provider_prefix(current_model)
def cancel(self):
- if self.provider_job_id:
- api_base = self.lm.kwargs["api_base"]
- url = urljoin(api_base, f"fine_tuning/grpo/{self.provider_job_id}/cancel")
- headers = {"Content-Type": "application/json"}
- response = requests.post(url, headers=headers)
- if response.status_code == 200:
- self.provider_job_id = None
- else:
- raise Exception(f"Failed to cancel GRPO job: {response.text}")
+ if ArborProvider.does_job_exist(self.provider_job_id):
+ status = self.status()
+ if ArborProvider.is_terminal_training_status(status):
+ err_msg = "Jobs that are complete cannot be canceled."
+ err_msg += f" Job with ID {self.provider_job_id} is done."
+ raise Exception(err_msg)
+ openai.fine_tuning.jobs.cancel(self.provider_job_id)
+ self.provider_job_id = None
def status(self) -> TrainingStatus:
status = ArborProvider.get_training_status(self.provider_job_id)
diff --git a/dspy/clients/provider.py b/dspy/clients/provider.py
index 1e7e47316..01952cd23 100644
--- a/dspy/clients/provider.py
+++ b/dspy/clients/provider.py
@@ -3,7 +3,7 @@ from concurrent.futures import Future
from threading import Thread
from typing import TYPE_CHECKING, Any
-from dspy.clients.utils_finetune import MultiGPUConfig, TrainDataFormat
+from dspy.clients.utils_finetune import TrainDataFormat
if TYPE_CHECKING:
from dspy.clients.lm import LM
@@ -36,13 +36,11 @@ class TrainingJob(Future):
class ReinforceJob:
- def __init__(self, lm: "LM", train_kwargs: dict[str, Any] | None = None, gpu_config: MultiGPUConfig = MultiGPUConfig(num_inference_gpus=1, num_training_gpus=1)):
+ def __init__(self, lm: "LM", train_kwargs: dict[str, Any] | None = None):
self.lm = lm
self.train_kwargs = train_kwargs or {}
- self.gpu_config = gpu_config
self.checkpoints = {}
self.last_checkpoint = None
- self.gpu_config = gpu_config
@abstractmethod
diff --git a/dspy/clients/utils_finetune.py b/dspy/clients/utils_finetune.py
index 8e6a49518..9ee5ba620 100644
--- a/dspy/clients/utils_finetune.py
+++ b/dspy/clients/utils_finetune.py
@@ -40,14 +40,17 @@ class GRPOChatData(TypedDict):
reward: float
-GRPOGroup = list[GRPOChatData]
-
-
-class MultiGPUConfig(TypedDict):
- # Number of GPUs to use for inference
- num_inference_gpus: int
- # Number of GPUs to use for training
- num_training_gpus: int
+class GRPOGroup(TypedDict):
+ batch_id: int | None
+ group: list[GRPOChatData]
+
+class GRPOStatus(TypedDict):
+ job_id: str
+ status: str | None = None
+ current_model: str
+ checkpoints: dict[str, str]
+ last_checkpoint: str | None = None
+ pending_batch_ids: list[int] = []
def infer_data_format(adapter: Adapter) -> str:
diff --git a/dspy/teleprompt/grpo.py b/dspy/teleprompt/grpo.py
index d3f80935e..7998d2608 100644
--- a/dspy/teleprompt/grpo.py
+++ b/dspy/teleprompt/grpo.py
@@ -1,12 +1,14 @@
import logging
import random
-from collections import Counter
+import time
+from collections import Counter, deque
from typing import Any, Callable, Literal
from dspy.adapters.base import Adapter
from dspy.adapters.chat_adapter import ChatAdapter
+from dspy.adapters.xml_adapter import XMLAdapter
from dspy.clients.lm import LM
-from dspy.clients.utils_finetune import GRPOGroup, MultiGPUConfig, TrainDataFormat
+from dspy.clients.utils_finetune import GRPOGroup, GRPOStatus, TrainDataFormat
from dspy.dsp.utils.settings import settings
from dspy.evaluate.evaluate import Evaluate
from dspy.primitives.example import Example
@@ -41,7 +43,6 @@ class GRPO(FinetuneTeleprompter):
format_failure_score: float = -1,
variably_invoked_predictor_grouping_mode: Literal["truncate"] | Literal["fill"] | Literal["ragged"] = "truncate",
variably_invoked_predictor_fill_strategy: Literal["randint"] | Literal["max"] | None = None,
- gpu_config: MultiGPUConfig = MultiGPUConfig(num_inference_gpus=1, num_training_gpus=1),
):
super().__init__(train_kwargs=train_kwargs)
self.metric = metric
@@ -58,7 +59,6 @@ class GRPO(FinetuneTeleprompter):
self.report_train_scores = report_train_scores
self.failure_score = failure_score
self.format_failure_score = format_failure_score
- self.gpu_config = gpu_config
assert failure_score > format_failure_score, "failure_score must be greater than format_failure_score since the range [format_failure_score, failure_score] is used to provide dspy formatting rewards"
@@ -79,6 +79,8 @@ class GRPO(FinetuneTeleprompter):
self.shuffled_trainset_ids = []
self.epoch = -1
self.id_freqs = Counter()
+ self.fulfilled_batch_ids = []
+ self.pending_batch_ids = []
def validate_trace_data_and_log_issues(
self,
@@ -334,7 +336,7 @@ class GRPO(FinetuneTeleprompter):
job_key = (pred.lm, data_key)
if job_key not in grpo_training_jobs:
train_kwargs = self.train_kwargs[pred.lm]
- job = pred.lm.reinforce(train_kwargs=train_kwargs, gpu_config=self.gpu_config)
+ job = pred.lm.reinforce(train_kwargs=train_kwargs)
grpo_training_jobs[job_key] = job
self.report_validation_metrics(
@@ -345,6 +347,8 @@ class GRPO(FinetuneTeleprompter):
step_idx=-1,
)
+ # Queue of GRPO groups per training job; key is (LM, data_key)
+ group_queues = {}
logger.info("Starting the GRPO training loop...")
for train_step_idx in range(self.num_train_steps):
logger.info(f"GRPO training step {train_step_idx + 1}/{self.num_train_steps}...")
@@ -353,6 +357,17 @@ class GRPO(FinetuneTeleprompter):
original_trainset=trainset,
train_step_idx=train_step_idx,
)
+ def _any_available_for_step():
+ for _, job in grpo_training_jobs.items():
+ grpo_status: GRPOStatus = job.get_status()
+ pending_batch_ids = grpo_status["pending_batch_ids"]
+ available = set(pending_batch_ids) - set(self.fulfilled_batch_ids)
+ if available:
+ return True
+ return False
+
+ while not _any_available_for_step():
+ time.sleep(1)
logger.info("Bootstrapping data...")
trace_data = [[[] for _ in range(len(teachers))] for _ in range(len(subsample_training_dataset))]
@@ -367,6 +382,7 @@ class GRPO(FinetuneTeleprompter):
capture_failed_parses=True,
failure_score=self.failure_score,
format_failure_score=self.format_failure_score,
+ log_format_failures=True,
)
for data_dict in round_data:
example_ind_in_subsample = data_dict["example_ind"] % len(subsample_training_dataset)
@@ -448,7 +464,7 @@ class GRPO(FinetuneTeleprompter):
predictor = trace_instance[0]
pred_lm = predictor.lm
- adapter = self.adapter[pred_lm] or settings.adapter or ChatAdapter()
+ adapter = self.adapter[pred_lm] or settings.adapter or XMLAdapter()
assert isinstance(adapter, ChatAdapter), f"Adapter {adapter} is not a ChatAdapter. GRPO training is not supported for this adapter."
# TODO(Lakshya): Currently we exclude demos from the training data
# TODO(GRPO Team): Use build_call_data_from_trace (from bootstrap_finetune) instead of
@@ -519,19 +535,58 @@ class GRPO(FinetuneTeleprompter):
# addition to updating any teacher programs that share the same
# LM.
logger.info("Invoking GRPO training step...")
- for (_, data_key), job in grpo_training_jobs.items():
+ for (lm_for_job, data_key), job in grpo_training_jobs.items():
train_data: list[GRPOGroup] = sum(train_batch_per_predictor, []) if data_key is None else train_batch_per_predictor[data_key] #noqa: RUF017
for group in train_data:
if len(group) != self.num_rollouts_per_grpo_step:
# TODO(GRPO Team): This is very undesirable. This occurs only because in some of the generations, the model does not follow the correct dspy format.
- # The ideal solution is to identify the full response string in that predictor's group, and then assign a high-negative (user-configurable) reward to that group.
-
+ # The ideal solution is to identify the full response string in that predictor's group, and then assign a high-negative (user-configurable) reward to that group.
# Pad the group to the expected number of generations by repeating the whole group, might require multiple iterations
while len(group) < self.num_rollouts_per_grpo_step:
group.extend(group[:min(self.num_rollouts_per_grpo_step - len(group), len(group))])
assert len(group) == self.num_rollouts_per_grpo_step, f"Number of completions {len(group)} does not match the expected number self.num_rollouts_per_grpo_step={self.num_rollouts_per_grpo_step}"
- job.step(train_data=train_data, train_data_format=TrainDataFormat.GRPO_CHAT)
+ # Determine available batch IDs for this specific job
+ grpo_status: GRPOStatus = job.get_status()
+ pending_batch_ids = grpo_status["pending_batch_ids"]
+ available_batch_ids = list(set(pending_batch_ids) - set(self.fulfilled_batch_ids))
+ if not available_batch_ids:
+ continue
+
+ # Initialize and (re)fill the queue for this job as needed
+ job_key = (lm_for_job, data_key)
+ q = group_queues.setdefault(job_key, deque())
+
+ # Refill strategy: add randomized copies of current train_data until we can satisfy all batch_ids
+ if len(q) < len(available_batch_ids) and len(train_data) > 0:
+ need = len(available_batch_ids) - len(q)
+ while need > 0:
+ # Shuffle by sampling without replacement
+ shuffled = self.rng.sample(train_data, k=len(train_data))
+ q.extend(shuffled)
+ need -= len(shuffled)
+
+ # Build GRPOGroup items by popping from the queue; fallback to random selection if needed
+ final_train_data: list[GRPOGroup] = []
+ for bid in available_batch_ids:
+ if q:
+ grp = q.popleft()
+ else:
+ # Fallback: choose randomly from current train_data (or flattened pool) if queue underflows
+ fallback_pool = train_data if len(train_data) > 0 else sum(train_batch_per_predictor, [])
+ if len(fallback_pool) == 0:
+ # Nothing to send for this job
+ continue
+ grp = self.rng.choice(fallback_pool)
+ final_train_data.append({"batch_id": bid, "group": grp})
+
+ if not final_train_data:
+ continue
+
+ # Track fulfilled IDs to avoid reuse
+ self.fulfilled_batch_ids.extend([item["batch_id"] for item in final_train_data])
+
+ job.step(train_data=final_train_data, train_data_format=TrainDataFormat.GRPO_CHAT)
logger.info(f"GRPO training step {train_step_idx + 1}/{self.num_train_steps} completed.")