Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- .pytest_cache/.gitignore +2 -0
- .pytest_cache/CACHEDIR.TAG +4 -0
- .pytest_cache/README.md +8 -0
- .pytest_cache/v/cache/nodeids +35 -0
- server/episode.py +6 -3
- server/flatmate_rl_environment.py +1 -2
- server/scenario_variants.py +133 -0
- tests/test_flatmate_rl.py +19 -0
- train_flatmate_rl_grpo.ipynb +838 -0
- train_flatmate_rl_trl.ipynb +777 -0
.pytest_cache/.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Created by pytest automatically.
|
| 2 |
+
*
|
.pytest_cache/CACHEDIR.TAG
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Signature: 8a477f597d28d172789f06886806bc55
|
| 2 |
+
# This file is a cache directory tag created by pytest.
|
| 3 |
+
# For information about cache directory tags, see:
|
| 4 |
+
# https://bford.info/cachedir/spec.html
|
.pytest_cache/README.md
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pytest cache directory #
|
| 2 |
+
|
| 3 |
+
This directory contains data from the pytest's cache plugin,
|
| 4 |
+
which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
|
| 5 |
+
|
| 6 |
+
**Do not** commit this to version control.
|
| 7 |
+
|
| 8 |
+
See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.
|
.pytest_cache/v/cache/nodeids
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
"tests/test_flatmate_rl.py::test_buyer_answers_diet_and_availability_when_broker_asks_for_both",
|
| 3 |
+
"tests/test_flatmate_rl.py::test_conflict_check_calendar_slots_exposes_pre_booked_and_available",
|
| 4 |
+
"tests/test_flatmate_rl.py::test_conflict_check_cannot_book_pre_booked_slot",
|
| 5 |
+
"tests/test_flatmate_rl.py::test_conflict_check_heuristic_books_only_available_slot",
|
| 6 |
+
"tests/test_flatmate_rl.py::test_heuristic_policy_progresses_after_confirmation_in_single_visit",
|
| 7 |
+
"tests/test_flatmate_rl.py::test_heuristic_policy_recovers_from_strict_eval_feedback",
|
| 8 |
+
"tests/test_flatmate_rl.py::test_hidden_flex_requires_alternative_slot_to_unlock_backup_availability",
|
| 9 |
+
"tests/test_flatmate_rl.py::test_legal_non_canonical_tool_after_store_can_continue",
|
| 10 |
+
"tests/test_flatmate_rl.py::test_multi_visit_scenario_books_two_visits",
|
| 11 |
+
"tests/test_flatmate_rl.py::test_negotiation_heuristic_confirms_deal_with_agreed_rent",
|
| 12 |
+
"tests/test_flatmate_rl.py::test_observation_surfaces_prerequisites_and_recent_tool_calls",
|
| 13 |
+
"tests/test_flatmate_rl.py::test_redundant_successful_tool_call_gets_small_penalty_without_termination",
|
| 14 |
+
"tests/test_flatmate_rl.py::test_reset_exposes_initial_buyer_message",
|
| 15 |
+
"tests/test_flatmate_rl.py::test_scenarios_are_self_consistent",
|
| 16 |
+
"tests/test_flatmate_rl.py::test_schema_valid_non_canonical_action_never_uses_legacy_flow_failure",
|
| 17 |
+
"tests/test_flatmate_rl.py::test_search_before_store_user_details_fails",
|
| 18 |
+
"tests/test_flatmate_rl.py::test_seeded_reset_varies_values_without_changing_episode_flow",
|
| 19 |
+
"tests/test_flatmate_rl.py::test_seller_followup_accepts_expected_tool_with_different_arguments",
|
| 20 |
+
"tests/test_flatmate_rl.py::test_seller_followup_accepts_paraphrased_assistant_message",
|
| 21 |
+
"tests/test_flatmate_rl.py::test_seller_followup_match_tools_infer_dynamic_post_when_args_are_loose",
|
| 22 |
+
"tests/test_flatmate_rl.py::test_seller_followup_non_canonical_tool_order_gets_small_penalty_without_termination",
|
| 23 |
+
"tests/test_flatmate_rl.py::test_seller_followup_scenario_schedules_dynamic_visit",
|
| 24 |
+
"tests/test_flatmate_rl.py::test_seller_followup_search_returns_no_visit_compatible_current_posts",
|
| 25 |
+
"tests/test_flatmate_rl.py::test_single_visit_scenario_books_one_visit",
|
| 26 |
+
"tests/test_flatmate_rl.py::test_store_user_details_does_not_return_expected_answers_payload",
|
| 27 |
+
"tests/test_flatmate_rl.py::test_strict_eval_mode_hides_scenario_metadata_and_reward",
|
| 28 |
+
"tests/test_inference_parsing.py::test_legacy_parse_can_coerce_tool_name_in_action_type",
|
| 29 |
+
"tests/test_inference_parsing.py::test_malformed_action_feedback_is_recoverable",
|
| 30 |
+
"tests/test_inference_parsing.py::test_model_call_error_does_not_fallback_to_heuristic",
|
| 31 |
+
"tests/test_inference_parsing.py::test_strict_parse_rejects_tool_name_in_action_type",
|
| 32 |
+
"tests/test_inference_parsing.py::test_strict_parse_reports_json_error",
|
| 33 |
+
"tests/test_inference_parsing.py::test_user_prompt_renders_prerequisites_and_recent_tools",
|
| 34 |
+
"tests/test_reward_regression.py::test_heuristic_reward_regression"
|
| 35 |
+
]
|
server/episode.py
CHANGED
|
@@ -11,10 +11,12 @@ from typing import Any
|
|
| 11 |
try:
|
| 12 |
from ..models import FlatmateRlAction, FlatmateRlObservation, FlatmateRlState
|
| 13 |
from .heuristic_policy import expected_policy_action
|
|
|
|
| 14 |
from .scenarios import POSTS, SCENARIOS
|
| 15 |
except ImportError:
|
| 16 |
from models import FlatmateRlAction, FlatmateRlObservation, FlatmateRlState
|
| 17 |
from server.heuristic_policy import expected_policy_action
|
|
|
|
| 18 |
from server.scenarios import POSTS, SCENARIOS
|
| 19 |
|
| 20 |
|
|
@@ -118,10 +120,11 @@ class FlatmateEpisode:
|
|
| 118 |
self._post_arrivals_fired: set[int] = set()
|
| 119 |
self._available_post_ids: list[str] = []
|
| 120 |
|
| 121 |
-
def reset(self, scenario_id: str | None = None) -> FlatmateRlObservation:
|
| 122 |
selected = scenario_id or "task_visit_single"
|
| 123 |
-
|
| 124 |
-
|
|
|
|
| 125 |
self._tool_results = []
|
| 126 |
self._tool_trace = []
|
| 127 |
self._history = []
|
|
|
|
| 11 |
try:
|
| 12 |
from ..models import FlatmateRlAction, FlatmateRlObservation, FlatmateRlState
|
| 13 |
from .heuristic_policy import expected_policy_action
|
| 14 |
+
from .scenario_variants import apply_seed_variant
|
| 15 |
from .scenarios import POSTS, SCENARIOS
|
| 16 |
except ImportError:
|
| 17 |
from models import FlatmateRlAction, FlatmateRlObservation, FlatmateRlState
|
| 18 |
from server.heuristic_policy import expected_policy_action
|
| 19 |
+
from server.scenario_variants import apply_seed_variant
|
| 20 |
from server.scenarios import POSTS, SCENARIOS
|
| 21 |
|
| 22 |
|
|
|
|
| 120 |
self._post_arrivals_fired: set[int] = set()
|
| 121 |
self._available_post_ids: list[str] = []
|
| 122 |
|
| 123 |
+
def reset(self, scenario_id: str | None = None, seed: int | None = None) -> FlatmateRlObservation:
|
| 124 |
selected = scenario_id or "task_visit_single"
|
| 125 |
+
base_scenario = deepcopy(SCENARIOS[selected])
|
| 126 |
+
base_posts = {post_id: deepcopy(POSTS[post_id]) for post_id in base_scenario["task_post_ids"]}
|
| 127 |
+
self._scenario, self._posts = apply_seed_variant(base_scenario, base_posts, seed)
|
| 128 |
self._tool_results = []
|
| 129 |
self._tool_trace = []
|
| 130 |
self._history = []
|
server/flatmate_rl_environment.py
CHANGED
|
@@ -27,9 +27,8 @@ class FlatmateRlEnvironment(Environment):
|
|
| 27 |
self._episode = FlatmateEpisode(strict_eval_mode=strict_eval_mode)
|
| 28 |
|
| 29 |
def reset(self, scenario_id: str | None = None, seed: int | None = None) -> FlatmateRlObservation:
|
| 30 |
-
del seed
|
| 31 |
self._state = FlatmateRlState(episode_id=str(uuid4()), step_count=0)
|
| 32 |
-
observation = self._episode.reset(scenario_id=scenario_id)
|
| 33 |
self._sync_state(observation)
|
| 34 |
return observation
|
| 35 |
|
|
|
|
| 27 |
self._episode = FlatmateEpisode(strict_eval_mode=strict_eval_mode)
|
| 28 |
|
| 29 |
def reset(self, scenario_id: str | None = None, seed: int | None = None) -> FlatmateRlObservation:
|
|
|
|
| 30 |
self._state = FlatmateRlState(episode_id=str(uuid4()), step_count=0)
|
| 31 |
+
observation = self._episode.reset(scenario_id=scenario_id, seed=seed)
|
| 32 |
self._sync_state(observation)
|
| 33 |
return observation
|
| 34 |
|
server/scenario_variants.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Seeded value variants for Flatmate RL scenarios.
|
| 2 |
+
|
| 3 |
+
Variants intentionally preserve episode flow: same task id, post ids, required
|
| 4 |
+
tools, required bookings, feasible slots, and phase transitions. Only safe
|
| 5 |
+
surface values are shifted so train/test episodes can differ without changing
|
| 6 |
+
the canonical solution structure.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import random
|
| 12 |
+
from copy import deepcopy
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
OCCUPATIONS = [
|
| 17 |
+
"software engineer at a startup",
|
| 18 |
+
"backend engineer at a fintech company",
|
| 19 |
+
"data engineer at a healthtech company",
|
| 20 |
+
"platform engineer at a SaaS company",
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
RENT_DELTAS = [-1200, -800, -500, 0, 500, 800, 1200]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _format_rs(amount: int) -> str:
|
| 27 |
+
return f"{amount:,}"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _buyer_message(scenario: dict[str, Any]) -> str:
|
| 31 |
+
buyer = scenario["buyer_profile"]
|
| 32 |
+
areas = " or ".join(buyer["areas"])
|
| 33 |
+
budget = _format_rs(int(buyer["budget_max"]))
|
| 34 |
+
occupation = buyer["occupation"]
|
| 35 |
+
availability = " or ".join(buyer["visit_availability"])
|
| 36 |
+
task_id = scenario["task_id"]
|
| 37 |
+
|
| 38 |
+
if task_id == "task_visit_multi":
|
| 39 |
+
return (
|
| 40 |
+
"Hi, I want to line up visits for at least two good flatmate-share options before deciding. "
|
| 41 |
+
f"My budget is Rs. {budget}, I'm focused on {areas}, and I work in Goregaon East as a {occupation}."
|
| 42 |
+
)
|
| 43 |
+
if task_id == "task_visit_single_seller_followup":
|
| 44 |
+
return (
|
| 45 |
+
f"Hi, I'm looking for a flatmate-share in {areas}. My budget is Rs. {budget}, "
|
| 46 |
+
f"I work in Goregaon East as a {occupation}, and {availability} are the only times I can visit."
|
| 47 |
+
)
|
| 48 |
+
if "visit_availability" in buyer.get("initial_disclosure_fields", []):
|
| 49 |
+
return (
|
| 50 |
+
f"Hi, I'm looking for a flatmate-share around {areas}. My budget is Rs. {budget}, "
|
| 51 |
+
f"I work in Goregaon East as a {occupation}, and {availability} is the slot I can do right now."
|
| 52 |
+
)
|
| 53 |
+
return (
|
| 54 |
+
"Hi, I'm looking for a flatmate-share near Goregaon East. "
|
| 55 |
+
f"My budget is up to Rs. {budget} and I'm mainly considering {areas} "
|
| 56 |
+
f"because I work as a {occupation}."
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _seller_message(scenario: dict[str, Any]) -> str:
|
| 61 |
+
seller = scenario.get("seller_profile")
|
| 62 |
+
if not seller:
|
| 63 |
+
return scenario.get("seller_initial_message", "")
|
| 64 |
+
return (
|
| 65 |
+
f"Hi, I want help listing a new flatmate-share opening in {seller['area']}. "
|
| 66 |
+
f"The rent is around Rs. {_format_rs(int(seller['rent']))} for a {seller['listing_type']}. "
|
| 67 |
+
"I can tell you more about the listing and available visit times."
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _shift_amount(value: Any, delta: int) -> Any:
|
| 72 |
+
if value is None:
|
| 73 |
+
return None
|
| 74 |
+
return max(1, int(value) + delta)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def apply_seed_variant(
|
| 78 |
+
scenario: dict[str, Any],
|
| 79 |
+
posts: dict[str, dict[str, Any]],
|
| 80 |
+
seed: int | None,
|
| 81 |
+
) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
|
| 82 |
+
"""Return seeded copies of a scenario and its posts.
|
| 83 |
+
|
| 84 |
+
The same seed always produces the same value variant for a scenario. A
|
| 85 |
+
missing seed returns the original values, preserving existing tests and
|
| 86 |
+
default behavior.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
variant_scenario = deepcopy(scenario)
|
| 90 |
+
variant_posts = deepcopy(posts)
|
| 91 |
+
if seed is None:
|
| 92 |
+
return variant_scenario, variant_posts
|
| 93 |
+
|
| 94 |
+
rng = random.Random(f"{variant_scenario['task_id']}:{seed}")
|
| 95 |
+
rent_delta = rng.choice(RENT_DELTAS)
|
| 96 |
+
occupation = rng.choice(OCCUPATIONS)
|
| 97 |
+
|
| 98 |
+
buyer = variant_scenario["buyer_profile"]
|
| 99 |
+
buyer["budget_max"] = _shift_amount(buyer["budget_max"], rent_delta)
|
| 100 |
+
if buyer.get("hidden_budget_ceiling") is not None:
|
| 101 |
+
buyer["hidden_budget_ceiling"] = _shift_amount(buyer["hidden_budget_ceiling"], rent_delta)
|
| 102 |
+
buyer["occupation"] = occupation
|
| 103 |
+
|
| 104 |
+
expected_answers = variant_scenario["scenario_creation_config"].get("expected_answers", {})
|
| 105 |
+
if "budget_max" in expected_answers:
|
| 106 |
+
expected_answers["budget_max"] = buyer["budget_max"]
|
| 107 |
+
if "occupation" in expected_answers:
|
| 108 |
+
expected_answers["occupation"] = buyer["occupation"]
|
| 109 |
+
|
| 110 |
+
negotiation_config = variant_scenario["scenario_creation_config"].get("negotiation_config", {})
|
| 111 |
+
for key in ("buyer_ceiling", "seller_floor"):
|
| 112 |
+
if key in negotiation_config:
|
| 113 |
+
negotiation_config[key] = _shift_amount(negotiation_config[key], rent_delta)
|
| 114 |
+
|
| 115 |
+
for post in variant_posts.values():
|
| 116 |
+
post["rent"] = _shift_amount(post["rent"], rent_delta)
|
| 117 |
+
|
| 118 |
+
seller = variant_scenario.get("seller_profile")
|
| 119 |
+
if seller:
|
| 120 |
+
seller["rent"] = _shift_amount(seller["rent"], rent_delta)
|
| 121 |
+
followup = variant_scenario["scenario_creation_config"].get("followup_seller_expected_answers", {})
|
| 122 |
+
if "rent" in followup:
|
| 123 |
+
followup["rent"] = seller["rent"]
|
| 124 |
+
|
| 125 |
+
variant_scenario["initial_user_message"] = _buyer_message(variant_scenario)
|
| 126 |
+
if seller:
|
| 127 |
+
variant_scenario["seller_initial_message"] = _seller_message(variant_scenario)
|
| 128 |
+
variant_scenario["scenario_creation_config"]["variant"] = {
|
| 129 |
+
"seed": seed,
|
| 130 |
+
"rent_delta": rent_delta,
|
| 131 |
+
"occupation": occupation,
|
| 132 |
+
}
|
| 133 |
+
return variant_scenario, variant_posts
|
tests/test_flatmate_rl.py
CHANGED
|
@@ -84,6 +84,25 @@ def test_reset_exposes_initial_buyer_message() -> None:
|
|
| 84 |
assert observation.remaining_required_fields == ["diet", "visit_availability"]
|
| 85 |
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
def test_search_before_store_user_details_fails() -> None:
|
| 88 |
env = FlatmateRlEnvironment()
|
| 89 |
env.reset(scenario_id="task_visit_single")
|
|
|
|
| 84 |
assert observation.remaining_required_fields == ["diet", "visit_availability"]
|
| 85 |
|
| 86 |
|
| 87 |
+
def test_seeded_reset_varies_values_without_changing_episode_flow() -> None:
|
| 88 |
+
default_env = FlatmateRlEnvironment()
|
| 89 |
+
default_obs = default_env.reset(scenario_id="task_visit_single")
|
| 90 |
+
|
| 91 |
+
seeded_env = FlatmateRlEnvironment()
|
| 92 |
+
seeded_obs = seeded_env.reset(scenario_id="task_visit_single", seed=123)
|
| 93 |
+
seeded_episode = seeded_env._episode # type: ignore[attr-defined]
|
| 94 |
+
|
| 95 |
+
assert seeded_obs.scenario_id == default_obs.scenario_id
|
| 96 |
+
assert seeded_obs.remaining_required_fields == default_obs.remaining_required_fields
|
| 97 |
+
assert seeded_episode._scenario["task_post_ids"] == SCENARIOS["task_visit_single"]["task_post_ids"]
|
| 98 |
+
assert seeded_episode._scenario["ground_truth"] == SCENARIOS["task_visit_single"]["ground_truth"]
|
| 99 |
+
assert seeded_episode._scenario["buyer_profile"]["budget_max"] != SCENARIOS["task_visit_single"]["buyer_profile"]["budget_max"]
|
| 100 |
+
assert (
|
| 101 |
+
seeded_episode._scenario["scenario_creation_config"]["expected_answers"]["budget_max"]
|
| 102 |
+
== seeded_episode._scenario["buyer_profile"]["budget_max"]
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
def test_search_before_store_user_details_fails() -> None:
|
| 107 |
env = FlatmateRlEnvironment()
|
| 108 |
env.reset(scenario_id="task_visit_single")
|
train_flatmate_rl_grpo.ipynb
ADDED
|
@@ -0,0 +1,838 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"id": "f1f7a30f",
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"source": [
|
| 8 |
+
"# Train Flatmate RL with TRL GRPO\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"This notebook uses the live Hugging Face Space endpoint as the reward source for GRPO. It first collects prompt states from websocket rollouts, then trains a model to generate one JSON action for each observation. The main reward function resets the endpoint, replays the stored action prefix, applies the model action, and scores the resulting Flatmate RL transition.\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"Space endpoint: `https://huggingface.co/spaces/kushalExplores/flatmate_rl`"
|
| 13 |
+
]
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"cell_type": "code",
|
| 17 |
+
"execution_count": null,
|
| 18 |
+
"id": "adabfca9",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"outputs": [],
|
| 21 |
+
"source": [
|
| 22 |
+
"# Restart the kernel after this cell if your notebook runtime asks you to.\n",
|
| 23 |
+
"%pip install -q \"trl>=0.26.2\" \"transformers>=4.57.0\" accelerate datasets peft websockets huggingface_hub matplotlib pandas"
|
| 24 |
+
]
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"cell_type": "code",
|
| 28 |
+
"execution_count": null,
|
| 29 |
+
"id": "b79df9da",
|
| 30 |
+
"metadata": {},
|
| 31 |
+
"outputs": [],
|
| 32 |
+
"source": [
|
| 33 |
+
"from __future__ import annotations\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"import asyncio\n",
|
| 36 |
+
"import json\n",
|
| 37 |
+
"import random\n",
|
| 38 |
+
"import threading\n",
|
| 39 |
+
"from dataclasses import dataclass\n",
|
| 40 |
+
"from typing import Any\n",
|
| 41 |
+
"from urllib.parse import urlparse\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"import websockets\n",
|
| 44 |
+
"from datasets import Dataset\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"SPACE_HTTP_URL = \"https://kushalexplores-flatmate-rl.hf.space\"\n",
|
| 47 |
+
"SCENARIOS = [\n",
|
| 48 |
+
" \"task_visit_single\",\n",
|
| 49 |
+
" \"task_visit_single_hidden_flex\",\n",
|
| 50 |
+
" \"task_visit_multi\",\n",
|
| 51 |
+
" \"task_visit_single_seller_followup\",\n",
|
| 52 |
+
"]\n",
|
| 53 |
+
"\n",
|
| 54 |
+
"def ws_url_from_http(base_url: str) -> str:\n",
|
| 55 |
+
" parsed = urlparse(base_url.rstrip(\"/\"))\n",
|
| 56 |
+
" scheme = \"wss\" if parsed.scheme == \"https\" else \"ws\"\n",
|
| 57 |
+
" return f\"{scheme}://{parsed.netloc}/ws\"\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"SPACE_WS_URL = ws_url_from_http(SPACE_HTTP_URL)\n",
|
| 60 |
+
"SPACE_WS_URL"
|
| 61 |
+
]
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "markdown",
|
| 65 |
+
"id": "ac8bdbfc",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"## Websocket Environment Client\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"OpenEnv keeps episode state on `/ws`. The plain HTTP `/reset` and `/step` endpoints create fresh environment instances, so GRPO reward replay uses websocket sessions."
|
| 71 |
+
]
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"execution_count": null,
|
| 76 |
+
"id": "bf61d6d4",
|
| 77 |
+
"metadata": {},
|
| 78 |
+
"outputs": [],
|
| 79 |
+
"source": [
|
| 80 |
+
"class FlatmateEndpoint:\n",
|
| 81 |
+
" def __init__(self, ws_url: str = SPACE_WS_URL, timeout_s: float = 120.0):\n",
|
| 82 |
+
" self.ws_url = ws_url\n",
|
| 83 |
+
" self.timeout_s = timeout_s\n",
|
| 84 |
+
"\n",
|
| 85 |
+
" async def __aenter__(self):\n",
|
| 86 |
+
" self.ws = await websockets.connect(\n",
|
| 87 |
+
" self.ws_url,\n",
|
| 88 |
+
" open_timeout=self.timeout_s,\n",
|
| 89 |
+
" ping_timeout=self.timeout_s,\n",
|
| 90 |
+
" )\n",
|
| 91 |
+
" return self\n",
|
| 92 |
+
"\n",
|
| 93 |
+
" async def __aexit__(self, exc_type, exc, tb):\n",
|
| 94 |
+
" try:\n",
|
| 95 |
+
" await self.ws.send(json.dumps({\"type\": \"close\"}))\n",
|
| 96 |
+
" finally:\n",
|
| 97 |
+
" await self.ws.close()\n",
|
| 98 |
+
"\n",
|
| 99 |
+
" async def _send(self, payload: dict[str, Any]) -> dict[str, Any]:\n",
|
| 100 |
+
" await self.ws.send(json.dumps(payload))\n",
|
| 101 |
+
" raw = await asyncio.wait_for(self.ws.recv(), timeout=self.timeout_s)\n",
|
| 102 |
+
" message = json.loads(raw)\n",
|
| 103 |
+
" if message.get(\"type\") == \"error\":\n",
|
| 104 |
+
" raise RuntimeError(message.get(\"data\", message))\n",
|
| 105 |
+
" data = message[\"data\"]\n",
|
| 106 |
+
" obs = data.get(\"observation\", {})\n",
|
| 107 |
+
" obs[\"reward\"] = data.get(\"reward\")\n",
|
| 108 |
+
" obs[\"done\"] = data.get(\"done\", False)\n",
|
| 109 |
+
" return obs\n",
|
| 110 |
+
"\n",
|
| 111 |
+
" async def reset(self, scenario_id: str, seed: int | None = None) -> dict[str, Any]:\n",
|
| 112 |
+
" data: dict[str, Any] = {\"scenario_id\": scenario_id}\n",
|
| 113 |
+
" if seed is not None:\n",
|
| 114 |
+
" data[\"seed\"] = seed\n",
|
| 115 |
+
" return await self._send({\"type\": \"reset\", \"data\": data})\n",
|
| 116 |
+
"\n",
|
| 117 |
+
" async def step(self, action: dict[str, Any]) -> dict[str, Any]:\n",
|
| 118 |
+
" return await self._send({\"type\": \"step\", \"data\": action})\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"async def smoke_test_endpoint():\n",
|
| 121 |
+
" async with FlatmateEndpoint() as env:\n",
|
| 122 |
+
" obs = await env.reset(\"task_visit_single\", seed=1)\n",
|
| 123 |
+
" print(obs[\"scenario_id\"], obs[\"status\"])\n",
|
| 124 |
+
" print(obs.get(\"last_user_message\") or obs.get(\"current_user_request\"))\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"await smoke_test_endpoint()"
|
| 127 |
+
]
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"cell_type": "markdown",
|
| 131 |
+
"id": "d6401b21",
|
| 132 |
+
"metadata": {},
|
| 133 |
+
"source": [
|
| 134 |
+
"## Prompt States\n",
|
| 135 |
+
"\n",
|
| 136 |
+
"GRPO needs prompts. These prompts are endpoint observations collected from heuristic rollouts. Each row also stores the action prefix needed to reconstruct that exact state during reward scoring."
|
| 137 |
+
]
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"cell_type": "code",
|
| 141 |
+
"execution_count": null,
|
| 142 |
+
"id": "c2ebe016",
|
| 143 |
+
"metadata": {},
|
| 144 |
+
"outputs": [],
|
| 145 |
+
"source": [
|
| 146 |
+
"def trace_tool_names(obs: dict[str, Any]) -> list[str]:\n",
|
| 147 |
+
" return [str(t.get(\"tool\", t.get(\"tool_name\", \"\"))) for t in obs.get(\"tool_trace\", [])]\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"def heuristic_action(obs: dict[str, Any]) -> dict[str, Any] | None:\n",
|
| 150 |
+
" tools = trace_tool_names(obs)\n",
|
| 151 |
+
" phase = obs.get(\"phase\", \"buyer\")\n",
|
| 152 |
+
" remaining = set(obs.get(\"remaining_required_fields\", []))\n",
|
| 153 |
+
" scenario_id = obs.get(\"scenario_id\", \"task_visit_single\")\n",
|
| 154 |
+
"\n",
|
| 155 |
+
" if phase == \"seller\" and not obs.get(\"seller_profile_stored\"):\n",
|
| 156 |
+
" if remaining:\n",
|
| 157 |
+
" return {\"action_type\": \"assistant_message\", \"assistant_message\": \"Please share the household dietary setup, who the flat is for, and available visit time slots.\"}\n",
|
| 158 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"store_seller_details\", \"tool_arguments\": {}}\n",
|
| 159 |
+
"\n",
|
| 160 |
+
" if not obs.get(\"buyer_profile_stored\"):\n",
|
| 161 |
+
" if \"diet\" in remaining and \"visit_availability\" in remaining:\n",
|
| 162 |
+
" return {\"action_type\": \"assistant_message\", \"assistant_message\": \"Please share your dietary preference and visit availability.\"}\n",
|
| 163 |
+
" if \"diet\" in remaining:\n",
|
| 164 |
+
" return {\"action_type\": \"assistant_message\", \"assistant_message\": \"Please share your dietary preference.\"}\n",
|
| 165 |
+
" if \"visit_availability\" in remaining:\n",
|
| 166 |
+
" return {\"action_type\": \"assistant_message\", \"assistant_message\": \"Please share your visit availability.\"}\n",
|
| 167 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"store_user_details\", \"tool_arguments\": {}}\n",
|
| 168 |
+
"\n",
|
| 169 |
+
" post_ids = [\"post_031\", \"post_052\"] if scenario_id == \"task_visit_multi\" else [\"post_031\"]\n",
|
| 170 |
+
" if \"search_posts\" not in tools:\n",
|
| 171 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"search_posts\", \"tool_arguments\": {}}\n",
|
| 172 |
+
" if \"match_location_preference\" not in tools:\n",
|
| 173 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"match_location_preference\", \"tool_arguments\": {\"post_ids\": post_ids}}\n",
|
| 174 |
+
" if \"get_commute_time\" not in tools:\n",
|
| 175 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"get_commute_time\", \"tool_arguments\": {\"post_ids\": post_ids}}\n",
|
| 176 |
+
" if \"check_calendar_slots\" not in tools:\n",
|
| 177 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"check_calendar_slots\", \"tool_arguments\": {\"post_ids\": post_ids}}\n",
|
| 178 |
+
" if \"shortlist\" not in tools:\n",
|
| 179 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"shortlist\", \"tool_arguments\": {\"post_ids\": post_ids}}\n",
|
| 180 |
+
" if \"contact_poster\" not in tools:\n",
|
| 181 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"contact_poster\", \"tool_arguments\": {\"post_id\": post_ids[0], \"time_text\": \"tomorrow 7pm\"}}\n",
|
| 182 |
+
" if \"book_viewing\" not in tools:\n",
|
| 183 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"book_viewing\", \"tool_arguments\": {\"post_id\": post_ids[0], \"time_text\": \"tomorrow 7pm\"}}\n",
|
| 184 |
+
" return None\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"def compact_observation(obs: dict[str, Any]) -> dict[str, Any]:\n",
|
| 187 |
+
" return {\n",
|
| 188 |
+
" \"scenario_id\": obs.get(\"scenario_id\"),\n",
|
| 189 |
+
" \"phase\": obs.get(\"phase\"),\n",
|
| 190 |
+
" \"status\": obs.get(\"status\"),\n",
|
| 191 |
+
" \"last_user_message\": obs.get(\"last_user_message\"),\n",
|
| 192 |
+
" \"current_user_request\": obs.get(\"current_user_request\"),\n",
|
| 193 |
+
" \"available_tools\": obs.get(\"available_tools\", []),\n",
|
| 194 |
+
" \"remaining_required_fields\": obs.get(\"remaining_required_fields\", []),\n",
|
| 195 |
+
" \"prerequisites_satisfied\": obs.get(\"prerequisites_satisfied\", {}),\n",
|
| 196 |
+
" \"recent_tool_calls\": obs.get(\"recent_tool_calls\", []),\n",
|
| 197 |
+
" \"last_tool_result\": obs.get(\"last_tool_result\", {}),\n",
|
| 198 |
+
" \"violations\": obs.get(\"violations\", []),\n",
|
| 199 |
+
" \"booked_visits\": obs.get(\"booked_visits\", []),\n",
|
| 200 |
+
" \"feedback_summary\": obs.get(\"feedback_summary\", \"\"),\n",
|
| 201 |
+
" }\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"def prompt_from_observation(obs: dict[str, Any]) -> str:\n",
|
| 204 |
+
" return (\n",
|
| 205 |
+
" \"You are a broker policy for the Flatmate RL environment. \"\n",
|
| 206 |
+
" \"Return exactly one JSON action and no extra text.\\n\\n\"\n",
|
| 207 |
+
" \"Valid action shapes:\\n\"\n",
|
| 208 |
+
" \"{\\\"action_type\\\":\\\"assistant_message\\\",\\\"assistant_message\\\":\\\"...\\\"}\\n\"\n",
|
| 209 |
+
" \"{\\\"action_type\\\":\\\"tool_call\\\",\\\"tool_name\\\":\\\"...\\\",\\\"tool_arguments\\\":{...}}\\n\\n\"\n",
|
| 210 |
+
" f\"Observation:\\n{json.dumps(compact_observation(obs), ensure_ascii=False, sort_keys=True)}\\n\\n\"\n",
|
| 211 |
+
" \"Action:\\n\"\n",
|
| 212 |
+
" )"
|
| 213 |
+
]
|
| 214 |
+
},
|
| 215 |
+
{
|
| 216 |
+
"cell_type": "code",
|
| 217 |
+
"execution_count": null,
|
| 218 |
+
"id": "d29c9dc5",
|
| 219 |
+
"metadata": {},
|
| 220 |
+
"outputs": [],
|
| 221 |
+
"source": [
|
| 222 |
+
"@dataclass\n",
|
| 223 |
+
"class PromptCollectionConfig:\n",
|
| 224 |
+
" episodes: int = 12\n",
|
| 225 |
+
" max_steps: int = 14\n",
|
| 226 |
+
" seed: int = 11\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"async def collect_prompt_rows(config: PromptCollectionConfig = PromptCollectionConfig()) -> list[dict[str, Any]]:\n",
|
| 229 |
+
" rng = random.Random(config.seed)\n",
|
| 230 |
+
" rows: list[dict[str, Any]] = []\n",
|
| 231 |
+
" for episode_idx in range(config.episodes):\n",
|
| 232 |
+
" scenario_id = rng.choice(SCENARIOS)\n",
|
| 233 |
+
" prefix_actions: list[dict[str, Any]] = []\n",
|
| 234 |
+
" async with FlatmateEndpoint() as env:\n",
|
| 235 |
+
" obs = await env.reset(scenario_id, seed=config.seed + episode_idx)\n",
|
| 236 |
+
" for step_idx in range(config.max_steps):\n",
|
| 237 |
+
" action = heuristic_action(obs)\n",
|
| 238 |
+
" if action is None or obs.get(\"done\"):\n",
|
| 239 |
+
" break\n",
|
| 240 |
+
" rows.append({\n",
|
| 241 |
+
" \"prompt\": prompt_from_observation(obs),\n",
|
| 242 |
+
" \"scenario_id\": scenario_id,\n",
|
| 243 |
+
" \"seed\": config.seed + episode_idx,\n",
|
| 244 |
+
" \"prefix_actions_json\": json.dumps(prefix_actions, ensure_ascii=False),\n",
|
| 245 |
+
" \"reference_action_json\": json.dumps(action, ensure_ascii=False, sort_keys=True),\n",
|
| 246 |
+
" })\n",
|
| 247 |
+
" obs = await env.step(action)\n",
|
| 248 |
+
" prefix_actions.append(action)\n",
|
| 249 |
+
" if obs.get(\"done\"):\n",
|
| 250 |
+
" break\n",
|
| 251 |
+
" print(f\"episode={episode_idx:02d} scenario={scenario_id} total_rows={len(rows)}\")\n",
|
| 252 |
+
" return rows\n",
|
| 253 |
+
"\n",
|
| 254 |
+
"rows = await collect_prompt_rows(PromptCollectionConfig(episodes=12, max_steps=14))\n",
|
| 255 |
+
"train_dataset = Dataset.from_list(rows)\n",
|
| 256 |
+
"train_dataset"
|
| 257 |
+
]
|
| 258 |
+
},
|
| 259 |
+
{
|
| 260 |
+
"cell_type": "markdown",
|
| 261 |
+
"id": "a10b4cd1",
|
| 262 |
+
"metadata": {},
|
| 263 |
+
"source": [
|
| 264 |
+
"## GRPO Rewards\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"`json_format_reward` is cheap and runs for every completion. `endpoint_transition_reward` is slower because it calls the live Space: it replays the prefix actions, sends the generated action, and returns a reward based on environment reward, validity, violations, and bookings."
|
| 267 |
+
]
|
| 268 |
+
},
|
| 269 |
+
{
|
| 270 |
+
"cell_type": "code",
|
| 271 |
+
"execution_count": null,
|
| 272 |
+
"id": "e7bdfc62",
|
| 273 |
+
"metadata": {},
|
| 274 |
+
"outputs": [],
|
| 275 |
+
"source": [
|
| 276 |
+
"def completion_text(completion: Any) -> str:\n",
|
| 277 |
+
" if isinstance(completion, str):\n",
|
| 278 |
+
" return completion\n",
|
| 279 |
+
" if isinstance(completion, list) and completion and isinstance(completion[0], dict):\n",
|
| 280 |
+
" return str(completion[0].get(\"content\", \"\"))\n",
|
| 281 |
+
" return str(completion)\n",
|
| 282 |
+
"\n",
|
| 283 |
+
"def parse_json_action(text: str) -> dict[str, Any]:\n",
|
| 284 |
+
" text = completion_text(text).strip()\n",
|
| 285 |
+
" start = text.find(\"{\")\n",
|
| 286 |
+
" end = text.rfind(\"}\")\n",
|
| 287 |
+
" if start == -1 or end == -1 or end <= start:\n",
|
| 288 |
+
" raise ValueError(\"completion does not contain a JSON object\")\n",
|
| 289 |
+
" action = json.loads(text[start : end + 1])\n",
|
| 290 |
+
" if action.get(\"action_type\") == \"assistant_message\":\n",
|
| 291 |
+
" if not str(action.get(\"assistant_message\", \"\")).strip():\n",
|
| 292 |
+
" raise ValueError(\"assistant_message action needs assistant_message\")\n",
|
| 293 |
+
" return {\n",
|
| 294 |
+
" \"action_type\": \"assistant_message\",\n",
|
| 295 |
+
" \"assistant_message\": str(action[\"assistant_message\"]),\n",
|
| 296 |
+
" }\n",
|
| 297 |
+
" if action.get(\"action_type\") == \"tool_call\":\n",
|
| 298 |
+
" if not str(action.get(\"tool_name\", \"\")).strip():\n",
|
| 299 |
+
" raise ValueError(\"tool_call action needs tool_name\")\n",
|
| 300 |
+
" args = action.get(\"tool_arguments\", {})\n",
|
| 301 |
+
" if not isinstance(args, dict):\n",
|
| 302 |
+
" raise ValueError(\"tool_arguments must be an object\")\n",
|
| 303 |
+
" return {\n",
|
| 304 |
+
" \"action_type\": \"tool_call\",\n",
|
| 305 |
+
" \"tool_name\": str(action[\"tool_name\"]),\n",
|
| 306 |
+
" \"tool_arguments\": args,\n",
|
| 307 |
+
" }\n",
|
| 308 |
+
" raise ValueError(\"action_type must be assistant_message or tool_call\")\n",
|
| 309 |
+
"\n",
|
| 310 |
+
"def json_format_reward(completions, **kwargs) -> list[float]:\n",
|
| 311 |
+
" rewards = []\n",
|
| 312 |
+
" for completion in completions:\n",
|
| 313 |
+
" try:\n",
|
| 314 |
+
" parse_json_action(completion_text(completion))\n",
|
| 315 |
+
" rewards.append(0.25)\n",
|
| 316 |
+
" except Exception:\n",
|
| 317 |
+
" rewards.append(-1.0)\n",
|
| 318 |
+
" return rewards\n",
|
| 319 |
+
"\n",
|
| 320 |
+
"async def score_one_completion(\n",
|
| 321 |
+
" completion: Any,\n",
|
| 322 |
+
" scenario_id: str,\n",
|
| 323 |
+
" seed: int,\n",
|
| 324 |
+
" prefix_actions_json: str,\n",
|
| 325 |
+
") -> float:\n",
|
| 326 |
+
" try:\n",
|
| 327 |
+
" action = parse_json_action(completion_text(completion))\n",
|
| 328 |
+
" prefix_actions = json.loads(prefix_actions_json)\n",
|
| 329 |
+
" except Exception:\n",
|
| 330 |
+
" return -1.0\n",
|
| 331 |
+
"\n",
|
| 332 |
+
" try:\n",
|
| 333 |
+
" async with FlatmateEndpoint() as env:\n",
|
| 334 |
+
" obs = await env.reset(scenario_id, seed=int(seed))\n",
|
| 335 |
+
" for prefix_action in prefix_actions:\n",
|
| 336 |
+
" obs = await env.step(prefix_action)\n",
|
| 337 |
+
" if obs.get(\"done\"):\n",
|
| 338 |
+
" return -0.5\n",
|
| 339 |
+
"\n",
|
| 340 |
+
" before_violations = len(obs.get(\"violations\", []))\n",
|
| 341 |
+
" before_bookings = len(obs.get(\"booked_visits\", []))\n",
|
| 342 |
+
" obs = await env.step(action)\n",
|
| 343 |
+
"\n",
|
| 344 |
+
" reward = float(obs.get(\"reward\") or obs.get(\"step_reward\") or 0.0)\n",
|
| 345 |
+
" reward += 0.15\n",
|
| 346 |
+
" if len(obs.get(\"violations\", [])) > before_violations:\n",
|
| 347 |
+
" reward -= 0.75\n",
|
| 348 |
+
" if len(obs.get(\"booked_visits\", [])) > before_bookings:\n",
|
| 349 |
+
" reward += 1.0\n",
|
| 350 |
+
" if obs.get(\"done\"):\n",
|
| 351 |
+
" reward += 0.5\n",
|
| 352 |
+
" return float(max(-2.0, min(2.0, reward)))\n",
|
| 353 |
+
" except Exception as exc:\n",
|
| 354 |
+
" print(\"endpoint reward error:\", repr(exc))\n",
|
| 355 |
+
" return -1.0\n",
|
| 356 |
+
"\n",
|
| 357 |
+
"async def score_completion_batch(completions, scenario_id, seed, prefix_actions_json) -> list[float]:\n",
|
| 358 |
+
" tasks = [\n",
|
| 359 |
+
" score_one_completion(c, s, int(sd), p)\n",
|
| 360 |
+
" for c, s, sd, p in zip(completions, scenario_id, seed, prefix_actions_json)\n",
|
| 361 |
+
" ]\n",
|
| 362 |
+
" return list(await asyncio.gather(*tasks))\n",
|
| 363 |
+
"\n",
|
| 364 |
+
"def run_async_blocking(coro):\n",
|
| 365 |
+
" try:\n",
|
| 366 |
+
" asyncio.get_running_loop()\n",
|
| 367 |
+
" except RuntimeError:\n",
|
| 368 |
+
" return asyncio.run(coro)\n",
|
| 369 |
+
"\n",
|
| 370 |
+
" result: dict[str, Any] = {}\n",
|
| 371 |
+
" def runner():\n",
|
| 372 |
+
" try:\n",
|
| 373 |
+
" result[\"value\"] = asyncio.run(coro)\n",
|
| 374 |
+
" except Exception as exc:\n",
|
| 375 |
+
" result[\"error\"] = exc\n",
|
| 376 |
+
"\n",
|
| 377 |
+
" thread = threading.Thread(target=runner, daemon=True)\n",
|
| 378 |
+
" thread.start()\n",
|
| 379 |
+
" thread.join()\n",
|
| 380 |
+
" if \"error\" in result:\n",
|
| 381 |
+
" raise result[\"error\"]\n",
|
| 382 |
+
" return result[\"value\"]\n",
|
| 383 |
+
"\n",
|
| 384 |
+
"def endpoint_transition_reward(completions, scenario_id, seed, prefix_actions_json, **kwargs) -> list[float]:\n",
|
| 385 |
+
" return run_async_blocking(score_completion_batch(completions, scenario_id, seed, prefix_actions_json))\n",
|
| 386 |
+
"\n",
|
| 387 |
+
"# Quick reward smoke test with known reference actions from the collected dataset.\n",
|
| 388 |
+
"sample = train_dataset.select(range(min(2, len(train_dataset))))\n",
|
| 389 |
+
"endpoint_transition_reward(\n",
|
| 390 |
+
" completions=sample[\"reference_action_json\"],\n",
|
| 391 |
+
" scenario_id=sample[\"scenario_id\"],\n",
|
| 392 |
+
" seed=sample[\"seed\"],\n",
|
| 393 |
+
" prefix_actions_json=sample[\"prefix_actions_json\"],\n",
|
| 394 |
+
")"
|
| 395 |
+
]
|
| 396 |
+
},
|
| 397 |
+
{
|
| 398 |
+
"cell_type": "markdown",
|
| 399 |
+
"id": "d286bdc7",
|
| 400 |
+
"metadata": {},
|
| 401 |
+
"source": [
|
| 402 |
+
"## Train with GRPO\n",
|
| 403 |
+
"\n",
|
| 404 |
+
"The endpoint reward is network-bound, so keep `num_generations`, dataset size, and max steps small until the loop is stable. Increase them once you see valid JSON actions and non-negative endpoint rewards."
|
| 405 |
+
]
|
| 406 |
+
},
|
| 407 |
+
{
|
| 408 |
+
"cell_type": "code",
|
| 409 |
+
"execution_count": null,
|
| 410 |
+
"id": "a6323589",
|
| 411 |
+
"metadata": {},
|
| 412 |
+
"outputs": [],
|
| 413 |
+
"source": [
|
| 414 |
+
"import inspect\n",
|
| 415 |
+
"\n",
|
| 416 |
+
"from peft import LoraConfig\n",
|
| 417 |
+
"from trl import GRPOConfig, GRPOTrainer\n",
|
| 418 |
+
"\n",
|
| 419 |
+
"MODEL_NAME = \"Qwen/Qwen2.5-0.5B-Instruct\"\n",
|
| 420 |
+
"OUTPUT_DIR = \"flatmate-rl-grpo-policy\"\n",
|
| 421 |
+
"\n",
|
| 422 |
+
"peft_config = LoraConfig(\n",
|
| 423 |
+
" r=16,\n",
|
| 424 |
+
" lora_alpha=32,\n",
|
| 425 |
+
" lora_dropout=0.05,\n",
|
| 426 |
+
" bias=\"none\",\n",
|
| 427 |
+
" task_type=\"CAUSAL_LM\",\n",
|
| 428 |
+
" target_modules=[\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\", \"gate_proj\", \"up_proj\", \"down_proj\"],\n",
|
| 429 |
+
")\n",
|
| 430 |
+
"\n",
|
| 431 |
+
"def make_grpo_config(**kwargs):\n",
|
| 432 |
+
" valid = set(inspect.signature(GRPOConfig.__init__).parameters)\n",
|
| 433 |
+
" filtered = {key: value for key, value in kwargs.items() if key in valid}\n",
|
| 434 |
+
" skipped = sorted(set(kwargs) - set(filtered))\n",
|
| 435 |
+
" if skipped:\n",
|
| 436 |
+
" print(\"Skipping unsupported GRPOConfig fields for this TRL version:\", skipped)\n",
|
| 437 |
+
" return GRPOConfig(**filtered)\n",
|
| 438 |
+
"\n",
|
| 439 |
+
"training_args = make_grpo_config(\n",
|
| 440 |
+
" output_dir=OUTPUT_DIR,\n",
|
| 441 |
+
" learning_rate=1e-5,\n",
|
| 442 |
+
" per_device_train_batch_size=1,\n",
|
| 443 |
+
" gradient_accumulation_steps=4,\n",
|
| 444 |
+
" num_generations=4,\n",
|
| 445 |
+
" max_prompt_length=1536,\n",
|
| 446 |
+
" max_completion_length=160,\n",
|
| 447 |
+
" max_steps=30,\n",
|
| 448 |
+
" logging_steps=1,\n",
|
| 449 |
+
" save_steps=15,\n",
|
| 450 |
+
" save_total_limit=2,\n",
|
| 451 |
+
" report_to=\"none\",\n",
|
| 452 |
+
")\n",
|
| 453 |
+
"\n",
|
| 454 |
+
"trainer = GRPOTrainer(\n",
|
| 455 |
+
" model=MODEL_NAME,\n",
|
| 456 |
+
" reward_funcs=[json_format_reward, endpoint_transition_reward],\n",
|
| 457 |
+
" args=training_args,\n",
|
| 458 |
+
" train_dataset=train_dataset,\n",
|
| 459 |
+
" peft_config=peft_config,\n",
|
| 460 |
+
")\n",
|
| 461 |
+
"\n",
|
| 462 |
+
"train_result = trainer.train()\n",
|
| 463 |
+
"train_log_history = trainer.state.log_history\n",
|
| 464 |
+
"trainer.save_model(OUTPUT_DIR)\n",
|
| 465 |
+
"train_result"
|
| 466 |
+
]
|
| 467 |
+
},
|
| 468 |
+
{
|
| 469 |
+
"cell_type": "markdown",
|
| 470 |
+
"id": "da41a231",
|
| 471 |
+
"metadata": {},
|
| 472 |
+
"source": [
|
| 473 |
+
"## Training Log\n",
|
| 474 |
+
"\n",
|
| 475 |
+
"Plot logged GRPO reward and loss curves over optimizer steps."
|
| 476 |
+
]
|
| 477 |
+
},
|
| 478 |
+
{
|
| 479 |
+
"cell_type": "code",
|
| 480 |
+
"execution_count": null,
|
| 481 |
+
"id": "a6c8071d",
|
| 482 |
+
"metadata": {},
|
| 483 |
+
"outputs": [],
|
| 484 |
+
"source": [
|
| 485 |
+
"import json\n",
|
| 486 |
+
"from pathlib import Path\n",
|
| 487 |
+
"\n",
|
| 488 |
+
"import matplotlib.pyplot as plt\n",
|
| 489 |
+
"import pandas as pd\n",
|
| 490 |
+
"\n",
|
| 491 |
+
"log_path = Path(OUTPUT_DIR) / \"train_log_history.json\"\n",
|
| 492 |
+
"log_path.parent.mkdir(parents=True, exist_ok=True)\n",
|
| 493 |
+
"log_path.write_text(json.dumps(train_log_history, indent=2))\n",
|
| 494 |
+
"\n",
|
| 495 |
+
"def plot_training_log(log_history, title: str = \"GRPO training log\"):\n",
|
| 496 |
+
" df = pd.DataFrame(log_history)\n",
|
| 497 |
+
" if df.empty:\n",
|
| 498 |
+
" print(\"No trainer log rows found yet.\")\n",
|
| 499 |
+
" return df\n",
|
| 500 |
+
" metric_cols = [col for col in [\"loss\", \"reward\", \"rewards/json_format_reward\", \"rewards/endpoint_transition_reward\", \"kl\"] if col in df.columns]\n",
|
| 501 |
+
" if not metric_cols:\n",
|
| 502 |
+
" metric_cols = [col for col in df.columns if \"reward\" in col or col in {\"loss\", \"kl\"}]\n",
|
| 503 |
+
" if not metric_cols or \"step\" not in df.columns:\n",
|
| 504 |
+
" print(\"No plottable step metrics found. Available columns:\", list(df.columns))\n",
|
| 505 |
+
" return df\n",
|
| 506 |
+
" axes = df.dropna(subset=[\"step\"]).plot(\n",
|
| 507 |
+
" x=\"step\",\n",
|
| 508 |
+
" y=metric_cols,\n",
|
| 509 |
+
" marker=\"o\",\n",
|
| 510 |
+
" figsize=(9, 4),\n",
|
| 511 |
+
" title=title,\n",
|
| 512 |
+
" )\n",
|
| 513 |
+
" axes.set_xlabel(\"optimizer step\")\n",
|
| 514 |
+
" axes.grid(True, alpha=0.3)\n",
|
| 515 |
+
" plt.show()\n",
|
| 516 |
+
" return df\n",
|
| 517 |
+
"\n",
|
| 518 |
+
"train_log_df = plot_training_log(train_log_history)\n",
|
| 519 |
+
"train_log_df.tail()"
|
| 520 |
+
]
|
| 521 |
+
},
|
| 522 |
+
{
|
| 523 |
+
"cell_type": "markdown",
|
| 524 |
+
"id": "c013682e",
|
| 525 |
+
"metadata": {},
|
| 526 |
+
"source": [
|
| 527 |
+
"## Evaluate One Episode"
|
| 528 |
+
]
|
| 529 |
+
},
|
| 530 |
+
{
|
| 531 |
+
"cell_type": "code",
|
| 532 |
+
"execution_count": null,
|
| 533 |
+
"id": "d4cc3bc3",
|
| 534 |
+
"metadata": {},
|
| 535 |
+
"outputs": [],
|
| 536 |
+
"source": [
|
| 537 |
+
"import torch\n",
|
| 538 |
+
"from peft import AutoPeftModelForCausalLM\n",
|
| 539 |
+
"from transformers import AutoModelForCausalLM, AutoTokenizer\n",
|
| 540 |
+
"\n",
|
| 541 |
+
"tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)\n",
|
| 542 |
+
"if tokenizer.pad_token is None:\n",
|
| 543 |
+
" tokenizer.pad_token = tokenizer.eos_token\n",
|
| 544 |
+
"\n",
|
| 545 |
+
"base_model_for_eval = AutoModelForCausalLM.from_pretrained(\n",
|
| 546 |
+
" MODEL_NAME,\n",
|
| 547 |
+
" trust_remote_code=True,\n",
|
| 548 |
+
" device_map=\"auto\",\n",
|
| 549 |
+
")\n",
|
| 550 |
+
"base_model_for_eval.eval()\n",
|
| 551 |
+
"base_model_for_eval.config.use_cache = False\n",
|
| 552 |
+
"\n",
|
| 553 |
+
"loaded_model_for_eval = AutoPeftModelForCausalLM.from_pretrained(OUTPUT_DIR, device_map=\"auto\")\n",
|
| 554 |
+
"loaded_model_for_eval.eval()\n",
|
| 555 |
+
"loaded_model_for_eval.config.use_cache = False\n",
|
| 556 |
+
"active_model = loaded_model_for_eval\n",
|
| 557 |
+
"print(f\"Loaded base model from {MODEL_NAME}\")\n",
|
| 558 |
+
"print(f\"Loaded saved GRPO model from {OUTPUT_DIR}\")\n",
|
| 559 |
+
"\n",
|
| 560 |
+
"generation_stats = {\"fallbacks\": 0, \"parse_errors\": []}\n",
|
| 561 |
+
"\n",
|
| 562 |
+
"\n",
|
| 563 |
+
"def safe_model_action(obs: dict[str, Any], log_bad: bool = False) -> dict[str, Any]:\n",
|
| 564 |
+
" # Prefix the completion with \"{\" so the model only has to finish a JSON object.\n",
|
| 565 |
+
" prompt = prompt_from_observation(obs) + \"{\"\n",
|
| 566 |
+
" inputs = tokenizer(prompt, return_tensors=\"pt\", truncation=True, max_length=1536).to(active_model.device)\n",
|
| 567 |
+
" active_model.generation_config.do_sample = False\n",
|
| 568 |
+
" active_model.generation_config.temperature = None\n",
|
| 569 |
+
" active_model.generation_config.top_p = None\n",
|
| 570 |
+
" active_model.generation_config.top_k = None\n",
|
| 571 |
+
" with torch.no_grad():\n",
|
| 572 |
+
" output = active_model.generate(\n",
|
| 573 |
+
" **inputs,\n",
|
| 574 |
+
" max_new_tokens=80,\n",
|
| 575 |
+
" do_sample=False,\n",
|
| 576 |
+
" repetition_penalty=1.15,\n",
|
| 577 |
+
" no_repeat_ngram_size=3,\n",
|
| 578 |
+
" eos_token_id=tokenizer.eos_token_id,\n",
|
| 579 |
+
" pad_token_id=tokenizer.eos_token_id,\n",
|
| 580 |
+
" )\n",
|
| 581 |
+
" completion_tail = tokenizer.decode(output[0][inputs[\"input_ids\"].shape[-1]:], skip_special_tokens=True)\n",
|
| 582 |
+
" completion = \"{\" + completion_tail\n",
|
| 583 |
+
" try:\n",
|
| 584 |
+
" return parse_json_action(completion)\n",
|
| 585 |
+
" except Exception as exc:\n",
|
| 586 |
+
" generation_stats[\"fallbacks\"] += 1\n",
|
| 587 |
+
" if len(generation_stats[\"parse_errors\"]) < 5:\n",
|
| 588 |
+
" generation_stats[\"parse_errors\"].append({\"error\": str(exc), \"completion\": completion[:300]})\n",
|
| 589 |
+
" if log_bad:\n",
|
| 590 |
+
" print(f\"bad generation, using fallback: {exc}\")\n",
|
| 591 |
+
" print(\"raw completion:\", repr(completion[:300]))\n",
|
| 592 |
+
" fallback = heuristic_action(obs)\n",
|
| 593 |
+
" if fallback is None:\n",
|
| 594 |
+
" fallback = {\"action_type\": \"assistant_message\", \"assistant_message\": \"Could you confirm the details needed for scheduling?\"}\n",
|
| 595 |
+
" return fallback\n",
|
| 596 |
+
"\n",
|
| 597 |
+
"def heuristic_policy(obs: dict[str, Any]) -> dict[str, Any]:\n",
|
| 598 |
+
" action = heuristic_action(obs)\n",
|
| 599 |
+
" if action is None:\n",
|
| 600 |
+
" return {\"action_type\": \"assistant_message\", \"assistant_message\": \"Could you confirm the details needed for scheduling?\"}\n",
|
| 601 |
+
" return action\n",
|
| 602 |
+
"\n",
|
| 603 |
+
"async def evaluate_policy(policy_fn, label: str, scenarios=SCENARIOS, seeds=(123, 124), max_steps: int = 20, verbose: bool = False):\n",
|
| 604 |
+
" rows = []\n",
|
| 605 |
+
" for scenario_id in scenarios:\n",
|
| 606 |
+
" for seed in seeds:\n",
|
| 607 |
+
" before_fallbacks = generation_stats[\"fallbacks\"] if \"generation_stats\" in globals() else 0\n",
|
| 608 |
+
" async with FlatmateEndpoint() as env:\n",
|
| 609 |
+
" obs = await env.reset(scenario_id, seed=seed)\n",
|
| 610 |
+
" total_reward = 0.0\n",
|
| 611 |
+
" steps = 0\n",
|
| 612 |
+
" for step_idx in range(max_steps):\n",
|
| 613 |
+
" action = policy_fn(obs)\n",
|
| 614 |
+
" if verbose:\n",
|
| 615 |
+
" print(label, scenario_id, seed, step_idx, action)\n",
|
| 616 |
+
" obs = await env.step(action)\n",
|
| 617 |
+
" steps = step_idx + 1\n",
|
| 618 |
+
" total_reward += float(obs.get(\"reward\") or obs.get(\"step_reward\") or 0.0)\n",
|
| 619 |
+
" if obs.get(\"done\"):\n",
|
| 620 |
+
" break\n",
|
| 621 |
+
" after_fallbacks = generation_stats[\"fallbacks\"] if \"generation_stats\" in globals() else before_fallbacks\n",
|
| 622 |
+
" rows.append({\n",
|
| 623 |
+
" \"policy\": label,\n",
|
| 624 |
+
" \"scenario_id\": scenario_id,\n",
|
| 625 |
+
" \"seed\": seed,\n",
|
| 626 |
+
" \"total_reward\": total_reward,\n",
|
| 627 |
+
" \"done\": bool(obs.get(\"done\")),\n",
|
| 628 |
+
" \"bookings\": len(obs.get(\"booked_visits\", [])),\n",
|
| 629 |
+
" \"violations\": len(obs.get(\"violations\", [])),\n",
|
| 630 |
+
" \"steps\": steps,\n",
|
| 631 |
+
" \"fallbacks\": after_fallbacks - before_fallbacks,\n",
|
| 632 |
+
" })\n",
|
| 633 |
+
" return rows\n",
|
| 634 |
+
"\n",
|
| 635 |
+
"def raw_generate_action_text(obs: dict[str, Any]) -> str:\n",
|
| 636 |
+
" prompt = prompt_from_observation(obs) + \"{\"\n",
|
| 637 |
+
" inputs = tokenizer(prompt, return_tensors=\"pt\", truncation=True, max_length=1536).to(active_model.device)\n",
|
| 638 |
+
" active_model.generation_config.do_sample = False\n",
|
| 639 |
+
" active_model.generation_config.temperature = None\n",
|
| 640 |
+
" active_model.generation_config.top_p = None\n",
|
| 641 |
+
" active_model.generation_config.top_k = None\n",
|
| 642 |
+
" with torch.no_grad():\n",
|
| 643 |
+
" output = active_model.generate(\n",
|
| 644 |
+
" **inputs,\n",
|
| 645 |
+
" max_new_tokens=80,\n",
|
| 646 |
+
" do_sample=False,\n",
|
| 647 |
+
" repetition_penalty=1.15,\n",
|
| 648 |
+
" no_repeat_ngram_size=3,\n",
|
| 649 |
+
" eos_token_id=tokenizer.eos_token_id,\n",
|
| 650 |
+
" pad_token_id=tokenizer.eos_token_id,\n",
|
| 651 |
+
" )\n",
|
| 652 |
+
" return \"{\" + tokenizer.decode(output[0][inputs[\"input_ids\"].shape[-1]:], skip_special_tokens=True)\n",
|
| 653 |
+
"\n",
|
| 654 |
+
"async def sanity_check_generations(limit: int = 4):\n",
|
| 655 |
+
" rows = []\n",
|
| 656 |
+
" for scenario_id in SCENARIOS[:limit]:\n",
|
| 657 |
+
" async with FlatmateEndpoint() as env:\n",
|
| 658 |
+
" obs = await env.reset(scenario_id, seed=321)\n",
|
| 659 |
+
" raw = raw_generate_action_text(obs)\n",
|
| 660 |
+
" try:\n",
|
| 661 |
+
" parsed = parse_json_action(raw)\n",
|
| 662 |
+
" ok = True\n",
|
| 663 |
+
" except Exception as exc:\n",
|
| 664 |
+
" parsed = str(exc)\n",
|
| 665 |
+
" ok = False\n",
|
| 666 |
+
" rows.append({\"scenario_id\": scenario_id, \"json_ok\": ok, \"raw\": raw[:240], \"parsed_or_error\": parsed})\n",
|
| 667 |
+
" return pd.DataFrame(rows)\n",
|
| 668 |
+
"\n",
|
| 669 |
+
"async def run_inference_each_task(policy_fn, label: str, seed: int = 321, max_steps: int = 20):\n",
|
| 670 |
+
" rows = []\n",
|
| 671 |
+
" for scenario_id in SCENARIOS:\n",
|
| 672 |
+
" print(f\"\\n=== {label}: {scenario_id} ===\")\n",
|
| 673 |
+
" async with FlatmateEndpoint() as env:\n",
|
| 674 |
+
" obs = await env.reset(scenario_id, seed=seed)\n",
|
| 675 |
+
" total_reward = 0.0\n",
|
| 676 |
+
" steps = 0\n",
|
| 677 |
+
" before_fallbacks = generation_stats[\"fallbacks\"]\n",
|
| 678 |
+
" for step_idx in range(max_steps):\n",
|
| 679 |
+
" action = policy_fn(obs)\n",
|
| 680 |
+
" print(f\"step={step_idx:02d} action={action}\")\n",
|
| 681 |
+
" obs = await env.step(action)\n",
|
| 682 |
+
" steps = step_idx + 1\n",
|
| 683 |
+
" total_reward += float(obs.get(\"reward\") or obs.get(\"step_reward\") or 0.0)\n",
|
| 684 |
+
" if obs.get(\"done\"):\n",
|
| 685 |
+
" break\n",
|
| 686 |
+
" result = {\n",
|
| 687 |
+
" \"policy\": label,\n",
|
| 688 |
+
" \"scenario_id\": scenario_id,\n",
|
| 689 |
+
" \"seed\": seed,\n",
|
| 690 |
+
" \"total_reward\": total_reward,\n",
|
| 691 |
+
" \"done\": bool(obs.get(\"done\")),\n",
|
| 692 |
+
" \"bookings\": len(obs.get(\"booked_visits\", [])),\n",
|
| 693 |
+
" \"violations\": len(obs.get(\"violations\", [])),\n",
|
| 694 |
+
" \"steps\": steps,\n",
|
| 695 |
+
" \"fallbacks\": generation_stats[\"fallbacks\"] - before_fallbacks,\n",
|
| 696 |
+
" }\n",
|
| 697 |
+
" print(\"result=\", result)\n",
|
| 698 |
+
" rows.append(result)\n",
|
| 699 |
+
" return pd.DataFrame(rows)\n",
|
| 700 |
+
"\n",
|
| 701 |
+
"generation_stats = {\"fallbacks\": 0, \"parse_errors\": []}\n",
|
| 702 |
+
"active_model = base_model_for_eval\n",
|
| 703 |
+
"base_generation_sanity_df = await sanity_check_generations()\n",
|
| 704 |
+
"base_generation_sanity_df[\"model\"] = \"base\"\n",
|
| 705 |
+
"base_per_task_inference_df = await run_inference_each_task(safe_model_action, \"base_model\")\n",
|
| 706 |
+
"base_model_eval = await evaluate_policy(safe_model_action, \"base_model\")\n",
|
| 707 |
+
"base_stats = dict(generation_stats)\n",
|
| 708 |
+
"\n",
|
| 709 |
+
"active_model = loaded_model_for_eval\n",
|
| 710 |
+
"generation_stats = {\"fallbacks\": 0, \"parse_errors\": []}\n",
|
| 711 |
+
"loaded_generation_sanity_df = await sanity_check_generations()\n",
|
| 712 |
+
"loaded_generation_sanity_df[\"model\"] = \"grpo_loaded\"\n",
|
| 713 |
+
"loaded_per_task_inference_df = await run_inference_each_task(safe_model_action, \"grpo_loaded\")\n",
|
| 714 |
+
"per_task_inference_df = pd.concat([base_per_task_inference_df, loaded_per_task_inference_df], ignore_index=True)\n",
|
| 715 |
+
"loaded_stats = dict(generation_stats)\n",
|
| 716 |
+
"\n",
|
| 717 |
+
"generation_sanity_df = pd.concat([base_generation_sanity_df, loaded_generation_sanity_df], ignore_index=True)\n",
|
| 718 |
+
"print(\"base_generation_stats\", base_stats)\n",
|
| 719 |
+
"print(\"loaded_generation_stats\", loaded_stats)\n",
|
| 720 |
+
"if loaded_stats[\"fallbacks\"] > 0:\n",
|
| 721 |
+
" print(\"WARNING: loaded fine-tuned model produced malformed JSON and used fallback.\")\n",
|
| 722 |
+
"\n",
|
| 723 |
+
"heuristic_eval = await evaluate_policy(heuristic_policy, \"heuristic\")\n",
|
| 724 |
+
"active_model = loaded_model_for_eval\n",
|
| 725 |
+
"grpo_eval = await evaluate_policy(safe_model_action, \"grpo_loaded\")\n",
|
| 726 |
+
"eval_rows = heuristic_eval + base_model_eval + grpo_eval\n",
|
| 727 |
+
"eval_df = pd.DataFrame(eval_rows)\n",
|
| 728 |
+
"eval_df"
|
| 729 |
+
]
|
| 730 |
+
},
|
| 731 |
+
{
|
| 732 |
+
"cell_type": "markdown",
|
| 733 |
+
"id": "644fd566",
|
| 734 |
+
"metadata": {},
|
| 735 |
+
"source": [
|
| 736 |
+
"## Performance Comparison\n",
|
| 737 |
+
"\n",
|
| 738 |
+
"Compare heuristic rollout behavior against the trained GRPO policy on the same scenarios and seeds."
|
| 739 |
+
]
|
| 740 |
+
},
|
| 741 |
+
{
|
| 742 |
+
"cell_type": "code",
|
| 743 |
+
"execution_count": null,
|
| 744 |
+
"id": "0162e4ad",
|
| 745 |
+
"metadata": {},
|
| 746 |
+
"outputs": [],
|
| 747 |
+
"source": [
|
| 748 |
+
"def plot_policy_comparison(eval_df, title: str = \"Base vs GRPO loaded-model comparison\"):\n",
|
| 749 |
+
" if eval_df is None or eval_df.empty or \"policy\" not in eval_df.columns:\n",
|
| 750 |
+
" print(\"eval_df is empty because loaded-model generation used fallback or evaluation was skipped.\")\n",
|
| 751 |
+
" if \"per_task_inference_df\" in globals() and not per_task_inference_df.empty:\n",
|
| 752 |
+
" print(\"Plotting per_task_inference_df instead. This is loaded-model rollout only, not heuristic-vs-model comparison.\")\n",
|
| 753 |
+
" display(per_task_inference_df)\n",
|
| 754 |
+
" ax = per_task_inference_df.set_index(\"scenario_id\")[[\"total_reward\", \"bookings\", \"violations\", \"fallbacks\"]].plot(\n",
|
| 755 |
+
" kind=\"bar\",\n",
|
| 756 |
+
" subplots=True,\n",
|
| 757 |
+
" layout=(2, 2),\n",
|
| 758 |
+
" figsize=(10, 7),\n",
|
| 759 |
+
" legend=False,\n",
|
| 760 |
+
" title=\"GRPO loaded-model per-task inference\",\n",
|
| 761 |
+
" )\n",
|
| 762 |
+
" for axis in ax.ravel():\n",
|
| 763 |
+
" axis.grid(axis=\"y\", alpha=0.3)\n",
|
| 764 |
+
" axis.set_xlabel(\"\")\n",
|
| 765 |
+
" plt.tight_layout()\n",
|
| 766 |
+
" plt.show()\n",
|
| 767 |
+
" return pd.DataFrame()\n",
|
| 768 |
+
"\n",
|
| 769 |
+
" summary = (\n",
|
| 770 |
+
" eval_df.groupby(\"policy\", as_index=True)\n",
|
| 771 |
+
" .agg(\n",
|
| 772 |
+
" avg_reward=(\"total_reward\", \"mean\"),\n",
|
| 773 |
+
" completion_rate=(\"done\", \"mean\"),\n",
|
| 774 |
+
" avg_bookings=(\"bookings\", \"mean\"),\n",
|
| 775 |
+
" avg_violations=(\"violations\", \"mean\"),\n",
|
| 776 |
+
" avg_steps=(\"steps\", \"mean\"),\n",
|
| 777 |
+
" avg_fallbacks=(\"fallbacks\", \"mean\") if \"fallbacks\" in eval_df.columns else (\"steps\", \"size\"),\n",
|
| 778 |
+
" )\n",
|
| 779 |
+
" .sort_index()\n",
|
| 780 |
+
" )\n",
|
| 781 |
+
" plot_cols = [\"avg_reward\", \"completion_rate\", \"avg_bookings\", \"avg_violations\"]\n",
|
| 782 |
+
" if \"avg_fallbacks\" in summary.columns:\n",
|
| 783 |
+
" plot_cols.append(\"avg_fallbacks\")\n",
|
| 784 |
+
" axes = summary[plot_cols].plot(\n",
|
| 785 |
+
" kind=\"bar\",\n",
|
| 786 |
+
" subplots=True,\n",
|
| 787 |
+
" layout=(3, 2),\n",
|
| 788 |
+
" figsize=(10, 9),\n",
|
| 789 |
+
" legend=False,\n",
|
| 790 |
+
" title=title,\n",
|
| 791 |
+
" )\n",
|
| 792 |
+
" for ax in axes.ravel():\n",
|
| 793 |
+
" ax.grid(axis=\"y\", alpha=0.3)\n",
|
| 794 |
+
" ax.set_xlabel(\"\")\n",
|
| 795 |
+
" plt.tight_layout()\n",
|
| 796 |
+
" plt.show()\n",
|
| 797 |
+
" return summary\n",
|
| 798 |
+
"\n",
|
| 799 |
+
"comparison_summary = plot_policy_comparison(eval_df)\n",
|
| 800 |
+
"comparison_summary"
|
| 801 |
+
]
|
| 802 |
+
},
|
| 803 |
+
{
|
| 804 |
+
"cell_type": "code",
|
| 805 |
+
"execution_count": null,
|
| 806 |
+
"id": "ee2e4887",
|
| 807 |
+
"metadata": {},
|
| 808 |
+
"outputs": [],
|
| 809 |
+
"source": [
|
| 810 |
+
"# Optional Hub upload after training.\n",
|
| 811 |
+
"# from huggingface_hub import notebook_login\n",
|
| 812 |
+
"# notebook_login()\n",
|
| 813 |
+
"# trainer.push_to_hub(\"flatmate-rl-grpo-policy\")"
|
| 814 |
+
]
|
| 815 |
+
}
|
| 816 |
+
],
|
| 817 |
+
"metadata": {
|
| 818 |
+
"kernelspec": {
|
| 819 |
+
"display_name": "Python 3",
|
| 820 |
+
"language": "python",
|
| 821 |
+
"name": "python3"
|
| 822 |
+
},
|
| 823 |
+
"language_info": {
|
| 824 |
+
"codemirror_mode": {
|
| 825 |
+
"name": "ipython",
|
| 826 |
+
"version": 3
|
| 827 |
+
},
|
| 828 |
+
"file_extension": ".py",
|
| 829 |
+
"mimetype": "text/x-python",
|
| 830 |
+
"name": "python",
|
| 831 |
+
"nbconvert_exporter": "python",
|
| 832 |
+
"pygments_lexer": "ipython3",
|
| 833 |
+
"version": "3.11"
|
| 834 |
+
}
|
| 835 |
+
},
|
| 836 |
+
"nbformat": 4,
|
| 837 |
+
"nbformat_minor": 5
|
| 838 |
+
}
|
train_flatmate_rl_trl.ipynb
ADDED
|
@@ -0,0 +1,777 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 7 |
+
"source": [
|
| 8 |
+
"# Train a Flatmate RL Action Policy with TRL\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"This notebook connects to the Hugging Face Space endpoint, collects rollout examples over OpenEnv websocket sessions, and fine-tunes a small causal language model to emit Flatmate RL JSON actions. The training path uses TRL `SFTTrainer`, which is the most stable starting point for this mixed natural-language plus structured-tool action space.\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"Endpoint used here: `https://huggingface.co/spaces/kushalExplores/flatmate_rl`."
|
| 13 |
+
]
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"cell_type": "code",
|
| 17 |
+
"execution_count": null,
|
| 18 |
+
"id": "54f0ddc0",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"outputs": [],
|
| 21 |
+
"source": [
|
| 22 |
+
"# Install notebook dependencies. Restart the kernel after this cell if Colab/Jupyter asks you to.\n",
|
| 23 |
+
"%pip install -q \"trl>=0.23.0\" \"transformers>=4.46.0\" accelerate datasets peft websockets huggingface_hub matplotlib pandas"
|
| 24 |
+
]
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"cell_type": "code",
|
| 28 |
+
"execution_count": null,
|
| 29 |
+
"id": "a6a37c34",
|
| 30 |
+
"metadata": {},
|
| 31 |
+
"outputs": [],
|
| 32 |
+
"source": [
|
| 33 |
+
"from __future__ import annotations\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"import asyncio\n",
|
| 36 |
+
"import json\n",
|
| 37 |
+
"import random\n",
|
| 38 |
+
"from dataclasses import dataclass\n",
|
| 39 |
+
"from pathlib import Path\n",
|
| 40 |
+
"from typing import Any\n",
|
| 41 |
+
"from urllib.parse import urlparse\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"import websockets\n",
|
| 44 |
+
"from datasets import Dataset\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"SPACE_HTTP_URL = \"https://kushalexplores-flatmate-rl.hf.space\"\n",
|
| 47 |
+
"SCENARIOS = [\n",
|
| 48 |
+
" \"task_visit_single\",\n",
|
| 49 |
+
" \"task_visit_single_hidden_flex\",\n",
|
| 50 |
+
" \"task_visit_multi\",\n",
|
| 51 |
+
" \"task_visit_single_seller_followup\",\n",
|
| 52 |
+
"]\n",
|
| 53 |
+
"\n",
|
| 54 |
+
"def ws_url_from_http(base_url: str) -> str:\n",
|
| 55 |
+
" parsed = urlparse(base_url.rstrip(\"/\"))\n",
|
| 56 |
+
" scheme = \"wss\" if parsed.scheme == \"https\" else \"ws\"\n",
|
| 57 |
+
" return f\"{scheme}://{parsed.netloc}/ws\"\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"SPACE_WS_URL = ws_url_from_http(SPACE_HTTP_URL)\n",
|
| 60 |
+
"SPACE_WS_URL"
|
| 61 |
+
]
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "markdown",
|
| 65 |
+
"id": "3e10f23e",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"## Endpoint Client\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"OpenEnv's plain HTTP `/reset` and `/step` endpoints are stateless. Use `/ws` for multi-step episodes because the websocket session keeps one environment instance alive across reset and step calls."
|
| 71 |
+
]
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"execution_count": null,
|
| 76 |
+
"id": "f958cca7",
|
| 77 |
+
"metadata": {},
|
| 78 |
+
"outputs": [],
|
| 79 |
+
"source": [
|
| 80 |
+
"class FlatmateEndpoint:\n",
|
| 81 |
+
" def __init__(self, ws_url: str = SPACE_WS_URL, timeout_s: float = 120.0):\n",
|
| 82 |
+
" self.ws_url = ws_url\n",
|
| 83 |
+
" self.timeout_s = timeout_s\n",
|
| 84 |
+
"\n",
|
| 85 |
+
" async def __aenter__(self):\n",
|
| 86 |
+
" self.ws = await websockets.connect(self.ws_url, open_timeout=self.timeout_s, ping_timeout=self.timeout_s)\n",
|
| 87 |
+
" return self\n",
|
| 88 |
+
"\n",
|
| 89 |
+
" async def __aexit__(self, exc_type, exc, tb):\n",
|
| 90 |
+
" try:\n",
|
| 91 |
+
" await self.ws.send(json.dumps({\"type\": \"close\"}))\n",
|
| 92 |
+
" finally:\n",
|
| 93 |
+
" await self.ws.close()\n",
|
| 94 |
+
"\n",
|
| 95 |
+
" async def _send(self, payload: dict[str, Any]) -> dict[str, Any]:\n",
|
| 96 |
+
" await self.ws.send(json.dumps(payload))\n",
|
| 97 |
+
" raw = await asyncio.wait_for(self.ws.recv(), timeout=self.timeout_s)\n",
|
| 98 |
+
" message = json.loads(raw)\n",
|
| 99 |
+
" if message.get(\"type\") == \"error\":\n",
|
| 100 |
+
" raise RuntimeError(message.get(\"data\", message))\n",
|
| 101 |
+
" data = message[\"data\"]\n",
|
| 102 |
+
" obs = data.get(\"observation\", {})\n",
|
| 103 |
+
" obs[\"reward\"] = data.get(\"reward\")\n",
|
| 104 |
+
" obs[\"done\"] = data.get(\"done\", False)\n",
|
| 105 |
+
" return obs\n",
|
| 106 |
+
"\n",
|
| 107 |
+
" async def reset(self, scenario_id: str, seed: int | None = None) -> dict[str, Any]:\n",
|
| 108 |
+
" data: dict[str, Any] = {\"scenario_id\": scenario_id}\n",
|
| 109 |
+
" if seed is not None:\n",
|
| 110 |
+
" data[\"seed\"] = seed\n",
|
| 111 |
+
" return await self._send({\"type\": \"reset\", \"data\": data})\n",
|
| 112 |
+
"\n",
|
| 113 |
+
" async def step(self, action: dict[str, Any]) -> dict[str, Any]:\n",
|
| 114 |
+
" return await self._send({\"type\": \"step\", \"data\": action})\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"async def smoke_test_endpoint():\n",
|
| 117 |
+
" async with FlatmateEndpoint() as env:\n",
|
| 118 |
+
" obs = await env.reset(\"task_visit_single\", seed=1)\n",
|
| 119 |
+
" print(obs[\"scenario_id\"], obs[\"status\"])\n",
|
| 120 |
+
" print(obs.get(\"last_user_message\") or obs.get(\"current_user_request\"))\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"await smoke_test_endpoint()"
|
| 123 |
+
]
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"cell_type": "markdown",
|
| 127 |
+
"id": "fe2ad079",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"source": [
|
| 130 |
+
"## Rollout Policy for Data Collection\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"This heuristic is intentionally simple. It produces valid-looking action examples from endpoint observations; after SFT, replace it with model generation and keep the same evaluator."
|
| 133 |
+
]
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"id": "611b1ac4",
|
| 139 |
+
"metadata": {},
|
| 140 |
+
"outputs": [],
|
| 141 |
+
"source": [
|
| 142 |
+
"def tool_names(obs: dict[str, Any]) -> list[str]:\n",
|
| 143 |
+
" return [str(t.get(\"tool\", t.get(\"tool_name\", \"\"))) for t in obs.get(\"tool_trace\", [])]\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"def action_policy(obs: dict[str, Any]) -> dict[str, Any] | None:\n",
|
| 146 |
+
" tools = tool_names(obs)\n",
|
| 147 |
+
" phase = obs.get(\"phase\", \"buyer\")\n",
|
| 148 |
+
" remaining = set(obs.get(\"remaining_required_fields\", []))\n",
|
| 149 |
+
" scenario_id = obs.get(\"scenario_id\", \"task_visit_single\")\n",
|
| 150 |
+
"\n",
|
| 151 |
+
" if phase == \"seller\" and not obs.get(\"seller_profile_stored\"):\n",
|
| 152 |
+
" if remaining:\n",
|
| 153 |
+
" return {\"action_type\": \"assistant_message\", \"assistant_message\": \"Please share the household dietary setup, who the flat is for, and available visit time slots.\"}\n",
|
| 154 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"store_seller_details\", \"tool_arguments\": {}}\n",
|
| 155 |
+
"\n",
|
| 156 |
+
" if not obs.get(\"buyer_profile_stored\"):\n",
|
| 157 |
+
" if \"diet\" in remaining and \"visit_availability\" in remaining:\n",
|
| 158 |
+
" return {\"action_type\": \"assistant_message\", \"assistant_message\": \"Please share your dietary preference and visit availability.\"}\n",
|
| 159 |
+
" if \"diet\" in remaining:\n",
|
| 160 |
+
" return {\"action_type\": \"assistant_message\", \"assistant_message\": \"Please share your dietary preference.\"}\n",
|
| 161 |
+
" if \"visit_availability\" in remaining:\n",
|
| 162 |
+
" return {\"action_type\": \"assistant_message\", \"assistant_message\": \"Please share your visit availability.\"}\n",
|
| 163 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"store_user_details\", \"tool_arguments\": {}}\n",
|
| 164 |
+
"\n",
|
| 165 |
+
" if \"search_posts\" not in tools:\n",
|
| 166 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"search_posts\", \"tool_arguments\": {}}\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" post_ids = [\"post_031\", \"post_052\"] if scenario_id == \"task_visit_multi\" else [\"post_031\"]\n",
|
| 169 |
+
" if \"match_location_preference\" not in tools:\n",
|
| 170 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"match_location_preference\", \"tool_arguments\": {\"post_ids\": post_ids}}\n",
|
| 171 |
+
" if \"get_commute_time\" not in tools:\n",
|
| 172 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"get_commute_time\", \"tool_arguments\": {\"post_ids\": post_ids}}\n",
|
| 173 |
+
" if \"check_calendar_slots\" not in tools:\n",
|
| 174 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"check_calendar_slots\", \"tool_arguments\": {\"post_ids\": post_ids}}\n",
|
| 175 |
+
" if \"shortlist\" not in tools:\n",
|
| 176 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"shortlist\", \"tool_arguments\": {\"post_ids\": post_ids}}\n",
|
| 177 |
+
" if \"contact_poster\" not in tools:\n",
|
| 178 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"contact_poster\", \"tool_arguments\": {\"post_id\": post_ids[0], \"time_text\": \"tomorrow 7pm\"}}\n",
|
| 179 |
+
" if \"book_viewing\" not in tools:\n",
|
| 180 |
+
" return {\"action_type\": \"tool_call\", \"tool_name\": \"book_viewing\", \"tool_arguments\": {\"post_id\": post_ids[0], \"time_text\": \"tomorrow 7pm\"}}\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" return None\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"def flatten_observation(obs: dict[str, Any]) -> str:\n",
|
| 185 |
+
" visible = {\n",
|
| 186 |
+
" \"scenario_id\": obs.get(\"scenario_id\"),\n",
|
| 187 |
+
" \"phase\": obs.get(\"phase\"),\n",
|
| 188 |
+
" \"status\": obs.get(\"status\"),\n",
|
| 189 |
+
" \"last_user_message\": obs.get(\"last_user_message\"),\n",
|
| 190 |
+
" \"current_user_request\": obs.get(\"current_user_request\"),\n",
|
| 191 |
+
" \"available_tools\": obs.get(\"available_tools\", []),\n",
|
| 192 |
+
" \"remaining_required_fields\": obs.get(\"remaining_required_fields\", []),\n",
|
| 193 |
+
" \"prerequisites_satisfied\": obs.get(\"prerequisites_satisfied\", {}),\n",
|
| 194 |
+
" \"recent_tool_calls\": obs.get(\"recent_tool_calls\", []),\n",
|
| 195 |
+
" \"last_tool_result\": obs.get(\"last_tool_result\", {}),\n",
|
| 196 |
+
" \"violations\": obs.get(\"violations\", []),\n",
|
| 197 |
+
" \"booked_visits\": obs.get(\"booked_visits\", []),\n",
|
| 198 |
+
" \"feedback_summary\": obs.get(\"feedback_summary\", \"\"),\n",
|
| 199 |
+
" }\n",
|
| 200 |
+
" return json.dumps(visible, ensure_ascii=False, sort_keys=True)\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"def make_training_text(obs: dict[str, Any], action: dict[str, Any]) -> str:\n",
|
| 203 |
+
" return (\n",
|
| 204 |
+
" \"You are a broker policy for the Flatmate RL environment. \"\n",
|
| 205 |
+
" \"Given an observation, return exactly one JSON action.\\n\\n\"\n",
|
| 206 |
+
" f\"Observation:\\n{flatten_observation(obs)}\\n\\n\"\n",
|
| 207 |
+
" f\"Action:\\n{json.dumps(action, ensure_ascii=False, sort_keys=True)}\"\n",
|
| 208 |
+
" )"
|
| 209 |
+
]
|
| 210 |
+
},
|
| 211 |
+
{
|
| 212 |
+
"cell_type": "code",
|
| 213 |
+
"execution_count": null,
|
| 214 |
+
"id": "7b22fa13",
|
| 215 |
+
"metadata": {},
|
| 216 |
+
"outputs": [],
|
| 217 |
+
"source": [
|
| 218 |
+
"@dataclass\n",
|
| 219 |
+
"class RolloutConfig:\n",
|
| 220 |
+
" train_episodes_per_task: int = 4\n",
|
| 221 |
+
" test_episodes_per_task: int = 2\n",
|
| 222 |
+
" max_steps: int = 20\n",
|
| 223 |
+
" seed: int = 7\n",
|
| 224 |
+
"\n",
|
| 225 |
+
"async def collect_one_episode(\n",
|
| 226 |
+
" scenario_id: str,\n",
|
| 227 |
+
" episode_id: str,\n",
|
| 228 |
+
" episode_idx: int,\n",
|
| 229 |
+
" split: str,\n",
|
| 230 |
+
" seed: int,\n",
|
| 231 |
+
" max_steps: int,\n",
|
| 232 |
+
") -> list[dict[str, Any]]:\n",
|
| 233 |
+
" rows: list[dict[str, Any]] = []\n",
|
| 234 |
+
" async with FlatmateEndpoint() as env:\n",
|
| 235 |
+
" obs = await env.reset(scenario_id, seed=seed)\n",
|
| 236 |
+
" total_reward = 0.0\n",
|
| 237 |
+
" for step_idx in range(max_steps):\n",
|
| 238 |
+
" action = action_policy(obs)\n",
|
| 239 |
+
" if action is None or obs.get(\"done\"):\n",
|
| 240 |
+
" break\n",
|
| 241 |
+
" rows.append({\n",
|
| 242 |
+
" \"text\": make_training_text(obs, action),\n",
|
| 243 |
+
" \"episode_id\": episode_id,\n",
|
| 244 |
+
" \"episode_idx\": episode_idx,\n",
|
| 245 |
+
" \"split\": split,\n",
|
| 246 |
+
" \"scenario_id\": scenario_id,\n",
|
| 247 |
+
" \"seed\": seed,\n",
|
| 248 |
+
" \"step\": step_idx,\n",
|
| 249 |
+
" \"action\": json.dumps(action, sort_keys=True),\n",
|
| 250 |
+
" })\n",
|
| 251 |
+
" obs = await env.step(action)\n",
|
| 252 |
+
" total_reward += float(obs.get(\"reward\") or obs.get(\"step_reward\") or 0.0)\n",
|
| 253 |
+
" if obs.get(\"done\"):\n",
|
| 254 |
+
" break\n",
|
| 255 |
+
" print(f\"split={split:5s} episode={episode_id} scenario={scenario_id} rows={len(rows)} total_reward={total_reward:.2f}\")\n",
|
| 256 |
+
" return rows\n",
|
| 257 |
+
"\n",
|
| 258 |
+
"async def collect_balanced_rollouts(config: RolloutConfig = RolloutConfig()) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:\n",
|
| 259 |
+
" train_rows: list[dict[str, Any]] = []\n",
|
| 260 |
+
" test_rows: list[dict[str, Any]] = []\n",
|
| 261 |
+
" episode_idx = 0\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" for scenario_idx, scenario_id in enumerate(SCENARIOS):\n",
|
| 264 |
+
" for task_episode_idx in range(config.train_episodes_per_task):\n",
|
| 265 |
+
" seed = config.seed + scenario_idx * 100 + task_episode_idx\n",
|
| 266 |
+
" episode_id = f\"train_{scenario_id}_{task_episode_idx:03d}\"\n",
|
| 267 |
+
" train_rows.extend(await collect_one_episode(scenario_id, episode_id, episode_idx, \"train\", seed, config.max_steps))\n",
|
| 268 |
+
" episode_idx += 1\n",
|
| 269 |
+
"\n",
|
| 270 |
+
" for task_episode_idx in range(config.test_episodes_per_task):\n",
|
| 271 |
+
" seed = 900 + config.seed + scenario_idx * 100 + task_episode_idx\n",
|
| 272 |
+
" episode_id = f\"test_{scenario_id}_{task_episode_idx:03d}\"\n",
|
| 273 |
+
" test_rows.extend(await collect_one_episode(scenario_id, episode_id, episode_idx, \"test\", seed, config.max_steps))\n",
|
| 274 |
+
" episode_idx += 1\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" return train_rows, test_rows\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"print(\"Note: seeded resets create value variants while preserving the same episode flow. Upload the updated Space before using this against the hosted endpoint.\")\n",
|
| 279 |
+
"train_rows, test_rows = await collect_balanced_rollouts(\n",
|
| 280 |
+
" RolloutConfig(train_episodes_per_task=4, test_episodes_per_task=2, max_steps=20, seed=7)\n",
|
| 281 |
+
")\n",
|
| 282 |
+
"rows = train_rows + test_rows\n",
|
| 283 |
+
"dataset = Dataset.from_list(rows)\n",
|
| 284 |
+
"train_dataset = Dataset.from_list(train_rows)\n",
|
| 285 |
+
"test_dataset = Dataset.from_list(test_rows)\n",
|
| 286 |
+
"\n",
|
| 287 |
+
"print({\n",
|
| 288 |
+
" \"train_rows\": len(train_dataset),\n",
|
| 289 |
+
" \"test_rows\": len(test_dataset),\n",
|
| 290 |
+
" \"total_rows\": len(dataset),\n",
|
| 291 |
+
" \"train_episodes\": len(set(train_dataset[\"episode_id\"])),\n",
|
| 292 |
+
" \"test_episodes\": len(set(test_dataset[\"episode_id\"])),\n",
|
| 293 |
+
"})\n",
|
| 294 |
+
"print(\"train scenarios\", sorted(set(train_dataset[\"scenario_id\"])))\n",
|
| 295 |
+
"print(\"test scenarios\", sorted(set(test_dataset[\"scenario_id\"])))\n",
|
| 296 |
+
"print(\"train episodes by scenario\")\n",
|
| 297 |
+
"display(pd.DataFrame(train_rows).groupby(\"scenario_id\")[\"episode_id\"].nunique().rename(\"episodes\"))\n",
|
| 298 |
+
"print(\"test episodes by scenario\")\n",
|
| 299 |
+
"display(pd.DataFrame(test_rows).groupby(\"scenario_id\")[\"episode_id\"].nunique().rename(\"episodes\"))\n",
|
| 300 |
+
"{\"train\": train_dataset, \"test\": test_dataset}"
|
| 301 |
+
]
|
| 302 |
+
},
|
| 303 |
+
{
|
| 304 |
+
"cell_type": "code",
|
| 305 |
+
"execution_count": null,
|
| 306 |
+
"id": "665b46fa",
|
| 307 |
+
"metadata": {},
|
| 308 |
+
"outputs": [],
|
| 309 |
+
"source": [
|
| 310 |
+
"from peft import LoraConfig\n",
|
| 311 |
+
"from transformers import AutoModelForCausalLM, AutoTokenizer\n",
|
| 312 |
+
"from trl import SFTConfig, SFTTrainer\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"MODEL_NAME = \"Qwen/Qwen2.5-0.5B-Instruct\"\n",
|
| 315 |
+
"OUTPUT_DIR = \"flatmate-rl-action-policy\"\n",
|
| 316 |
+
"\n",
|
| 317 |
+
"tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)\n",
|
| 318 |
+
"if tokenizer.pad_token is None:\n",
|
| 319 |
+
" tokenizer.pad_token = tokenizer.eos_token\n",
|
| 320 |
+
"\n",
|
| 321 |
+
"model = AutoModelForCausalLM.from_pretrained(\n",
|
| 322 |
+
" MODEL_NAME,\n",
|
| 323 |
+
" trust_remote_code=True,\n",
|
| 324 |
+
" device_map=\"auto\",\n",
|
| 325 |
+
")\n",
|
| 326 |
+
"model.config.use_cache = False\n",
|
| 327 |
+
"\n",
|
| 328 |
+
"peft_config = LoraConfig(\n",
|
| 329 |
+
" r=16,\n",
|
| 330 |
+
" lora_alpha=32,\n",
|
| 331 |
+
" lora_dropout=0.05,\n",
|
| 332 |
+
" bias=\"none\",\n",
|
| 333 |
+
" task_type=\"CAUSAL_LM\",\n",
|
| 334 |
+
" target_modules=[\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\", \"gate_proj\", \"up_proj\", \"down_proj\"],\n",
|
| 335 |
+
")\n",
|
| 336 |
+
"\n",
|
| 337 |
+
"training_args = SFTConfig(\n",
|
| 338 |
+
" output_dir=OUTPUT_DIR,\n",
|
| 339 |
+
" dataset_text_field=\"text\",\n",
|
| 340 |
+
" max_length=1536,\n",
|
| 341 |
+
" per_device_train_batch_size=1,\n",
|
| 342 |
+
" gradient_accumulation_steps=8,\n",
|
| 343 |
+
" num_train_epochs=1,\n",
|
| 344 |
+
" learning_rate=5e-5,\n",
|
| 345 |
+
" logging_steps=5,\n",
|
| 346 |
+
" save_steps=50,\n",
|
| 347 |
+
" save_total_limit=2,\n",
|
| 348 |
+
" packing=False,\n",
|
| 349 |
+
" report_to=\"none\",\n",
|
| 350 |
+
")\n",
|
| 351 |
+
"\n",
|
| 352 |
+
"trainer = SFTTrainer(\n",
|
| 353 |
+
" model=model,\n",
|
| 354 |
+
" args=training_args,\n",
|
| 355 |
+
" train_dataset=train_dataset,\n",
|
| 356 |
+
" eval_dataset=test_dataset,\n",
|
| 357 |
+
" processing_class=tokenizer,\n",
|
| 358 |
+
" peft_config=peft_config,\n",
|
| 359 |
+
")\n",
|
| 360 |
+
"\n",
|
| 361 |
+
"train_result = trainer.train()\n",
|
| 362 |
+
"test_metrics = trainer.evaluate(eval_dataset=test_dataset)\n",
|
| 363 |
+
"train_log_history = trainer.state.log_history\n",
|
| 364 |
+
"trainer.save_model(OUTPUT_DIR)\n",
|
| 365 |
+
"tokenizer.save_pretrained(OUTPUT_DIR)\n",
|
| 366 |
+
"print(\"heldout_test_metrics\", test_metrics)\n",
|
| 367 |
+
"train_result"
|
| 368 |
+
]
|
| 369 |
+
},
|
| 370 |
+
{
|
| 371 |
+
"cell_type": "markdown",
|
| 372 |
+
"id": "22d9fc14",
|
| 373 |
+
"metadata": {},
|
| 374 |
+
"source": [
|
| 375 |
+
"## Training Log\n",
|
| 376 |
+
"\n",
|
| 377 |
+
"Plot the logged training loss over optimizer steps."
|
| 378 |
+
]
|
| 379 |
+
},
|
| 380 |
+
{
|
| 381 |
+
"cell_type": "code",
|
| 382 |
+
"execution_count": null,
|
| 383 |
+
"id": "c3e44d74",
|
| 384 |
+
"metadata": {},
|
| 385 |
+
"outputs": [],
|
| 386 |
+
"source": [
|
| 387 |
+
"import json\n",
|
| 388 |
+
"from pathlib import Path\n",
|
| 389 |
+
"\n",
|
| 390 |
+
"import matplotlib.pyplot as plt\n",
|
| 391 |
+
"import pandas as pd\n",
|
| 392 |
+
"\n",
|
| 393 |
+
"log_path = Path(OUTPUT_DIR) / \"train_log_history.json\"\n",
|
| 394 |
+
"log_path.parent.mkdir(parents=True, exist_ok=True)\n",
|
| 395 |
+
"log_path.write_text(json.dumps(train_log_history, indent=2))\n",
|
| 396 |
+
"\n",
|
| 397 |
+
"def plot_training_log(log_history, title: str = \"SFT training loss\"):\n",
|
| 398 |
+
" rows = [row for row in log_history if \"loss\" in row and \"step\" in row]\n",
|
| 399 |
+
" if not rows:\n",
|
| 400 |
+
" print(\"No loss rows found in trainer.state.log_history yet.\")\n",
|
| 401 |
+
" return None\n",
|
| 402 |
+
" df = pd.DataFrame(rows)\n",
|
| 403 |
+
" ax = df.plot(x=\"step\", y=\"loss\", marker=\"o\", figsize=(7, 4), title=title)\n",
|
| 404 |
+
" ax.set_xlabel(\"optimizer step\")\n",
|
| 405 |
+
" ax.set_ylabel(\"loss\")\n",
|
| 406 |
+
" ax.grid(True, alpha=0.3)\n",
|
| 407 |
+
" plt.show()\n",
|
| 408 |
+
" return df\n",
|
| 409 |
+
"\n",
|
| 410 |
+
"train_log_df = plot_training_log(train_log_history)\n",
|
| 411 |
+
"train_log_df.tail() if train_log_df is not None else None"
|
| 412 |
+
]
|
| 413 |
+
},
|
| 414 |
+
{
|
| 415 |
+
"cell_type": "code",
|
| 416 |
+
"execution_count": null,
|
| 417 |
+
"id": "539548f7",
|
| 418 |
+
"metadata": {},
|
| 419 |
+
"outputs": [],
|
| 420 |
+
"source": [
|
| 421 |
+
"import torch\n",
|
| 422 |
+
"from peft import AutoPeftModelForCausalLM\n",
|
| 423 |
+
"\n",
|
| 424 |
+
"# Load both the base model and the saved fine-tuned adapter from disk for comparison.\n",
|
| 425 |
+
"try:\n",
|
| 426 |
+
" del model\n",
|
| 427 |
+
"except NameError:\n",
|
| 428 |
+
" pass\n",
|
| 429 |
+
"\n",
|
| 430 |
+
"base_model_for_eval = AutoModelForCausalLM.from_pretrained(\n",
|
| 431 |
+
" MODEL_NAME,\n",
|
| 432 |
+
" trust_remote_code=True,\n",
|
| 433 |
+
" device_map=\"auto\",\n",
|
| 434 |
+
")\n",
|
| 435 |
+
"base_model_for_eval.eval()\n",
|
| 436 |
+
"base_model_for_eval.config.use_cache = False\n",
|
| 437 |
+
"\n",
|
| 438 |
+
"loaded_model_for_eval = AutoPeftModelForCausalLM.from_pretrained(OUTPUT_DIR, device_map=\"auto\")\n",
|
| 439 |
+
"loaded_model_for_eval.eval()\n",
|
| 440 |
+
"loaded_model_for_eval.config.use_cache = False\n",
|
| 441 |
+
"active_model = loaded_model_for_eval\n",
|
| 442 |
+
"print(f\"Loaded base model from {MODEL_NAME}\")\n",
|
| 443 |
+
"print(f\"Loaded saved SFT model from {OUTPUT_DIR}\")\n",
|
| 444 |
+
"\n",
|
| 445 |
+
"TEST_SEEDS = (901, 902)\n",
|
| 446 |
+
"\n",
|
| 447 |
+
"\n",
|
| 448 |
+
"def prompt_from_observation(obs: dict[str, Any]) -> str:\n",
|
| 449 |
+
" return (\n",
|
| 450 |
+
" \"You are a broker policy for the Flatmate RL environment. \"\n",
|
| 451 |
+
" \"Given an observation, return exactly one JSON action.\\n\\n\"\n",
|
| 452 |
+
" f\"Observation:\\n{flatten_observation(obs)}\\n\\nAction:\\n\"\n",
|
| 453 |
+
" )\n",
|
| 454 |
+
"\n",
|
| 455 |
+
"\n",
|
| 456 |
+
"def _first_balanced_json(text: str) -> str:\n",
|
| 457 |
+
" start = text.find(\"{\")\n",
|
| 458 |
+
" if start == -1:\n",
|
| 459 |
+
" raise ValueError(f\"No JSON object found in generation: {text!r}\")\n",
|
| 460 |
+
" depth = 0\n",
|
| 461 |
+
" in_string = False\n",
|
| 462 |
+
" escape = False\n",
|
| 463 |
+
" for index, char in enumerate(text[start:], start=start):\n",
|
| 464 |
+
" if escape:\n",
|
| 465 |
+
" escape = False\n",
|
| 466 |
+
" continue\n",
|
| 467 |
+
" if char == \"\\\\\" and in_string:\n",
|
| 468 |
+
" escape = True\n",
|
| 469 |
+
" continue\n",
|
| 470 |
+
" if char == '\\\"':\n",
|
| 471 |
+
" in_string = not in_string\n",
|
| 472 |
+
" continue\n",
|
| 473 |
+
" if in_string:\n",
|
| 474 |
+
" continue\n",
|
| 475 |
+
" if char == \"{\":\n",
|
| 476 |
+
" depth += 1\n",
|
| 477 |
+
" elif char == \"}\":\n",
|
| 478 |
+
" depth -= 1\n",
|
| 479 |
+
" if depth == 0:\n",
|
| 480 |
+
" return text[start : index + 1]\n",
|
| 481 |
+
" raise ValueError(f\"Unterminated JSON object in generation: {text!r}\")\n",
|
| 482 |
+
"\n",
|
| 483 |
+
"\n",
|
| 484 |
+
"def normalize_action(action: dict[str, Any]) -> dict[str, Any]:\n",
|
| 485 |
+
" if action.get(\"action_type\") == \"assistant_message\" and str(action.get(\"assistant_message\", \"\")).strip():\n",
|
| 486 |
+
" return {\n",
|
| 487 |
+
" \"action_type\": \"assistant_message\",\n",
|
| 488 |
+
" \"assistant_message\": str(action[\"assistant_message\"]),\n",
|
| 489 |
+
" }\n",
|
| 490 |
+
" if action.get(\"action_type\") == \"tool_call\" and str(action.get(\"tool_name\", \"\")).strip():\n",
|
| 491 |
+
" tool_arguments = action.get(\"tool_arguments\", {})\n",
|
| 492 |
+
" return {\n",
|
| 493 |
+
" \"action_type\": \"tool_call\",\n",
|
| 494 |
+
" \"tool_name\": str(action[\"tool_name\"]),\n",
|
| 495 |
+
" \"tool_arguments\": tool_arguments if isinstance(tool_arguments, dict) else {},\n",
|
| 496 |
+
" }\n",
|
| 497 |
+
" raise ValueError(f\"Invalid action shape: {action!r}\")\n",
|
| 498 |
+
"\n",
|
| 499 |
+
"\n",
|
| 500 |
+
"def parse_action(text: str) -> dict[str, Any]:\n",
|
| 501 |
+
" return normalize_action(json.loads(_first_balanced_json(text)))\n",
|
| 502 |
+
"\n",
|
| 503 |
+
"\n",
|
| 504 |
+
"def heuristic_policy(obs: dict[str, Any]) -> dict[str, Any]:\n",
|
| 505 |
+
" action = action_policy(obs)\n",
|
| 506 |
+
" if action is None:\n",
|
| 507 |
+
" return {\"action_type\": \"assistant_message\", \"assistant_message\": \"Could you confirm the details needed for scheduling?\"}\n",
|
| 508 |
+
" return action\n",
|
| 509 |
+
"\n",
|
| 510 |
+
"\n",
|
| 511 |
+
"def raw_generate_action_text(obs: dict[str, Any]) -> str:\n",
|
| 512 |
+
" prompt = prompt_from_observation(obs) + \"{\"\n",
|
| 513 |
+
" inputs = tokenizer(prompt, return_tensors=\"pt\").to(active_model.device)\n",
|
| 514 |
+
" active_model.generation_config.do_sample = False\n",
|
| 515 |
+
" active_model.generation_config.temperature = None\n",
|
| 516 |
+
" active_model.generation_config.top_p = None\n",
|
| 517 |
+
" active_model.generation_config.top_k = None\n",
|
| 518 |
+
" with torch.no_grad():\n",
|
| 519 |
+
" output = active_model.generate(\n",
|
| 520 |
+
" **inputs,\n",
|
| 521 |
+
" max_new_tokens=80,\n",
|
| 522 |
+
" do_sample=False,\n",
|
| 523 |
+
" repetition_penalty=1.15,\n",
|
| 524 |
+
" no_repeat_ngram_size=3,\n",
|
| 525 |
+
" eos_token_id=tokenizer.eos_token_id,\n",
|
| 526 |
+
" pad_token_id=tokenizer.eos_token_id,\n",
|
| 527 |
+
" )\n",
|
| 528 |
+
" return \"{\" + tokenizer.decode(output[0][inputs[\"input_ids\"].shape[-1]:], skip_special_tokens=True)\n",
|
| 529 |
+
"\n",
|
| 530 |
+
"\n",
|
| 531 |
+
"def model_action_or_error(obs: dict[str, Any]) -> tuple[dict[str, Any] | None, str, str]:\n",
|
| 532 |
+
" raw = raw_generate_action_text(obs)\n",
|
| 533 |
+
" try:\n",
|
| 534 |
+
" return parse_action(raw), raw, \"\"\n",
|
| 535 |
+
" except Exception as exc:\n",
|
| 536 |
+
" return None, raw, str(exc)\n",
|
| 537 |
+
"\n",
|
| 538 |
+
"\n",
|
| 539 |
+
"async def sanity_check_generations(model_label: str, limit: int = 4):\n",
|
| 540 |
+
" rows = []\n",
|
| 541 |
+
" for scenario_id in SCENARIOS[:limit]:\n",
|
| 542 |
+
" async with FlatmateEndpoint() as env:\n",
|
| 543 |
+
" obs = await env.reset(scenario_id, seed=TEST_SEEDS[0])\n",
|
| 544 |
+
" action, raw, error = model_action_or_error(obs)\n",
|
| 545 |
+
" rows.append({\n",
|
| 546 |
+
" \"model\": model_label,\n",
|
| 547 |
+
" \"scenario_id\": scenario_id,\n",
|
| 548 |
+
" \"json_ok\": action is not None,\n",
|
| 549 |
+
" \"raw\": raw[:240],\n",
|
| 550 |
+
" \"parsed_action\": action,\n",
|
| 551 |
+
" \"error\": error,\n",
|
| 552 |
+
" })\n",
|
| 553 |
+
" return pd.DataFrame(rows)\n",
|
| 554 |
+
"\n",
|
| 555 |
+
"\n",
|
| 556 |
+
"async def evaluate_heuristic(label: str = \"heuristic\", scenarios=SCENARIOS, seeds=TEST_SEEDS, max_steps: int = 20, verbose: bool = False):\n",
|
| 557 |
+
" rows = []\n",
|
| 558 |
+
" for scenario_id in scenarios:\n",
|
| 559 |
+
" for seed in seeds:\n",
|
| 560 |
+
" async with FlatmateEndpoint() as env:\n",
|
| 561 |
+
" obs = await env.reset(scenario_id, seed=seed)\n",
|
| 562 |
+
" total_reward = 0.0\n",
|
| 563 |
+
" steps = 0\n",
|
| 564 |
+
" for step_idx in range(max_steps):\n",
|
| 565 |
+
" action = heuristic_policy(obs)\n",
|
| 566 |
+
" if verbose:\n",
|
| 567 |
+
" print(label, scenario_id, seed, step_idx, action)\n",
|
| 568 |
+
" obs = await env.step(action)\n",
|
| 569 |
+
" steps = step_idx + 1\n",
|
| 570 |
+
" total_reward += float(obs.get(\"reward\") or obs.get(\"step_reward\") or 0.0)\n",
|
| 571 |
+
" if obs.get(\"done\"):\n",
|
| 572 |
+
" break\n",
|
| 573 |
+
" rows.append({\n",
|
| 574 |
+
" \"policy\": label,\n",
|
| 575 |
+
" \"scenario_id\": scenario_id,\n",
|
| 576 |
+
" \"seed\": seed,\n",
|
| 577 |
+
" \"total_reward\": total_reward,\n",
|
| 578 |
+
" \"done\": bool(obs.get(\"done\")),\n",
|
| 579 |
+
" \"bookings\": len(obs.get(\"booked_visits\", [])),\n",
|
| 580 |
+
" \"violations\": len(obs.get(\"violations\", [])),\n",
|
| 581 |
+
" \"steps\": steps,\n",
|
| 582 |
+
" \"parse_errors\": 0,\n",
|
| 583 |
+
" })\n",
|
| 584 |
+
" return rows\n",
|
| 585 |
+
"\n",
|
| 586 |
+
"\n",
|
| 587 |
+
"async def evaluate_model_policy(label: str, scenarios=SCENARIOS, seeds=TEST_SEEDS, max_steps: int = 20, verbose: bool = False):\n",
|
| 588 |
+
" rows = []\n",
|
| 589 |
+
" for scenario_id in scenarios:\n",
|
| 590 |
+
" for seed in seeds:\n",
|
| 591 |
+
" async with FlatmateEndpoint() as env:\n",
|
| 592 |
+
" obs = await env.reset(scenario_id, seed=seed)\n",
|
| 593 |
+
" total_reward = 0.0\n",
|
| 594 |
+
" steps = 0\n",
|
| 595 |
+
" parse_errors = 0\n",
|
| 596 |
+
" last_error = \"\"\n",
|
| 597 |
+
" for step_idx in range(max_steps):\n",
|
| 598 |
+
" action, raw, error = model_action_or_error(obs)\n",
|
| 599 |
+
" if action is None:\n",
|
| 600 |
+
" parse_errors += 1\n",
|
| 601 |
+
" last_error = error\n",
|
| 602 |
+
" if verbose:\n",
|
| 603 |
+
" print(label, scenario_id, seed, f\"step={step_idx:02d}\", \"PARSE_ERROR\", raw[:220])\n",
|
| 604 |
+
" total_reward -= 1.0\n",
|
| 605 |
+
" break\n",
|
| 606 |
+
" if verbose:\n",
|
| 607 |
+
" print(label, scenario_id, seed, f\"step={step_idx:02d}\", action)\n",
|
| 608 |
+
" obs = await env.step(action)\n",
|
| 609 |
+
" steps = step_idx + 1\n",
|
| 610 |
+
" total_reward += float(obs.get(\"reward\") or obs.get(\"step_reward\") or 0.0)\n",
|
| 611 |
+
" if obs.get(\"done\"):\n",
|
| 612 |
+
" break\n",
|
| 613 |
+
" rows.append({\n",
|
| 614 |
+
" \"policy\": label,\n",
|
| 615 |
+
" \"scenario_id\": scenario_id,\n",
|
| 616 |
+
" \"seed\": seed,\n",
|
| 617 |
+
" \"total_reward\": total_reward,\n",
|
| 618 |
+
" \"done\": bool(obs.get(\"done\")),\n",
|
| 619 |
+
" \"bookings\": len(obs.get(\"booked_visits\", [])),\n",
|
| 620 |
+
" \"violations\": len(obs.get(\"violations\", [])),\n",
|
| 621 |
+
" \"steps\": steps,\n",
|
| 622 |
+
" \"parse_errors\": parse_errors,\n",
|
| 623 |
+
" \"last_error\": last_error,\n",
|
| 624 |
+
" })\n",
|
| 625 |
+
" return rows\n",
|
| 626 |
+
"\n",
|
| 627 |
+
"\n",
|
| 628 |
+
"async def run_model_inference_each_task(label: str, seed: int = TEST_SEEDS[0], max_steps: int = 20):\n",
|
| 629 |
+
" rows = []\n",
|
| 630 |
+
" for scenario_id in SCENARIOS:\n",
|
| 631 |
+
" print(f\"\\n=== {label}: {scenario_id} ===\")\n",
|
| 632 |
+
" async with FlatmateEndpoint() as env:\n",
|
| 633 |
+
" obs = await env.reset(scenario_id, seed=seed)\n",
|
| 634 |
+
" total_reward = 0.0\n",
|
| 635 |
+
" steps = 0\n",
|
| 636 |
+
" parse_errors = 0\n",
|
| 637 |
+
" for step_idx in range(max_steps):\n",
|
| 638 |
+
" action, raw, error = model_action_or_error(obs)\n",
|
| 639 |
+
" if action is None:\n",
|
| 640 |
+
" parse_errors += 1\n",
|
| 641 |
+
" print(f\"step={step_idx:02d} PARSE_ERROR={error}\")\n",
|
| 642 |
+
" print(\"raw=\", repr(raw[:300]))\n",
|
| 643 |
+
" total_reward -= 1.0\n",
|
| 644 |
+
" break\n",
|
| 645 |
+
" print(f\"step={step_idx:02d} action={action}\")\n",
|
| 646 |
+
" obs = await env.step(action)\n",
|
| 647 |
+
" steps = step_idx + 1\n",
|
| 648 |
+
" total_reward += float(obs.get(\"reward\") or obs.get(\"step_reward\") or 0.0)\n",
|
| 649 |
+
" if obs.get(\"done\"):\n",
|
| 650 |
+
" break\n",
|
| 651 |
+
" result = {\n",
|
| 652 |
+
" \"policy\": label,\n",
|
| 653 |
+
" \"scenario_id\": scenario_id,\n",
|
| 654 |
+
" \"seed\": seed,\n",
|
| 655 |
+
" \"total_reward\": total_reward,\n",
|
| 656 |
+
" \"done\": bool(obs.get(\"done\")),\n",
|
| 657 |
+
" \"bookings\": len(obs.get(\"booked_visits\", [])),\n",
|
| 658 |
+
" \"violations\": len(obs.get(\"violations\", [])),\n",
|
| 659 |
+
" \"steps\": steps,\n",
|
| 660 |
+
" \"parse_errors\": parse_errors,\n",
|
| 661 |
+
" }\n",
|
| 662 |
+
" print(\"result=\", result)\n",
|
| 663 |
+
" rows.append(result)\n",
|
| 664 |
+
" return pd.DataFrame(rows)\n",
|
| 665 |
+
"\n",
|
| 666 |
+
"\n",
|
| 667 |
+
"active_model = base_model_for_eval\n",
|
| 668 |
+
"base_generation_sanity_df = await sanity_check_generations(\"base_model\")\n",
|
| 669 |
+
"base_per_task_inference_df = await run_model_inference_each_task(\"base_model\")\n",
|
| 670 |
+
"base_model_eval = await evaluate_model_policy(\"base_model\")\n",
|
| 671 |
+
"\n",
|
| 672 |
+
"active_model = loaded_model_for_eval\n",
|
| 673 |
+
"loaded_generation_sanity_df = await sanity_check_generations(\"sft_loaded\")\n",
|
| 674 |
+
"loaded_per_task_inference_df = await run_model_inference_each_task(\"sft_loaded\")\n",
|
| 675 |
+
"loaded_eval = await evaluate_model_policy(\"sft_loaded\")\n",
|
| 676 |
+
"\n",
|
| 677 |
+
"per_task_inference_df = pd.concat([base_per_task_inference_df, loaded_per_task_inference_df], ignore_index=True)\n",
|
| 678 |
+
"generation_sanity_df = pd.concat([base_generation_sanity_df, loaded_generation_sanity_df], ignore_index=True)\n",
|
| 679 |
+
"heuristic_eval = await evaluate_heuristic(\"heuristic\")\n",
|
| 680 |
+
"\n",
|
| 681 |
+
"eval_rows = heuristic_eval + base_model_eval + loaded_eval\n",
|
| 682 |
+
"eval_df = pd.DataFrame(eval_rows)\n",
|
| 683 |
+
"display(generation_sanity_df)\n",
|
| 684 |
+
"display(per_task_inference_df)\n",
|
| 685 |
+
"eval_df"
|
| 686 |
+
]
|
| 687 |
+
},
|
| 688 |
+
{
|
| 689 |
+
"cell_type": "markdown",
|
| 690 |
+
"id": "e1e70c8f",
|
| 691 |
+
"metadata": {},
|
| 692 |
+
"source": [
|
| 693 |
+
"## Performance Comparison\n",
|
| 694 |
+
"\n",
|
| 695 |
+
"Compare heuristic rollout behavior against the trained SFT policy on the same scenarios and seeds."
|
| 696 |
+
]
|
| 697 |
+
},
|
| 698 |
+
{
|
| 699 |
+
"cell_type": "code",
|
| 700 |
+
"execution_count": null,
|
| 701 |
+
"id": "e8931930",
|
| 702 |
+
"metadata": {},
|
| 703 |
+
"outputs": [],
|
| 704 |
+
"source": [
|
| 705 |
+
"def plot_policy_comparison(eval_df, title: str = \"Base vs SFT loaded-model comparison\"):\n",
|
| 706 |
+
" if eval_df is None or eval_df.empty or \"policy\" not in eval_df.columns:\n",
|
| 707 |
+
" print(\"eval_df is empty; run the evaluation cell first.\")\n",
|
| 708 |
+
" return pd.DataFrame()\n",
|
| 709 |
+
"\n",
|
| 710 |
+
" summary = (\n",
|
| 711 |
+
" eval_df.groupby(\"policy\", as_index=True)\n",
|
| 712 |
+
" .agg(\n",
|
| 713 |
+
" avg_reward=(\"total_reward\", \"mean\"),\n",
|
| 714 |
+
" completion_rate=(\"done\", \"mean\"),\n",
|
| 715 |
+
" avg_bookings=(\"bookings\", \"mean\"),\n",
|
| 716 |
+
" avg_violations=(\"violations\", \"mean\"),\n",
|
| 717 |
+
" avg_steps=(\"steps\", \"mean\"),\n",
|
| 718 |
+
" avg_parse_errors=(\"parse_errors\", \"mean\") if \"parse_errors\" in eval_df.columns else (\"steps\", \"size\"),\n",
|
| 719 |
+
" )\n",
|
| 720 |
+
" .sort_index()\n",
|
| 721 |
+
" )\n",
|
| 722 |
+
" plot_cols = [\"avg_reward\", \"completion_rate\", \"avg_bookings\", \"avg_violations\", \"avg_parse_errors\"]\n",
|
| 723 |
+
" axes = summary[plot_cols].plot(\n",
|
| 724 |
+
" kind=\"bar\",\n",
|
| 725 |
+
" subplots=True,\n",
|
| 726 |
+
" layout=(3, 2),\n",
|
| 727 |
+
" figsize=(10, 9),\n",
|
| 728 |
+
" legend=False,\n",
|
| 729 |
+
" title=title,\n",
|
| 730 |
+
" )\n",
|
| 731 |
+
" for ax in axes.ravel():\n",
|
| 732 |
+
" ax.grid(axis=\"y\", alpha=0.3)\n",
|
| 733 |
+
" ax.set_xlabel(\"\")\n",
|
| 734 |
+
" plt.tight_layout()\n",
|
| 735 |
+
" plt.show()\n",
|
| 736 |
+
" return summary\n",
|
| 737 |
+
"\n",
|
| 738 |
+
"comparison_summary = plot_policy_comparison(eval_df)\n",
|
| 739 |
+
"comparison_summary"
|
| 740 |
+
]
|
| 741 |
+
},
|
| 742 |
+
{
|
| 743 |
+
"cell_type": "code",
|
| 744 |
+
"execution_count": null,
|
| 745 |
+
"id": "a9fd3807",
|
| 746 |
+
"metadata": {},
|
| 747 |
+
"outputs": [],
|
| 748 |
+
"source": [
|
| 749 |
+
"# Optional: upload the trained adapter/model to the Hub.\n",
|
| 750 |
+
"# from huggingface_hub import notebook_login\n",
|
| 751 |
+
"# notebook_login()\n",
|
| 752 |
+
"# trainer.push_to_hub(\"flatmate-rl-action-policy\")"
|
| 753 |
+
]
|
| 754 |
+
}
|
| 755 |
+
],
|
| 756 |
+
"metadata": {
|
| 757 |
+
"kernelspec": {
|
| 758 |
+
"display_name": "Python 3",
|
| 759 |
+
"language": "python",
|
| 760 |
+
"name": "python3"
|
| 761 |
+
},
|
| 762 |
+
"language_info": {
|
| 763 |
+
"codemirror_mode": {
|
| 764 |
+
"name": "ipython",
|
| 765 |
+
"version": 3
|
| 766 |
+
},
|
| 767 |
+
"file_extension": ".py",
|
| 768 |
+
"mimetype": "text/x-python",
|
| 769 |
+
"name": "python",
|
| 770 |
+
"nbconvert_exporter": "python",
|
| 771 |
+
"pygments_lexer": "ipython3",
|
| 772 |
+
"version": "3.11"
|
| 773 |
+
}
|
| 774 |
+
},
|
| 775 |
+
"nbformat": 4,
|
| 776 |
+
"nbformat_minor": 5
|
| 777 |
+
}
|