Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 20 additions & 19 deletions docs/docs/tutorials/rl_multihop/index.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -226,29 +226,30 @@
"metadata": {},
"outputs": [],
"source": [
"from dspy.teleprompt.grpo import GRPO\n",
"from dspy.teleprompt.grpo import GRPO, GRPOConfig\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",
"\n",
"# NOTE: Training on 6 GPUs.\n",
"train_kwargs = {\n",
" \"per_device_train_batch_size\": 2,\n",
" \"gradient_accumulation_steps\": 8,\n",
" \"temperature\": 1.0,\n",
" \"beta\": 0.04,\n",
" \"learning_rate\": 1e-5,\n",
" \"gradient_checkpointing\": True,\n",
" \"gradient_checkpointing_kwargs\": {\"use_reentrant\": False},\n",
" \"bf16\": True,\n",
" \"lr_scheduler_type\": \"constant_with_warmup\",\n",
" \"max_prompt_length\": None,\n",
" \"max_completion_length\": None,\n",
" \"scale_rewards\": True,\n",
" \"max_grad_norm\": 0.5,\n",
" \"lora\": True,\n",
"}\n",
"config = GRPOConfig(\n",
" num_generations=4,\n",
" temperature=1.0,\n",
" beta=0.04,\n",
" per_device_train_batch_size=2,\n",
" learning_rate=1e-5,\n",
" gradient_accumulation_steps=8,\n",
" gradient_checkpointing=True,\n",
" gradient_checkpointing_kwargs={\"use_reentrant\": False},\n",
" bf16=True,\n",
" lr_scheduler_type=\"constant_with_warmup\",\n",
" max_prompt_length=None,\n",
" max_completion_length=None,\n",
" scale_rewards=True,\n",
" max_grad_norm=0.5,\n",
" lora=True,\n",
")\n",
"\n",
"compiler = GRPO(\n",
" metric=recall,\n",
Expand All @@ -259,7 +260,7 @@
" num_threads=16,\n",
" use_train_as_val=False,\n",
" num_steps_for_val=10,\n",
" train_kwargs=train_kwargs,\n",
" config=config,#now using GRPOConfig directly\n",
" report_train_scores=False,\n",
" gpu_config=MultiGPUConfig(num_inference_gpus=1, num_training_gpus=1),\n",
")\n",
Expand All @@ -268,7 +269,7 @@
" student=program,\n",
" trainset=trainset,\n",
" valset=devset,\n",
")\n"
")"
]
},
{
Expand Down
41 changes: 21 additions & 20 deletions docs/docs/tutorials/rl_papillon/index.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -255,41 +255,42 @@
"metadata": {},
"outputs": [],
"source": [
"from dspy.teleprompt.grpo import GRPO\n",
"from dspy.teleprompt.grpo import GRPO, GRPOConfig\n",
"from dspy.clients.utils_finetune import MultiGPUConfig\n",
"\n",
"papillon = PAPILLON(untrusted_model=openai_lm)\n",
"papillon.set_lm(local_lm)\n",
"\n",
"# NOTE: Training on 3 GPUs.\n",
"train_kwargs = {\n",
" \"per_device_train_batch_size\": 8,\n",
" \"gradient_accumulation_steps\": 4,\n",
" \"temperature\": 1.0,\n",
" \"beta\": 0.04,\n",
" \"learning_rate\": 2e-6,\n",
" \"gradient_checkpointing\": True,\n",
" \"gradient_checkpointing_kwargs\": {\"use_reentrant\": False},\n",
" \"bf16\": True,\n",
" \"lr_scheduler_type\": \"constant_with_warmup\",\n",
" \"max_prompt_length\": None,\n",
" \"max_completion_length\": None,\n",
" \"scale_rewards\": True,\n",
" \"max_grad_norm\": 0.5,\n",
" \"lora\": True,\n",
"}\n",
"config = GRPOConfig(\n",
" num_generations=8,\n",
" temperature=1.0,\n",
" beta=0.04,\n",
" per_device_train_batch_size=8,\n",
" learning_rate=2e-6,\n",
" gradient_accumulation_steps=4,\n",
" gradient_checkpointing=True,\n",
" gradient_checkpointing_kwargs={\"use_reentrant\": False},\n",
" bf16=True,\n",
" lr_scheduler_type=\"constant_with_warmup\",\n",
" max_prompt_length=None,\n",
" max_completion_length=None,\n",
" scale_rewards=True,\n",
" max_grad_norm=0.5,\n",
" lora=True,\n",
")\n",
"\n",
"compiler = GRPO(\n",
" metric=compute_overall_score,\n",
" multitask=True,\n",
" num_dspy_examples_per_grpo_step=4,\n",
" num_samples_per_input=8,\n",
" num_rollouts_per_grpo_step=8,#changed from num_generations since that parameter doesn't exist anymore\n",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch!

" exclude_demos=True,\n",
" num_train_steps=500,\n",
" num_threads=24,\n",
" use_train_as_val=False,\n",
" num_steps_for_val=10,\n",
" train_kwargs=train_kwargs,\n",
" config=config,#now using GRPOConfig directly\n",
" report_train_scores=False,\n",
" gpu_config=MultiGPUConfig(num_inference_gpus=2, num_training_gpus=2),\n",
")\n",
Expand All @@ -298,7 +299,7 @@
" student=papillon,\n",
" trainset=trainset,\n",
" valset=devset,\n",
")\n"
")"
]
},
{
Expand Down
6 changes: 2 additions & 4 deletions dspy/clients/lm.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,16 +227,14 @@ def thread_function_wrapper():

return job

def reinforce(
self, train_kwargs, gpu_config: MultiGPUConfig = MultiGPUConfig(num_inference_gpus=1, num_training_gpus=1)
) -> ReinforceJob:
def reinforce(self, config, gpu_config: MultiGPUConfig = MultiGPUConfig(num_inference_gpus=1, num_training_gpus=1)) -> 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, gpu_config=gpu_config)
job = self.provider.ReinforceJob(lm=self, config=config, gpu_config=gpu_config)
job.initialize()
return job

