Spaces:
Sleeping
Sleeping
File size: 7,588 Bytes
dbb1ce2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Flatmate RL GRPO Step-2 Curriculum\n",
"\n",
"This notebook is a minimal GRPO starter for `flatmate_rl`.\n",
"It only trains the first two workflow steps:\n",
"\n",
"1. ask for the missing buyer details\n",
"2. store the buyer profile\n",
"\n",
"The goal is to keep the reward simple enough to bootstrap the broker policy before training on later booking steps."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install -q trl transformers accelerate datasets peft bitsandbytes sentencepiece\n",
"\n",
"from __future__ import annotations\n",
"\n",
"import json\n",
"import sys\n",
"from pathlib import Path\n",
"\n",
"repo_root = Path.cwd().resolve().parent\n",
"if str(repo_root) not in sys.path:\n",
" sys.path.insert(0, str(repo_root))\n",
"\n",
"from datasets import Dataset\n",
"from flatmate_rl import FlatmateRlAction\n",
"from flatmate_rl.server.flatmate_rl_environment import FlatmateRlEnvironment\n",
"from flatmate_rl.server.heuristic_policy import expected_policy_action\n",
"\n",
"print('imports ready')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"TARGET_SCENARIOS = [\n",
" 'task_visit_single',\n",
" 'task_visit_single_hidden_flex',\n",
" 'task_visit_multi',\n",
" 'task_visit_single_seller_followup',\n",
"]\n",
"\n",
"def format_prompt(obs, step: int) -> str:\n",
" visible_state = {\n",
" 'step': step,\n",
" 'phase': obs.phase,\n",
" 'status': obs.status,\n",
" 'remaining_required_fields': obs.remaining_required_fields,\n",
" 'available_tools': obs.available_tools,\n",
" 'feedback_summary': obs.feedback_summary,\n",
" 'message': obs.message,\n",
" 'last_tool_result': obs.last_tool_result,\n",
" 'buyer_history': obs.buyer_conversation_history[-4:],\n",
" 'seller_history': obs.seller_conversation_history[-4:],\n",
" }\n",
"\n",
" return (\n",
" 'Return exactly one JSON object.\\\\n'\n",
" 'Schema: {\"action_type\":\"assistant_message\",\"assistant_message\":\"...\"} or '\n",
" '{\"action_type\":\"tool_call\",\"tool_name\":\"...\",\"tool_arguments\":{...}}\\\\n\\\\n'\n",
" f'Observation:\\n{json.dumps(visible_state, ensure_ascii=False, indent=2)}\\n'\n",
" 'Return JSON only.'\n",
" )\n",
"\n",
"rows = []\n",
"for scenario_id in TARGET_SCENARIOS:\n",
" env = FlatmateRlEnvironment()\n",
" obs = env.reset(scenario_id=scenario_id)\n",
" for step in (1, 2):\n",
" payload = expected_policy_action(scenario_id, obs.model_dump())\n",
" if payload is None:\n",
" break\n",
" rows.append(\n",
" {\n",
" 'scenario_id': scenario_id,\n",
" 'step': step,\n",
" 'prompt': format_prompt(obs, step),\n",
" 'expected_action': payload,\n",
" }\n",
" )\n",
" obs = env.step(FlatmateRlAction.model_validate(payload))\n",
"\n",
"train_ds = Dataset.from_list(rows)\n",
"train_ds[:2]\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def score_completion(example, completion_text: str) -> float:\n",
" try:\n",
" action = json.loads(completion_text)\n",
" except json.JSONDecodeError:\n",
" return -0.25\n",
"\n",
" step = int(example['step'])\n",
" expected = example['expected_action']\n",
"\n",
" if step == 1:\n",
" message = str(action.get('assistant_message', '')).lower()\n",
" if action.get('action_type') == 'assistant_message' and 'diet' in message and 'availability' in message:\n",
" return 1.0\n",
" return -0.1\n",
"\n",
" if step == 2:\n",
" if action.get('action_type') == 'tool_call' and action.get('tool_name') == expected.get('tool_name'):\n",
" return 1.0\n",
" return -0.2\n",
"\n",
" return 0.0\n",
"\n",
"for row in rows[:2]:\n",
" print(row['scenario_id'], row['step'], score_completion(row, json.dumps(row['expected_action'])))\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoModelForCausalLM, AutoTokenizer\n",
"\n",
"model_name = 'Qwen/Qwen2.5-0.5B-Instruct'\n",
"tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
"model = AutoModelForCausalLM.from_pretrained(model_name, device_map='auto')\n",
"\n",
"from peft import LoraConfig\n",
"from trl import GRPOConfig, GRPOTrainer\n",
"\n",
"grpo_args = GRPOConfig(\n",
" output_dir='flatmate_grpo_step2',\n",
" learning_rate=1e-5,\n",
" per_device_train_batch_size=1,\n",
" gradient_accumulation_steps=4,\n",
" max_prompt_length=1024,\n",
" max_completion_length=256,\n",
" num_generations=4,\n",
" logging_steps=1,\n",
" save_steps=25,\n",
")\n",
"\n",
"lora_config = LoraConfig(\n",
" r=8,\n",
" lora_alpha=16,\n",
" lora_dropout=0.05,\n",
" bias='none',\n",
" task_type='CAUSAL_LM',\n",
")\n",
"\n",
"def reward_func(prompts, completions, **kwargs):\n",
" rewards = []\n",
" examples = kwargs['examples']\n",
" for example, completion in zip(examples, completions):\n",
" rewards.append(score_completion(example, completion))\n",
" return rewards\n",
"\n",
"# Starter training block.\n",
"# If your installed TRL version expects a slightly different GRPOTrainer signature,\n",
"# keep the dataset, reward, and LoRA config from above and adapt only the constructor call.\n",
"trainer = GRPOTrainer(\n",
" model=model,\n",
" tokenizer=tokenizer,\n",
" args=grpo_args,\n",
" train_dataset=train_ds,\n",
" reward_funcs=[reward_func],\n",
" peft_config=lora_config,\n",
")\n",
"\n",
"# trainer.train()\n",
"print('GRPO trainer configured for the step-1/step-2 curriculum')\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|