DSPy: The framework for programming—not prompting—language models
Python
Add GRPO Optimizer to DSPy (#8171)
Noah Ziems88ae78a2d115
diff --git a/docs/docs/tutorials/classification_finetuning/index.ipynb b/docs/docs/tutorials/classification_finetuning/index.ipynbindex d7c7f4300..4864183b1 100644--- a/docs/docs/tutorials/classification_finetuning/index.ipynb+++ b/docs/docs/tutorials/classification_finetuning/index.ipynb@@ -211,7 +211,7 @@},{"cell_type": "code",- "execution_count": 5,+ "execution_count": null,"metadata": {},"outputs": [],"source": [diff --git a/dspy/adapters/json_adapter.py b/dspy/adapters/json_adapter.pyindex b5941a7cf..018bd5f41 100644--- a/dspy/adapters/json_adapter.py+++ b/dspy/adapters/json_adapter.py@@ -62,8 +62,8 @@ class JSONAdapter(ChatAdapter):structured_output_model = _get_structured_outputs_response_format(signature)lm_kwargs["response_format"] = structured_output_modelreturn super().__call__(lm, lm_kwargs, signature, demos, inputs)- except Exception as e:- logger.warning(f"Failed to use structured output format. Falling back to JSON mode. Error: {e}")+ except Exception:+ logger.warning("Failed to use structured output format, falling back to JSON mode.")try:lm_kwargs["response_format"] = {"type": "json_object"}return super().__call__(lm, lm_kwargs, signature, demos, inputs)diff --git a/dspy/clients/lm.py b/dspy/clients/lm.pyindex 6f7edfd58..d69d4533a 100644--- a/dspy/clients/lm.py+++ b/dspy/clients/lm.py@@ -11,7 +11,7 @@ from asyncer import syncifyimport dspyfrom dspy.clients.cache import request_cachefrom dspy.clients.openai import OpenAIProvider-from dspy.clients.provider import Provider, TrainingJob+from dspy.clients.provider import Provider, TrainingJob, ReinforceJobfrom dspy.clients.utils_finetune import TrainDataFormatfrom dspy.dsp.utils.settings import settingsfrom dspy.utils.callback import BaseCallback@@ -188,10 +188,6 @@ class LM(BaseLM):) -> TrainingJob:from dspy import settings as settings- err = "Fine-tuning is an experimental feature."- err += " Set `dspy.settings.experimental` to `True` to use it."- assert settings.experimental, err-err = f"Provider {self.provider} does not support fine-tuning."assert self.provider.finetunable, err@@ -212,6 +208,17 @@ class LM(BaseLM):return job+ def reinforce(self, train_kwargs) -> ReinforceJob:+ # TODO(GRPO Team): Should we return an initialized job here?+ from dspy import settings as settings++ 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)+ job.initialize()+ return job+def _run_finetune_job(self, job: TrainingJob):# TODO(enhance): We should listen for keyboard interrupts somewhere.# Requires TrainingJob.cancel() to be implemented for each provider.diff --git a/dspy/clients/lm_local_arbor.py b/dspy/clients/lm_local_arbor.pynew file mode 100644index 000000000..e7bf1debc--- /dev/null+++ b/dspy/clients/lm_local_arbor.py@@ -0,0 +1,514 @@+import time+import requests+from datetime import datetime+from typing import Any, Dict, List, Optional, Union, TypedDict, TYPE_CHECKING++import openai++import dspy+from dspy.clients.provider import TrainingJob, ReinforceJob, Provider+from dspy.clients.utils_finetune import TrainDataFormat, TrainingStatus, GRPOGroup, 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)+ self.provider_file_id = None+ self.provider_job_id = None++ def cancel(self):+ 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++ if self.provider_file_id is not None:+ if ArborProvider.does_file_exist(self.provider_file_id):+ openai.files.delete(self.provider_file_id)+ self.provider_file_id = None++ super().cancel()++ def status(self) -> TrainingStatus:+ status = ArborProvider.get_training_status(self.provider_job_id)+ return status+++class ArborReinforceJob(ReinforceJob):+ DEFAULT_TRAIN_KWARGS = {+ "update_interval": 10,+ "temperature": 0.9,+ "beta": 0.04,+ "num_iterations": 1,+ "per_device_train_batch_size": 8,+ "learning_rate": 1e-6,+ "gradient_accumulation_steps": 1,+ # 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",+ "max_prompt_length": None,+ "max_completion_length": None,+ "gradient_checkpointing_kwargs": None,+ "bf16": False,+ "scale_rewards": True,+ "max_grad_norm": 1.0,+ "report_to": "none",+ "log_completions": True,+ "logging_steps": 100,+ # By default, none is the model's max context length+ "max_context_length": None,+ "lora": False+ }++ def __init__(self, lm: "LM", train_kwargs: GRPOTrainKwargs):+ # 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")++ self.lm = lm+ self.train_kwargs = train_kwargs+ self.provider_job_id = None+ self.checkpoints = {}+ self.last_checkpoint = None++ def initialize(self):+ # TODO(GRPO Team): Set provider job ID+ num_generations = self.train_kwargs.get("num_generations")+ update_interval = self.train_kwargs.get("update_interval", self.DEFAULT_TRAIN_KWARGS["update_interval"])+ temperature = self.train_kwargs.get("temperature", self.DEFAULT_TRAIN_KWARGS["temperature"])+ beta = self.train_kwargs.get("beta", self.DEFAULT_TRAIN_KWARGS["beta"])+ num_iterations = self.train_kwargs.get("num_iterations", self.DEFAULT_TRAIN_KWARGS["num_iterations"])+ per_device_train_batch_size = self.train_kwargs.get("per_device_train_batch_size", self.DEFAULT_TRAIN_KWARGS["per_device_train_batch_size"])+ learning_rate = self.train_kwargs.get("learning_rate", self.DEFAULT_TRAIN_KWARGS["learning_rate"])+ gradient_accumulation_steps = self.train_kwargs.get("gradient_accumulation_steps", self.DEFAULT_TRAIN_KWARGS["gradient_accumulation_steps"])+ gradient_checkpointing = self.train_kwargs.get("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"])+ 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"])+ bf16 = self.train_kwargs.get("bf16", self.DEFAULT_TRAIN_KWARGS["bf16"])+ scale_rewards = self.train_kwargs.get("scale_rewards", self.DEFAULT_TRAIN_KWARGS["scale_rewards"])+ gradient_checkpointing_kwargs = self.train_kwargs.get("gradient_checkpointing_kwargs", self.DEFAULT_TRAIN_KWARGS["gradient_checkpointing_kwargs"])+ max_grad_norm = self.train_kwargs.get("max_grad_norm", self.DEFAULT_TRAIN_KWARGS["max_grad_norm"])+ report_to = self.train_kwargs.get("report_to", self.DEFAULT_TRAIN_KWARGS["report_to"])+ log_completions = self.train_kwargs.get("log_completions", self.DEFAULT_TRAIN_KWARGS["log_completions"])+ logging_steps = self.train_kwargs.get("logging_steps", self.DEFAULT_TRAIN_KWARGS["logging_steps"])+ 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"])+ api_base = self.lm.kwargs["api_base"]++ suffix = "dspy"+ finetune_model = ArborProvider._remove_provider_prefix(self.lm.model)+ data = {+ 'model': finetune_model,+ 'suffix': suffix,+ 'num_generations': num_generations,+ 'update_interval': update_interval,+ '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,+ }+ 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}"+ self.lm.model = ArborProvider._add_provider_prefix(finetune_model)+ # self.provider_job_id = response.json().get("job_id") # TODO: To be updated++ def _run_grpo_step_one_group(self, train_group: GRPOGroup, train_data_format: Optional[Union[TrainDataFormat, str]] = None):+ # TODO: Check that the data follows the intended format+ api_base = self.lm.kwargs["api_base"]+ # api_key = self.lm.kwargs["api_key"]++ finetune_model = ArborProvider._remove_provider_prefix(self.lm.model)+ data = {+ 'model': finetune_model,+ 'update_inference_model': True,+ 'batch': train_group+ }+ url = f"{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}"+ response = response.json()+ assert "current_model" in response, f"Response does not contain the next model ID to be used: {response}"+ current_model = response["current_model"]+ self.lm.model = ArborProvider._add_provider_prefix(current_model)++ def step(self, train_data: List[GRPOGroup], train_data_format: Optional[Union[TrainDataFormat, str]]):+ # Note: TrainDataFormat specifies the format for the inner most dict.+ # Because we run GRPO at the group level, train_data will be a list of+ # groups, where each group is a list of GRPOChatData. Our teleprompters+ # ensure that we pass the right data format.+ # We can consider making this distinction clearer, e.g., by having two+ # different step methods or changing our smallets data format to be the+ # GRPO group.+ # TODO: Support step on the server side+ assert train_data_format == TrainDataFormat.GRPO_CHAT, f"GRPO only supports the GRPO_CHAT data format. Got {train_data_format} instead."+ for group in train_data:+ self._run_grpo_step_one_group(group, train_data_format)++ def update_model(self):+ api_base = self.lm.kwargs["api_base"]++ url = f"{api_base}fine_tuning/grpo/update_model"+ headers = {'Content-Type': 'application/json'}+ response = requests.post(url, headers=headers)+ assert response.status_code == 200, f"Failed to update model: {response.text}"++ response = response.json()+ current_model = response["current_model"]+ self.lm.model = ArborProvider._add_provider_prefix(current_model)++ def save_checkpoint(self, checkpoint_name: str, score: float = None):+ api_base = self.lm.kwargs["api_base"]+ url = f"{api_base}fine_tuning/grpo/checkpoint"+ headers = {'Content-Type': 'application/json'}+ body = {"checkpoint_name": checkpoint_name}+ response = requests.post(url, headers=headers, json=body)+ assert response.status_code == 200, f"Failed to save checkpoint: {response.text}"+ response = response.json()++ current_model = response["current_model"]+ last_checkpoint = response["last_checkpoint"]+ checkpoints = response["checkpoints"]+ checkpoint_model_path = checkpoints[last_checkpoint]+ self.checkpoints[last_checkpoint] = {+ 'model_path':checkpoint_model_path,+ 'score': score,+ }+ self.last_checkpoint = last_checkpoint++ def terminate(self):+ api_base = self.lm.kwargs["api_base"]++ url = f"{api_base}fine_tuning/grpo/terminate"+ headers = {'Content-Type': 'application/json'}+ response = requests.post(url, headers=headers)+ assert response.status_code == 200, f"Failed to terminate GRPO: {response.text}"++ response = response.json()+ current_model = response["current_model"]+ self.lm.model = ArborProvider._add_provider_prefix(current_model)++ def cancel(self):+ 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)+ return status+++class ArborProvider(Provider):++ def __init__(self):+ super().__init__()+ self.finetunable = True+ self.reinforceable = True+ self.TrainingJob = ArborTrainingJob+ self.ReinforceJob = ArborReinforceJob++ @staticmethod+ def launch(lm: "LM", launch_kwargs: Optional[Dict[str, Any]] = None):+ model = ArborProvider._remove_provider_prefix(lm.model)+ # TODO: Handle this on the server side+ if model.startswith("huggingface/"):+ model = model[len("huggingface/"):]++ api_base = lm.kwargs["api_base"]+ api_key = lm.kwargs["api_key"]++ launch_kwargs = launch_kwargs or lm.launch_kwargs++ # Make request to launch endpoint+ response = requests.post(+ f"{api_base}chat/launch",+ json={"model": model, "launch_kwargs": launch_kwargs}+ )++ if response.status_code != 200:+ raise Exception(f"Failed to launch model. Status code: {response.status_code}, Response: {response.text}")++ print(f"Inference server for model {model} launched successfully")+++ @staticmethod+ def kill(lm: "LM", launch_kwargs: Optional[Dict[str, Any]] = None):+ api_base = lm.kwargs["api_base"]+ api_key = lm.kwargs["api_key"]++ response = requests.post(+ f"{api_base}chat/kill",+ )++ if response.status_code != 200:+ raise Exception(f"Failed to kill model. Status code: {response.status_code}, Response: {response.text}")++ print("Inference killed successfully")++ @staticmethod+ def _remove_provider_prefix(model: str) -> str:+ if model.startswith("openai/"):+ model = model[7:]+ if model.startswith("arbor:"):+ model = model[6:]+ return model++ @staticmethod+ def _add_provider_prefix(model: str) -> str:+ if not model.startswith("openai/arbor:"):+ model = "openai/arbor:" + model+ return model++ @staticmethod+ def _get_arbor_base_api():+ # TODO: We will delete this method once we start passing the LM object+ # to finetune.+ import dspy.settings as settings+ if not hasattr(settings, "arbor_api_base"):+ raise ValueError("Arbor API base not set. Please set the `dspy.settings.arbor_api_base` to the URL for the Arbor server (e.g. 'http://localhost:8000/v1/').")+ return dspy.settings.arbor_api_base++ @staticmethod+ def finetune(+ job: ArborTrainingJob,+ model: str,+ train_data: List[Dict[str, Any]],+ train_data_format: Optional[TrainDataFormat],+ train_kwargs: Optional[Dict[str, Any]] = None+ ) -> str:+ # TODO: We want to re-factor finetune so that it takes in an LM.+ # Until then, we use the following to get the api information. The+ # following is a dummy call to ensure that dspy.settings.arbor_base_api+ # is set.+ ArborProvider._get_arbor_base_api()++ model = ArborProvider._remove_provider_prefix(model)++ print("[Arbor Provider] Validating the data format")+ ArborProvider.validate_data_format(train_data_format)++ print("[Arbor Provider] Saving the data to a file")+ data_path = save_data(train_data)+ print(f"[Arbor Provider] Data saved to {data_path}")++ print("[Arbor Provider] Uploading the data to the provider")+ provider_file_id = ArborProvider.upload_data(data_path)+ job.provider_file_id = provider_file_id++ print("[Arbor Provider] Starting remote training")+ provider_job_id = ArborProvider._start_remote_training(+ train_file_id=job.provider_file_id,+ model=model,+ train_kwargs=train_kwargs,+ )+ job.provider_job_id = provider_job_id+ print(f"[Arbor Provider] Job started with the Arbor Job ID {provider_job_id}")++ print("[Arbor Provider] Waiting for training to complete")+ ArborProvider.wait_for_job(job, train_kwargs)++ print("[Arbor Provider] Attempting to retrieve the trained model")+ model = ArborProvider.get_trained_model(job)+ print(f"[Arbor Provider] Model retrieved: {model}")++ return ArborProvider._add_provider_prefix(model)++ @staticmethod+ def does_job_exist(job_id: str, training_kwargs: Dict[str, Any]) -> bool:+ try:+ original_base_url = openai.base_url+ openai.base_url = ArborProvider._get_arbor_base_api()+ openai.fine_tuning.jobs.retrieve(job_id)+ openai.base_url = original_base_url+ return True+ except Exception:+ return False++ @staticmethod+ def does_file_exist(file_id: str, training_kwargs: Dict[str, Any]) -> bool:+ try:+ original_base_url = openai.base_url+ openai.base_url = ArborProvider._get_arbor_base_api()+ openai.files.retrieve(file_id)+ openai.base_url = original_base_url+ return True+ except Exception:+ return False++ @staticmethod+ def is_terminal_training_status(status: TrainingStatus) -> bool:+ return status in [+ TrainingStatus.succeeded,+ TrainingStatus.failed,+ TrainingStatus.cancelled,+ ]++ @staticmethod+ def get_training_status(job_id: str, training_kwargs: Dict[str, Any]) -> TrainingStatus:+ provider_status_to_training_status = {+ "validating_files": TrainingStatus.pending,+ "queued": TrainingStatus.pending,+ "running": TrainingStatus.running,+ "succeeded": TrainingStatus.succeeded,+ "failed": TrainingStatus.failed,+ "cancelled": TrainingStatus.cancelled,+ "pending": TrainingStatus.pending,+ "pending_pause": TrainingStatus.pending,+ "pending_resume": TrainingStatus.pending,+ "paused": TrainingStatus.pending,+ "pending_cancel": TrainingStatus.pending,+ }++ if job_id is None:+ print("There is no active job.")+ return TrainingStatus.not_started++ err_msg = f"Job with ID {job_id} does not exist."+ assert ArborProvider.does_job_exist(job_id, training_kwargs), err_msg++ original_base_url = openai.base_url+ openai.base_url = ArborProvider._get_arbor_base_api()+ provider_job = openai.fine_tuning.jobs.retrieve(job_id)+ openai.base_url = original_base_url++ provider_status = provider_job.status+ status = provider_status_to_training_status[provider_status]++ return status++ @staticmethod+ def validate_data_format(data_format: TrainDataFormat):+ supported_data_formats = [+ TrainDataFormat.CHAT,+ TrainDataFormat.COMPLETION,+ TrainDataFormat.GRPO_CHAT,+ ]++ if data_format not in supported_data_formats:+ err_msg = f"Arbor does not support the data format {data_format}."+ raise ValueError(err_msg)++ @staticmethod+ def upload_data(data_path: str, training_kwargs: Dict[str, Any]) -> str:+ original_base_url = openai.base_url+ openai.base_url = ArborProvider._get_arbor_base_api()+ provider_file = openai.files.create(+ file=open(data_path, "rb"),+ purpose="fine-tune",+ )+ openai.base_url = original_base_url++ return provider_file.id++ @staticmethod+ def _start_remote_training(+ train_file_id: str,+ model: str,+ train_kwargs: Dict[str, Any]+ ) -> str:+ train_kwargs = train_kwargs or {}+ original_base_url = openai.base_url+ openai.base_url = ArborProvider._get_arbor_base_api()+ provider_job = openai.fine_tuning.jobs.create(+ model=model,+ training_file=train_file_id,+ hyperparameters=train_kwargs,+ )+ openai.base_url = original_base_url+ return provider_job.id++ @staticmethod+ def wait_for_job(+ job: TrainingJob,+ training_kwargs: Dict[str, Any],+ poll_frequency: int = 20,+ ):+ done = False+ cur_event_id = None+ reported_estimated_time = False+ while not done:+ # Report estimated time if not already reported+ if not reported_estimated_time:++ original_base_url = openai.base_url+ openai.base_url = ArborProvider._get_arbor_base_api()+ remote_job = openai.fine_tuning.jobs.retrieve(job.provider_job_id)+ openai.base_url = original_base_url++ timestamp = remote_job.estimated_finish+ if timestamp:+ estimated_finish_dt = datetime.fromtimestamp(timestamp)+ delta_dt = estimated_finish_dt - datetime.now()+ print(f"[Arbor Provider] The Arbor estimated time remaining is: {delta_dt}")+ reported_estimated_time = True++ # Get new events+ original_base_url = openai.base_url+ openai.base_url = ArborProvider._get_arbor_base_api()+ page = openai.fine_tuning.jobs.list_events(fine_tuning_job_id=job.provider_job_id, limit=1)+ openai.base_url = original_base_url++ new_event = page.data[0] if page.data else None+ if new_event and new_event.id != cur_event_id:+ dt = datetime.fromtimestamp(new_event.created_at)+ print(f"[Arbor Provider] {dt} {new_event.message}")+ cur_event_id = new_event.id++ # Sleep and update the flag+ time.sleep(poll_frequency)+ done = ArborProvider.is_terminal_training_status(job.status())++ @staticmethod+ def get_trained_model(job, training_kwargs: Dict[str, Any]):+ status = job.status()+ if status != TrainingStatus.succeeded:+ err_msg = f"Job status is {status}."+ err_msg += f" Must be {TrainingStatus.succeeded} to retrieve model."+ raise Exception(err_msg)++ original_base_url = openai.base_url+ openai.base_url = ArborProvider._get_arbor_base_api()+ provider_job = openai.fine_tuning.jobs.retrieve(job.provider_job_id)+ openai.base_url = original_base_url++ finetuned_model = provider_job.fine_tuned_model+ return finetuned_modeldiff --git a/dspy/clients/provider.py b/dspy/clients/provider.pyindex b73f577c7..1722a586e 100644--- a/dspy/clients/provider.py+++ b/dspy/clients/provider.py@@ -35,10 +35,47 @@ class TrainingJob(Future):raise NotImplementedError++class ReinforceJob:+ def __init__(self, lm: "LM", train_kwargs: Optional[Dict[str, Any]] = None):+ self.lm = LM+ self.train_kwargs = train_kwargs or {}+ self.checkpoints = {}+ self.last_checkpoint = None++ @abstractmethod+ def initialize(self):+ raise NotImplementedError++ @abstractmethod+ def step(self, train_data: List[Dict[str, Any]], train_data_format: Optional[Union[TrainDataFormat, str]] = None):+ raise NotImplementedError++ @abstractmethod+ def terminate(self):+ raise NotImplementedError++ @abstractmethod+ def update_model(self):+ raise NotImplementedError++ @abstractmethod+ def save_checkpoint(self, checkpoint_name: str):+ raise NotImplementedError++ def cancel(self):+ raise NotImplementedError++ def status(self):+ raise NotImplementedError++class Provider:def __init__(self):self.finetunable = False+ self.reinforceable = Falseself.TrainingJob = TrainingJob+ self.ReinforceJob = ReinforceJob@staticmethoddef is_provider_model(model: str) -> bool:diff --git a/dspy/clients/utils_finetune.py b/dspy/clients/utils_finetune.pyindex 7d83c741f..086914c9a 100644--- a/dspy/clients/utils_finetune.py+++ b/dspy/clients/utils_finetune.py@@ -1,6 +1,6 @@import osfrom enum import Enum-from typing import Any, Dict, List, Optional+from typing import Any, Dict, List, Literal, Optional, TypedDict, Unionimport ujson@@ -9,11 +9,6 @@ from dspy.adapters.base import Adapterfrom dspy.utils.caching import DSPY_CACHEDIR-class TrainDataFormat(str, Enum):- CHAT = "chat"- COMPLETION = "completion"--class TrainingStatus(str, Enum):not_started = "not_started"pending = "pending"@@ -23,6 +18,31 @@ class TrainingStatus(str, Enum):cancelled = "cancelled"+class TrainDataFormat(str, Enum):+ CHAT = "chat"+ COMPLETION = "completion"+ GRPO_CHAT = "grpo_chat"+++class Message(TypedDict):+ role: Union[Literal["user"], Literal["assistant"], Literal["system"]]+ content: str+++class MessageAssistant(TypedDict):+ role: Literal["assistant"]+ content: str+++class GRPOChatData(TypedDict):+ messages: List[Message]+ completion: MessageAssistant+ reward: float+++GRPOGroup = List[GRPOChatData]++def infer_data_format(adapter: Adapter) -> str:if isinstance(adapter, dspy.ChatAdapter):return TrainDataFormat.CHATdiff --git a/dspy/dsp/utils/settings.py b/dspy/dsp/utils/settings.pyindex 983927f33..0bbac1af7 100644--- a/dspy/dsp/utils/settings.py+++ b/dspy/dsp/utils/settings.py@@ -14,7 +14,6 @@ DEFAULT_CONFIG = dotdict(bypass_suggest=False,assert_failures=0,suggest_failures=0,- experimental=False,backoff_time=10,callbacks=[],async_max_workers=8,@@ -24,8 +23,8 @@ DEFAULT_CONFIG = dotdict(usage_tracker=None,caller_predict=None,stream_listeners=[],- provide_traceback=False, # Whether to include traceback information in error logs.- num_threads=8, # Number of threads to use for parallel processing.+ provide_traceback=False, # Whether to include traceback information in error logs.+ num_threads=8, # Number of threads to use for parallel processing.)# Global base configuration and owner trackingdiff --git a/dspy/teleprompt/bettertogether.py b/dspy/teleprompt/bettertogether.pyindex bad685880..64c613030 100644--- a/dspy/teleprompt/bettertogether.py+++ b/dspy/teleprompt/bettertogether.py@@ -5,7 +5,7 @@ from typing import Callable, List, Optionalimport dspyfrom dspy.primitives.example import Examplefrom dspy.primitives.program import Program-from dspy.teleprompt.bootstrap_finetune import BootstrapFinetune, prepare_student, set_missing_predictor_lms, launch_lms, kill_lms+from dspy.teleprompt.bootstrap_finetune import BootstrapFinetune, prepare_student, all_predictors_have_lms, launch_lms, kill_lmsfrom dspy.teleprompt.random_search import BootstrapFewShotWithRandomSearchfrom dspy.teleprompt.teleprompt import Teleprompter@@ -66,7 +66,7 @@ class BetterTogether(Teleprompter):# TODO: Prepare student returns student.reset_copy(), which is what gets# optimized. We should make this clear in the doc comments.student = prepare_student(student)- set_missing_predictor_lms(student)+ all_predictors_have_lms(student)# Make a shallow copy of the trainset, so that we don't change the order# of the examples in the original trainsetdiff --git a/dspy/teleprompt/bootstrap_finetune.py b/dspy/teleprompt/bootstrap_finetune.pyindex 354426594..7ce5787cc 100644--- a/dspy/teleprompt/bootstrap_finetune.py+++ b/dspy/teleprompt/bootstrap_finetune.py@@ -1,5 +1,6 @@import loggingfrom collections import defaultdict+from dataclasses import dataclassfrom typing import Any, Callable, Dict, List, Optional, Unionimport dspy@@ -13,6 +14,7 @@ from dspy.predict.predict import Predictfrom dspy.primitives.example import Examplefrom dspy.primitives.program import Programfrom dspy.teleprompt.teleprompt import Teleprompter+from dspy.utils.exceptions import AdapterParseErrorlogger = logging.getLogger(__name__)@@ -64,7 +66,7 @@ class BootstrapFinetune(FinetuneTeleprompter):# that the default DSPy logger logs info level messages in notebook# environments.logger.info("Preparing the student and teacher programs...")- set_missing_predictor_lms(student)+ all_predictors_have_lms(student)logger.info("Bootstrapping data...")trace_data = []@@ -73,10 +75,7 @@ class BootstrapFinetune(FinetuneTeleprompter):teachers = [prepare_teacher(student, t) for t in teachers]num_threads = self.num_threads or dspy.settings.num_threadsfor t in teachers:- set_missing_predictor_lms(t)- trace_data += bootstrap_trace_data(- program=t, dataset=trainset, metric=self.metric, num_threads=num_threads- )+ trace_data += bootstrap_trace_data(program=t, dataset=trainset, metric=self.metric, num_threads=num_threads)logger.info("Preparing the train data...")key_to_data = {}@@ -187,6 +186,9 @@ class BootstrapFinetune(FinetuneTeleprompter):return data, data_format+# Note: Shared below are useful functions for preparing student/teacher programs+# Similar methods are implemented separately and used by other DSPy+# teleprompters. These can be moved to shared locations.def build_call_data_from_trace(trace: List[Dict],pred_ind: int,@@ -206,11 +208,22 @@ def build_call_data_from_trace(return call_data+@dataclass+class FailedPrediction:+ completion_text: str+ format_reward: Union[float, None] = None++def bootstrap_trace_data(program: Program,dataset: List[Example],metric: Optional[Callable] = None,num_threads: Optional[int] = None,+ raise_on_error=True,+ capture_failed_parses=False,+ failure_score: float = 0,+ format_failure_score: float = -1,+ log_format_failures: bool = False,) -> List[Dict[str, Any]]:# Return a list of dicts with the following keys: example_ind, example, prediction, trace, and score# (if metric != None)@@ -219,22 +232,82 @@ def bootstrap_trace_data(num_threads=num_threads,display_progress=True,return_outputs=True,- provide_traceback=True, # TODO(check with team)+ provide_traceback=False, # TODO(check with team)+ max_errors=len(dataset) * 10, # TODO(check with team)+ failure_score=failure_score,)def wrapped_metric(example, prediction, trace=None):prediction, _ = prediction+ if isinstance(prediction, FailedPrediction):+ return prediction.format_reward or format_failure_scorereturn metric(example, prediction, trace) if metric else Truedef wrapped_program(**kwargs):with dspy.context(trace=[]):- return program(**kwargs), dspy.settings.trace.copy()+ try:+ return program(**kwargs), dspy.settings.trace.copy()+ except AdapterParseError as e:+ completion_str = e.lm_response+ parsed_result = e.parsed_result+ failed_signature = e.signature+ failed_inputs = kwargs++ present = list(parsed_result.keys()) if parsed_result else None+ expected = list(failed_signature.output_fields.keys())++ found_pred = None+ for pred in program.predictors():+ if pred.signature == failed_signature:+ found_pred = pred+ break+ if found_pred is None:+ raise ValueError(f"Failed to find the predictor for the failed signature: {failed_signature}")++ trace = dspy.settings.trace.copy()+ # Trace is Tuple[signature, inputs, prediction outputs]+ if present:+ failed_pred = FailedPrediction(+ completion_text=completion_str,+ format_reward=format_failure_score+ + (failure_score - format_failure_score) * (present / expected),+ )+ else:+ failed_pred = FailedPrediction(completion_text=completion_str, format_reward=format_failure_score)++ trace.append(+ (+ found_pred,+ failed_inputs,+ failed_pred,+ )+ )++ if log_format_failures:+ logging.warning(+ "Failed to parse output for example. This is likely due to the LLM response not following the adapter's formatting."+ )++ return failed_pred, trace_, outputs = evaluator(wrapped_program, metric=wrapped_metric)data = []for example_ind, (example, prediction, score) in enumerate(outputs):- prediction, trace = prediction+ try:+ prediction, trace = prediction+ except ValueError as ve:+ # TODO(GRPO Team): Often during GRPO bootstrapping, the LLM response does not follow dspy formatting. This leads to a value error.+ # To reproduce this issue, try Qwen/Qwen2.5-Coder-0.5B-Instruct with MATH dataset+ # Proposal(Lakshya): We should capture the incorrectly-formatted LLM response, and store it in the trace, and pass it to in the GRPO group+ # with a high-negative user-configurable score.+ logger.warning(+ "Failed to unpack prediction and trace. This is likely due to the LLM response not following dspy formatting."+ )+ if raise_on_error:+ raise ve+ else:+ continuedata_dict = dict(example=example, prediction=prediction, trace=trace, example_ind=example_ind)if metric:data_dict["score"] = score@@ -270,12 +343,16 @@ def bootstrap_trace_data(# Note: Shared below are useful functions for preparing student/teacher programs# Similar methods are implemented separately and used by other DSPy# teleprompters. These can be moved to shared locations.-def set_missing_predictor_lms(program: Program) -> Program:- # If the predictors do not have LMs, set them to the global LM- for pred in program.predictors():- if not pred.lm:- pred.lm = dspy.settings.lm+def all_predictors_have_lms(program: Program) -> bool:+ """Return True if all predictors in the program have an LM set."""+ return all(pred.lm for pred in program.predictors())++def copy_program_with_lms(program: Program) -> Program:+ pred_lms = [pred.lm for pred in program.predictors()]+ program = program.deepcopy()+ for ind, pred in enumerate(program.predictors()):+ pred.lm = pred_lms[ind]return program@@ -285,15 +362,15 @@ def prepare_student(student: Program) -> Program:# TODO: Should we use reset_copy here? How would it affect the student# program's predictor LMs, if they are set?- student = student.deepcopy()++ # TODO: Should there be a deepcopy here?+ # student = student.deepcopy()return student-def prepare_teacher(student: Program, teacher: Program = None) -> Program:+def prepare_teacher(student: Program, teacher: Optional[Program] = None) -> Program:if teacher is None:- return student.deepcopy()- else:- teacher = teacher.deepcopy()+ return student# Ensuring that the student and teacher are are structurally equivalentassert_structural_equivalency(student, teacher)diff --git a/dspy/teleprompt/grpo.py b/dspy/teleprompt/grpo.pynew file mode 100644index 000000000..d693779cc--- /dev/null+++ b/dspy/teleprompt/grpo.py@@ -0,0 +1,585 @@+from collections import Counter+import logging+import random+from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union++from dspy.adapters.base import Adapter+from dspy.adapters.chat_adapter import ChatAdapter+from dspy.clients.lm import LM+from dspy.clients.utils_finetune import TrainDataFormat, GRPOGroup+from dspy.dsp.utils.settings import settings+from dspy.evaluate.evaluate import Evaluate+from dspy.primitives.example import Example+from dspy.primitives.program import Program+from dspy.teleprompt.bootstrap_finetune import FinetuneTeleprompter, all_predictors_have_lms, assert_structural_equivalency, bootstrap_trace_data, FailedPrediction+++logger = logging.getLogger(__name__)+++class GRPO(FinetuneTeleprompter):+ def __init__(+ self,+ metric: Optional[Callable] = None,+ multitask: bool = True,+ train_kwargs: Optional[Union[Dict[str, Any], Dict[LM, Dict[str, Any]]]] = None,+ adapter: Optional[Union[Adapter, Dict[LM, Adapter]]] = None,+ exclude_demos: bool = False,+ num_threads: int = 6,+ num_train_steps: int = 100,+ seed: int = 0,+ num_dspy_examples_per_grpo_step: int = 1,+ num_rollouts_per_grpo_step: int = 1,+ use_train_as_val: bool = False,+ num_steps_for_val: int = 5,+ report_train_scores: bool = False,+ failure_score: float = 0,+ format_failure_score: float = -1,+ variably_invoked_predictor_grouping_mode: Union[Literal['truncate'], Literal['fill'], Literal['ragged']] = 'truncate',+ variably_invoked_predictor_fill_strategy: Optional[Union[Literal['randint'], Literal['max']]] = None,+ ):+ super().__init__(train_kwargs=train_kwargs)+ self.metric = metric+ self.multitask = multitask+ self.adapter: Dict[LM, Adapter] = self.convert_to_lm_dict(adapter)+ self.exclude_demos = exclude_demos+ self.num_threads = num_threads+ self.num_train_steps = num_train_steps+ self.rng = random.Random(seed)+ self.num_dspy_examples_per_grpo_step = num_dspy_examples_per_grpo_step+ self.num_rollouts_per_grpo_step = num_rollouts_per_grpo_step+ self.use_train_as_val = use_train_as_val+ self.num_steps_for_val = num_steps_for_val+ self.report_train_scores = report_train_scores+ self.failure_score = failure_score+ self.format_failure_score = format_failure_score++ 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"++ if self.use_train_as_val:+ assert report_train_scores, "If use_train_as_val is True, report_train_scores must be True."++ assert exclude_demos, "exclude_demos==False is not supported yet. Please set it to True."+ assert multitask, "independent GRPO training jobs for each predictor in the student program is not supported yet. Please set multitask=True."++ # The backend will be called with a batch of (num_dspy_examples_per_grpo_step * num_rollouts_per_grpo_step * num_predictors) per training set if multitask is True+ # If multitask is False, the backend will be called with a batch of (num_dspy_examples_per_grpo_step * num_rollouts_per_grpo_step) per training job+ self.variably_invoked_predictor_grouping_mode = variably_invoked_predictor_grouping_mode+ if variably_invoked_predictor_grouping_mode == 'fill':+ assert variably_invoked_predictor_fill_strategy is not None, "variably_invoked_predictor_fill_strategy must be set when variably_invoked_predictor_grouping_mode is 'fill'"+ assert variably_invoked_predictor_fill_strategy in ['randint', 'max'], "variably_invoked_predictor_fill_strategy must be either 'randint' or 'max'"+ self.variably_invoked_predictor_fill_strategy = variably_invoked_predictor_fill_strategy++ self.shuffled_trainset_ids = []+ self.epoch = -1+ self.id_freqs = Counter()++ def validate_trace_data_and_log_issues(+ self,+ trace_data: List[List[List[Dict[str, Any]]]],+ subsample_training_dataset: List[Example],+ num_teachers: int,+ num_samples_per_input: int,+ pred_signature_hash_to_ind: Dict[int, int],+ ):+ # At this point, trace_data: List[example_idx -> List[teacher_idx -> [num_samples_per_input * Dict(example, prediction, trace, example_ind, score)]]]+ # Shape of trace is: [dspy_module_invocation_idx -> Tuple[Predictor, PredictorInputs, Prediction]]+ assert len(trace_data) == len(subsample_training_dataset), f"Trace data length {len(trace_data)} does not match the number of examples {len(subsample_training_dataset)}"+ assert len(trace_data[0]) == num_teachers, f"Trace data length {len(trace_data[0])} does not match the number of teachers {num_teachers}"+ # TODO(GRPO Team): Ideally, once the dspy format issue is fixed, this change should be reverted back to being a normal assert.+ if len(trace_data[0][0]) == 0:+ logger.warning(f"Trace data for example {0} and teacher {0} is empty. This is likely due to all examples in the training set input, resulting in the model generating output not following the dspy response format.")+ elif len(trace_data[0][0]) != num_samples_per_input:+ logger.warning(f"Trace data length {len(trace_data[0][0])} does not match the expected number of samples per input {num_samples_per_input}")+ assert "trace" in trace_data[0][0][0], "Trace data does not contain the 'trace' key"+ assert len(trace_data[0][0][0]["trace"]) > 0, "Trace data is empty"+ assert len(trace_data[0][0][0]["trace"][0]) == 3, f"Trace tuple length {len(trace_data[0][0][0]['trace'][0])} does not match the expected length 3"++ for example_data in trace_data:+ for teacher_data in example_data:+ for sample in teacher_data:+ for t in sample["trace"]:+ assert hash(t[0].signature) in pred_signature_hash_to_ind++ def report_validation_metrics(self, student, trainset, valset, logger, step_idx=-1):+ if step_idx == -1 or step_idx == self.num_train_steps - 1 or (step_idx + 1) % self.num_steps_for_val == 0:+ pass+ else:+ return++ if valset is not None:+ # Validation set provided by user+ assert not self.use_train_as_val, "If valset is provided, use_train_as_val must be False."+ assert isinstance(self.num_steps_for_val, int) and self.num_steps_for_val > 0, "num_steps_for_val must be a positive integer."+ if self.report_train_scores:+ if step_idx == -1:+ logger.info("Using user provided validation set and reporting train scores for every validation step in addition.")+ valset_evaluator = Evaluate(+ devset=valset + trainset,+ num_threads=self.num_threads,+ display_progress=True,+ return_all_scores=True,+ return_outputs=False,+ provide_traceback=False, # TODO(check with team)+ max_errors=len(valset)*10, # TODO(check with team)+ failure_score=self.failure_score+ )+ if step_idx == -1:+ logger.info("Evaluating the student program on the train+validation set before training loop...")+ else:+ logger.info(f"Evaluating the student program on the validation set after training step {step_idx + 1}/{self.num_train_steps}")+ valset_evaluation = valset_evaluator(student, metric=self.metric)+ trainset_scores = valset_evaluation[1][len(valset):]+ valset_scores = valset_evaluation[1][:len(valset)]+ trainset_agg = sum(trainset_scores) / len(trainset_scores)+ valset_agg = sum(valset_scores) / len(valset_scores)+ if step_idx == -1:+ logger.info(f"Student program training set score before training loop: {trainset_agg}")+ logger.info(f"Student program validation set score before training loop: {valset_agg}")+ else:+ logger.info(f"Student program training set score after training step {step_idx + 1}/{self.num_train_steps}: {trainset_agg}")+ logger.info(f"Student program validation set score after training step {step_idx + 1}/{self.num_train_steps}: {valset_agg}")+ else:+ if step_idx == -1:+ logger.info("Using user provided validation set and not reporting train scores.")+ valset_evaluator = Evaluate(+ devset=valset,+ num_threads=self.num_threads,+ display_progress=True,+ return_all_scores=True,+ return_outputs=False,+ provide_traceback=False, # TODO(check with team)+ max_errors=len(valset)*10, # TODO(check with team)+ failure_score=self.failure_score+ )+ if step_idx == -1:+ logger.info("Evaluating the student program on the validation set before training loop...")+ else:+ logger.info(f"Evaluating the student program on the validation set after training step {step_idx + 1}/{self.num_train_steps}")+ valset_evaluation = valset_evaluator(student, metric=self.metric)+ if step_idx == -1:+ logger.info(f"Student program validation set score before training loop: {valset_evaluation[0]}")+ else:+ logger.info(f"Student program validation set score after training step {step_idx + 1}/{self.num_train_steps}: {valset_evaluation[0]}")+ else:+ # No validation set provided by user+ if self.report_train_scores:+ assert self.use_train_as_val, "If report_train_scores is True, use_train_as_val must be True when valset is not provided explicitly."+ assert isinstance(self.num_steps_for_val, int) and self.num_steps_for_val > 0, "num_steps_for_val must be a positive integer."+ if step_idx == -1:+ logger.info("Using trainset as validation set.")+ valset_evaluator = Evaluate(+ devset=trainset,+ num_threads=self.num_threads,+ display_progress=True,+ return_all_scores=True,+ return_outputs=False,+ provide_traceback=False, # TODO(check with team)+ max_errors=len(trainset)*10, # TODO(check with team)+ failure_score=self.failure_score+ )+ if step_idx == -1:+ logger.info("Evaluating the student program on the validation set before training loop...")+ else:+ logger.info(f"Evaluating the student program on the validation set after training step {step_idx + 1}/{self.num_train_steps}")+ valset_evaluation = valset_evaluator(student, metric=self.metric)+ if step_idx == -1:+ logger.info(f"Student program training set score before training loop: {valset_evaluation[0]}")+ else:+ logger.info(f"Student program training set score after training step {step_idx + 1}/{self.num_train_steps}: {valset_evaluation[0]}")+ else:+ # No valset provided, and not using train as val+ assert not self.use_train_as_val, "If report_train_scores is False, use_train_as_val must be False."+ if step_idx == -1:+ logger.info("Not using any validation set and not reporting train scores.")++ def update_shuffled_trainset(self, original_trainset):+ self.shuffled_trainset_ids = list(range(len(original_trainset)))+ self.rng.shuffle(self.shuffled_trainset_ids)+ for id in self.shuffled_trainset_ids:+ self.id_freqs[id] += 1++ num_to_pad = self.num_dspy_examples_per_grpo_step - (len(original_trainset) % self.num_dspy_examples_per_grpo_step)+ if num_to_pad > 0:+ # Select ids based on least frequent ids+ for _ in range(num_to_pad):+ selected_id = self.id_freqs.most_common()[::-1][0][0]+ self.shuffled_trainset_ids.append(selected_id)+ self.id_freqs[selected_id] += 1++ def select_training_sample_and_update_shuffled_trainset(+ self,+ original_trainset: List[Example],+ train_step_idx: int,+ ) -> List[Example]:+ base_idx = train_step_idx * self.num_dspy_examples_per_grpo_step+ if self.epoch == -1:+ curr_epoch = 0+ else:+ curr_epoch = base_idx // len(self.shuffled_trainset_ids)+ if curr_epoch > self.epoch:+ logger.info(f"Updating shuffled trainset for epoch {curr_epoch}...")+ self.epoch = curr_epoch+ self.update_shuffled_trainset(original_trainset)++ assert len(self.shuffled_trainset_ids) >= self.num_dspy_examples_per_grpo_step, f"Shuffled trainset length {len(self.shuffled_trainset_ids)} is less than num_dspy_examples_per_grpo_step {self.num_dspy_examples_per_grpo_step}"+ assert len(self.shuffled_trainset_ids) % self.num_dspy_examples_per_grpo_step == 0, f"Shuffled trainset length {len(self.shuffled_trainset_ids)} is not divisible by num_dspy_examples_per_grpo_step {self.num_dspy_examples_per_grpo_step}"++ base_idx = base_idx % len(self.shuffled_trainset_ids)+ end_idx = base_idx + self.num_dspy_examples_per_grpo_step+ assert end_idx <= len(self.shuffled_trainset_ids), f"End index {end_idx} is out of bounds for shuffled trainset length {len(self.shuffled_trainset_ids)}"+ selected_ids = self.shuffled_trainset_ids[base_idx:end_idx]+ selected_trainset = [original_trainset[i] for i in selected_ids]+ return selected_trainset++ def compile(+ self,+ student: Program,+ trainset: List[Example],+ teacher: Optional[Union[Program, List[Program]]] = None,+ valset: Optional[List[Example]] = None,+ **kwargs,+ ) -> Program:+ logger.info("Starting the GRPO compilation process... The LM(s) for the student program will be updated in place at the end of the training.")+ logger.info("Validating the inputs...")++ assert len(trainset) > 0, "Training set is empty. Please provide a non-empty training set."++ if len(trainset) < self.num_dspy_examples_per_grpo_step:+ logger.warning(+ f"Number of training examples {len(trainset)} is less than the number of examples per GRPO step {self.num_dspy_examples_per_grpo_step}. "+ "Repeating the training set to fill the GRPO step. This could lead to overfitting and training instability."+ )+ multiplier = (self.num_dspy_examples_per_grpo_step + len(trainset) - 1) // len(trainset)+ if multiplier > 1:+ logger.warning(+ f"Repeating the training set {multiplier} times to fill the GRPO step. This could lead to overfitting and training instability."+ )+ trainset = trainset * multiplier++ # TODO(GRPO Team): Following checks are for unimplemented features.+ # Consider if we want to eventually implement them or remove. We don't+ # yet support:+ # * multitask == False+ # * student program with multiple predictor LMs+ # The main reason for these is that we update the LMs in place. If these+ # LMs are shared between the different predictors of the student+ # program and we have multitask == False, we need to decide which steps+ # will use new LM copies and we need to ensure our decision is+ # consistent with any teacher LMs that share the same LMs.+ # TODO(GRPO Team): We want to make it possible to continue GRPO runs in+ # the future by saving the state of the GRPO run in the event of a+ # process failure.+ if not self.multitask:+ raise ValueError(+ "Independent GRPO training jobs for each predictor in the student program "+ "are not supported yet. Please set multitask=True."+ )++ student_lms = {id(pred.lm) for pred in student.predictors()}+ assert len(student_lms) == 1, (+ f"Student program has multiple LMs: {student_lms}. "+ "GRPO only supports student programs with a single LM."+ "You can set the LM for a program with `program.set_lm(...)`"+ )++ # Our regular input validation starts here+ if self.use_train_as_val:+ assert valset is None, "If use_train_as_val is True, valset must be None."++ logger.info("Preparing the student program...")+ all_predictors_have_lms(student)+ pred_signature_hash_to_ind = {hash(pred.signature): ind for ind, pred in enumerate(student.predictors())}+ num_student_predictors = len(student.predictors())++ logging.info("Preparing the teacher program(s)... We will ensure that the provided programs have the same program structure as the student program.")+ if isinstance(teacher, list) and len(teacher) == 0 or teacher is None:+ teacher = student+ teachers = teacher if isinstance(teacher, list) else [teacher]+ for t in teachers:+ assert_structural_equivalency(student, t)+ all_predictors_have_lms(t)++ # Ensure that the teachers list contain the student program+ assert student in teachers, f"Student program {student} is not in the list of teachers {teachers}. Please provide the student program as one of the teachers. Alternatively, you can leave the teacher argument as None, and the student program will be used as the teacher program."+ assert self.num_rollouts_per_grpo_step % len(teachers) == 0, (+ f"The GRPO group size (num_rollouts_per_grpo_step) {self.num_rollouts_per_grpo_step} is not divisible by the number of teachers {len(teachers)}. "+ "This is required to ensure that each teacher gets the same number of examples."+ "Please provide a number of examples that is divisible by the number of teachers."+ )+ num_samples_per_input = self.num_rollouts_per_grpo_step // len(teachers)++ # We will disable the LM cache for all programs (student and teachers)+ # These will be reverted to their original state at the end of the+ # training+ lm_cache_dict = {}+ disable_lm_cache(program=student, lm_cache_dict=lm_cache_dict)+ for t in teachers:+ disable_lm_cache(program=t, lm_cache_dict=lm_cache_dict)++ # Update train_kwargs+ for pred in student.predictors():+ train_kwargs = self.train_kwargs[pred.lm]+ train_kwargs = {} if train_kwargs is None else train_kwargs+ train_kwargs["num_generations"] = self.num_rollouts_per_grpo_step+ self.train_kwargs[pred.lm] = train_kwargs++ # We need to have a separate job for each unique LM x the data+ # collection strategy. This properly handles all combinations of+ # multitask and predictor LMs+ logger.info("Preparing the GRPO training job(s)...")+ grpo_training_jobs = {}+ for pred_ind, pred in enumerate(student.predictors()):+ data_key = None if self.multitask else pred_ind+ 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)+ grpo_training_jobs[job_key] = job++ self.report_validation_metrics(+ student=student,+ trainset=trainset,+ valset=valset,+ logger=logger,+ step_idx=-1,+ )++ 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}...")++ subsample_training_dataset = self.select_training_sample_and_update_shuffled_trainset(+ original_trainset=trainset,+ train_step_idx=train_step_idx,+ )++ logger.info("Bootstrapping data...")+ trace_data = [[[] for _ in range(len(teachers))] for _ in range(len(subsample_training_dataset))]+ for tind, teacher in enumerate(teachers):+ subsample_training_dataset_repeated = [example for _ in range(num_samples_per_input) for example in subsample_training_dataset]+ round_data = bootstrap_trace_data(+ program=teacher,+ dataset=subsample_training_dataset_repeated,+ metric=self.metric,+ num_threads=self.num_threads,+ raise_on_error=False, # TODO(GRPO Team): This should be True, once the dspy format issue is fixed+ capture_failed_parses=True,+ failure_score=self.failure_score,+ format_failure_score=self.format_failure_score,+ )+ for data_dict in round_data:+ example_ind_in_subsample = data_dict['example_ind'] % len(subsample_training_dataset)+ data_dict["example_ind"] = example_ind_in_subsample+ trace_data[example_ind_in_subsample][tind].append(data_dict)++ # The trace_data for examples with FailedPrediction cases will have the signature at index 0, instead of the predictor+ # We need to replace the signature with the predictor++ # At this point, trace_data: List[example_idx -> List[teacher_idx -> [num_samples_per_input * Dict(example, prediction, trace, example_ind, score)]]]+ # Shape of trace is: [dspy_module_invocation_idx -> Tuple[Predictor, PredictorInputs, Prediction]]+ self.validate_trace_data_and_log_issues(+ trace_data=trace_data,+ subsample_training_dataset=subsample_training_dataset,+ num_teachers=len(teachers),+ num_samples_per_input=num_samples_per_input,+ pred_signature_hash_to_ind=pred_signature_hash_to_ind,+ )++ logger.info("Preparing the training data batch from bootstrapped examples for GRPO...")+ # Now, we need to prepare batches of data to be sent for training+ # Shape of train_batch_per_predictor: List[num_student_predictors -> List[ ]]+ train_batch_per_predictor: List[List[GRPOGroup]] = [[] for _ in range(num_student_predictors)]+ for pred_id in range(num_student_predictors):+ for example_ind, example_data in enumerate(trace_data):+ # Each example_data is a list of teacher_idx -> [num_samples_per_input * Dict(example, prediction, trace, example_ind, score)]+ # We need to flatten this list and create a batch for each predictor++ # TODO(Lakshya, Omar, Noah): Discuss what to do with the same module being invoked multiple times within a single dspy.Example+ predictor_example_invocations: List[List[Tuple]] = []++ for teacher_data in example_data:+ for sample in teacher_data:+ # Each sample is a Dict(example, prediction, trace, example_ind, score)+ # sample['prediction'] is module_level prediction+ assert sample["example_ind"] == example_ind, f"Example index {sample['example_ind']} does not match the expected index {example_ind}"++ trace_instances_for_current_pred = [(*t, sample["score"]) for t in sample["trace"] if hash(t[0].signature) == hash(student.predictors()[pred_id].signature)]++ predictor_example_invocations.append(trace_instances_for_current_pred)++ if len(predictor_example_invocations) == 0:+ logger.warning(f"Skipping example {example_ind} for predictor {pred_id} as it has no invocations. This is likely due to all examples in the training set input, resulting in the model generating output not following the dspy response format.")+ continue+ elif len(predictor_example_invocations) != self.num_rollouts_per_grpo_step:+ logger.warning(f"Number of predictor example invocations {len(predictor_example_invocations)} does not match the expected batch size {self.num_rollouts_per_grpo_step}. This is likely due to all examples in the training set input, resulting in the model generating output not following the dspy response format.")++ min_len = min([len(predictor_example_invocations[i]) for i in range(len(predictor_example_invocations))])+ max_len = max([len(predictor_example_invocations[i]) for i in range(len(predictor_example_invocations))])+ if min_len == 0:+ logger.warning(f"Skipping example {example_ind} for predictor {pred_id} as it has no invocations.")+ continue++ if self.variably_invoked_predictor_grouping_mode == 'truncate':+ predictor_example_invocations = [invocation[:min_len] for invocation in predictor_example_invocations]+ elif self.variably_invoked_predictor_grouping_mode == 'fill':+ if self.variably_invoked_predictor_fill_strategy == 'randint':+ selector = lambda l: self.rng.choice(l)+ else:+ selector = lambda l: l[-1]+ predictor_example_invocations = [+ invocation + [selector(invocation) for _ in range(max_len - len(invocation))]+ for invocation in predictor_example_invocations+ ]+ else:+ assert self.variably_invoked_predictor_grouping_mode == 'ragged', f"Unknown variably invoked predictor grouping mode {self.variably_invoked_predictor_grouping_mode}"+ max_len = max([len(predictor_example_invocations[i]) for i in range(len(predictor_example_invocations))])++ example_training_data: List[GRPOGroup] = [[] for _ in range(max_len)]++ for group_idx in range(max_len):+ for rollout_idx in range(len(predictor_example_invocations)):+ trace_instance = predictor_example_invocations[rollout_idx][group_idx]+ score = trace_instance[3]+ # for module_invocation_idx, trace_instance in enumerate(trace_instances_for_current_pred):+ # Each trace is a tuple of (Predictor, PredictorInputs, Prediction)+ trace_pred_id = pred_signature_hash_to_ind.get(hash(trace_instance[0].signature))+ assert trace_pred_id == pred_id++ predictor = trace_instance[0]+ pred_lm = predictor.lm+ adapter = self.adapter[pred_lm] or settings.adapter or ChatAdapter()+ 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+ # dealing with the message formatting ourselves.+ inp_messages = adapter.format(+ signature=trace_instance[0].signature,+ inputs=trace_instance[1],+ demos=[] # TODO: Add support for demos+ )++ if isinstance(trace_instance[2], FailedPrediction):+ score = trace_instance[2].format_reward or self.format_failure_score+ example_training_data[group_idx].append({+ "messages": inp_messages,+ "completion": {+ "role": "assistant",+ "content": trace_instance[2].completion_text,+ },+ "reward": float(score),+ })+ logger.warning(f"Adding a format failure example to the training data for predictor {pred_id} and example {example_ind}.")+ else:+ all_messages = adapter.format_finetune_data(+ signature=trace_instance[0].signature,+ inputs=trace_instance[1],+ outputs=trace_instance[2],+ demos=[] # TODO: Add support for demos+ )['messages']++ assert all_messages[:-1] == inp_messages, f"Input messages {inp_messages} do not match the expected messages {all_messages[:-1]}"++ example_training_data[group_idx].append({+ "messages": inp_messages,+ "completion": {+ "role": all_messages[-1]["role"],+ "content": all_messages[-1]["content"],+ },+ "reward": float(score),+ })++ train_batch_per_predictor[pred_id].extend(example_training_data)++ if len(sum(train_batch_per_predictor, [])) == 0:+ logger.warning("No training data found for this training step. This means that the model did not generate valid formatted responses for any of the examples in the training set. This is a critical error. Please check the model and the training set.")+ continue++ for predictor_train_batch in train_batch_per_predictor:+ for grpo_train_group in predictor_train_batch:+ if len(grpo_train_group) != self.num_rollouts_per_grpo_step:+ logger.warning(f"Number of completions {len(grpo_train_group)} does not match the expected number num_rollouts_per_grpo_step={self.num_rollouts_per_grpo_step}")+ assert len(grpo_train_group) <= self.num_rollouts_per_grpo_step, f"Number of completions {len(grpo_train_group)} is greater than the expected number num_rollouts_per_grpo_step={self.num_rollouts_per_grpo_step}"+ if len(set(map(repr, grpo_train_group))) < 2:+ # TODO(GRPO Team): How can we avoid this warning?+ logger.warning(f"GRPOGroup has no diversity. This could be due to low temperature, or low number of rollouts, or the cache could be enabled inadvertently. The GRPOGroup is {grpo_train_group}.")++ # We now run the GRPO step. Notes:+ # * The job here has a reference to a particular M that's attached+ # to the student program. We update the .model field of this LM+ # inside the job, which also updates the LM in the student program+ # since these point to the same reference (along with any teacher+ # program that shares the same LM).+ # * TODO(GRPO Team): This is inconsistent with how+ # BootstrapFinetune works, which creates new LM instances post+ # training. We should decide whether the LMs should be updated in+ # place or new LMs should be created, and standardize our approach+ # for both. If we decide to create new LMs, we should find a way+ # to update self.adapter and self.train_kwargs accordingly, in+ # addition to updating any teacher programs that share the same+ # LM.+ logger.info("Invoking GRPO training step...")+ for (lm, 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]+ 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.++ # 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)++ for (lm, data_key), job in grpo_training_jobs.items():+ if (train_step_idx + 1) % self.train_kwargs[lm]["update_interval"] == 0 and train_step_idx != 0:+ logger.info(f"Current train step is {train_step_idx + 1}. Updating the model...")+ job.update_model()++ logger.info(f"GRPO training step {train_step_idx + 1}/{self.num_train_steps} completed.")++ self.report_validation_metrics(+ student=student,+ trainset=trainset,+ valset=valset,+ logger=logger,+ step_idx=train_step_idx,+ )++ logger.info("Done with the iterations! Retrieving the final model(s)...")+ for (lm, data_key), job in grpo_training_jobs.items():+ job.terminate()++ # Revert cache states to their initial values+ recover_lm_cache(program=student, lm_cache_dict=lm_cache_dict)+ for t in teachers:+ recover_lm_cache(program=t, lm_cache_dict=lm_cache_dict)++ logger.info("GRPO compiler has finished compiling the student program")+ student._compiled = True+ return student+++def disable_lm_cache(program: Program, lm_cache_dict: dict):+ """Disable the LM cache for all predictors in the program."""+ for pred in program.predictors():+ if not pred.lm:+ raise ValueError(f"Cannot disable cache: predictor {pred} does not have an LM set.")+ if pred.lm not in lm_cache_dict: # Check to avoid overwriting the cache+ lm_cache_dict[pred.lm] = pred.lm.cache+ pred.lm.cache = False+++def recover_lm_cache(program: Program, lm_cache_dict: dict):+ """Recover the LM caches for all predictors in the program to their original state."""+ for pred in program.predictors():+ if pred.lm in lm_cache_dict:+ pred.lm.cache = lm_cache_dict[pred.lm]+ else:+ # We do not expect this branch to execute at all since all the LMs+ # are modified in place and no new LMs are created during training.+ # However, we do not complain if this happens since this is a+ # relatively minor feature. We default the LM cache to True.+ pred.lm.cache = Truediff --git a/tests/teleprompt/test_grpo.py b/tests/teleprompt/test_grpo.pynew file mode 100644index 000000000..9de74f7c5--- /dev/null+++ b/tests/teleprompt/test_grpo.py@@ -0,0 +1,62 @@+from dspy.teleprompt.grpo import GRPO++def test_grpo_dataset_shuffler():+ dataset = [1,2,3]+ grpo = GRPO(+ num_dspy_examples_per_grpo_step=3,+ exclude_demos=True,+ )++ trainset_instances = []+ for i in range(4):+ trainset_instances.append(grpo.select_training_sample_and_update_shuffled_trainset(dataset, i))+ assert len(trainset_instances[-1]) == 3+ assert set(trainset_instances[-1]) == set(dataset)++def test_grpo_dataset_shuffler_with_num_ex_per_step_less_dataset():+ dataset = [1,2,3]+ grpo = GRPO(+ num_dspy_examples_per_grpo_step=2,+ exclude_demos=True,+ )++ trainset_instances = []+ for i in range(15):+ trainset_instances.append(grpo.select_training_sample_and_update_shuffled_trainset(dataset, i))+ assert len(trainset_instances[-1]) == 2++ from collections import Counter+ counter = Counter()+ for instance in trainset_instances:+ counter.update(instance)++ assert len(counter) == 3+ for i in counter:+ assert counter[i] == 10++def test_grpo_dataset_shuffler_with_num_ex_per_step_greater_dataset():+ dataset = [1,2,3]+ grpo = GRPO(+ num_dspy_examples_per_grpo_step=5,+ exclude_demos=True,+ )++ trainset_instances = []+ for i in range(6):+ trainset_instances.append(grpo.select_training_sample_and_update_shuffled_trainset(dataset, i))+ assert len(trainset_instances[-1]) == 5++ from collections import Counter+ counter = Counter()+ for instance in trainset_instances:+ counter.update(instance)++ assert len(counter) == 3+ for i in counter:+ assert counter[i] == 10++if __name__ == "__main__":+ test_grpo_dataset_shuffler()+ test_grpo_dataset_shuffler_with_num_ex_per_step_less_dataset()+ test_grpo_dataset_shuffler_with_num_ex_per_step_greater_dataset()+ print("All tests passed!")\ No newline at end of file