Expand Down
104 changes: 13 additions & 91 deletions dspy/clients/lm_local_arbor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
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
Expand All @@ -9,15 +9,12 @@
import dspy
from dspy.clients.provider import Provider, ReinforceJob, TrainingJob
from dspy.clients.utils_finetune import GRPOGroup, MultiGPUConfig, TrainDataFormat, TrainingStatus, save_data
from dspy.teleprompt.grpo.grpo_config import GRPOConfig

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)
Expand Down Expand Up @@ -47,107 +44,32 @@ def status(self) -> TrainingStatus:


class ArborReinforceJob(ReinforceJob):
DEFAULT_TRAIN_KWARGS = { # noqa: RUF012
"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, gpu_config: MultiGPUConfig = MultiGPUConfig(num_inference_gpus=1, num_training_gpus=1)):
def __init__(self, lm: "LM", config: GRPOConfig, gpu_config: MultiGPUConfig = MultiGPUConfig(num_inference_gpus=1, num_training_gpus=1)):
# 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")
if not isinstance(config, GRPOConfig):
raise TypeError(f"Expected config to be of type GRPOConfig, but got {type(config)}")

self.lm = lm
self.train_kwargs = train_kwargs
self.config: GRPOConfig = config
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
num_generations = self.train_kwargs.get("num_generations")
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"]

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,
"gpu_config": {
"type": gpu_config_type,
gpu_config_type: self.gpu_config,
},

# Create data payload from GRPOConfig
data = self.config.to_dict()
data["model"] = finetune_model
data["gpu_config"] = {
"type": gpu_config_type,
gpu_config_type: self.gpu_config,
}
url = urljoin(api_base, "fine_tuning/grpo/initialize")
headers = {"Content-Type": "application/json"}
Expand Down
4 changes: 2 additions & 2 deletions dspy/clients/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ def status(self):


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", config: dict[str, Any] | None = None, gpu_config: MultiGPUConfig = MultiGPUConfig(num_inference_gpus=1, num_training_gpus=1)):
self.lm = lm
self.train_kwargs = train_kwargs or {}
self.config = config or {}
self.gpu_config = gpu_config
self.checkpoints = {}
self.last_checkpoint = None
Expand Down
4 changes: 4 additions & 0 deletions dspy/teleprompt/grpo/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from dspy.teleprompt.grpo.grpo import GRPO
from dspy.teleprompt.grpo.grpo_config import GRPOConfig

__all__ = ["GRPO", "GRPOConfig"]
Loading
Loading