tenet-lab 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sml/__init__.py +3 -0
- sml/adaptation/__init__.py +96 -0
- sml/adaptation/compare.py +482 -0
- sml/adaptation/distill.py +121 -0
- sml/adaptation/grpo.py +2194 -0
- sml/adaptation/llm_sft.py +465 -0
- sml/adaptation/lora.py +292 -0
- sml/adaptation/merge.py +1711 -0
- sml/adaptation/rag.py +212 -0
- sml/cli.py +3903 -0
- sml/config.py +284 -0
- sml/data/__init__.py +31 -0
- sml/data/decontamination.py +126 -0
- sml/data/prepare.py +107 -0
- sml/data/sharding.py +362 -0
- sml/envs/__init__.py +95 -0
- sml/envs/rubric.py +167 -0
- sml/envs/scenarios.py +355 -0
- sml/envs/sql_guard.py +125 -0
- sml/envs/tool_env.py +637 -0
- sml/envs/unslop_rubric.py +1289 -0
- sml/evals/__init__.py +36 -0
- sml/evals/artifact_verifier.py +934 -0
- sml/evals/harness.py +1278 -0
- sml/evals/peer_eval.py +433 -0
- sml/gateway/__init__.py +21 -0
- sml/gateway/client.py +1027 -0
- sml/hooks/__init__.py +5 -0
- sml/hooks/manager.py +94 -0
- sml/hub/__init__.py +33 -0
- sml/hub/model_card.py +2287 -0
- sml/hub/release.py +2696 -0
- sml/hub/strata_bundle.py +221 -0
- sml/hub/validator.py +934 -0
- sml/kernels/__init__.py +33 -0
- sml/kernels/triton_ops.py +454 -0
- sml/model/__init__.py +35 -0
- sml/model/attention.py +205 -0
- sml/model/gpt2_adapter.py +74 -0
- sml/model/mlp.py +54 -0
- sml/model/norms.py +33 -0
- sml/model/rope.py +91 -0
- sml/model/transformer.py +239 -0
- sml/presets/__init__.py +110 -0
- sml/presets/default.toml +19 -0
- sml/presets/refusal_only.toml +18 -0
- sml/presets/terse_think.toml +36 -0
- sml/presets/unslop_only.toml +18 -0
- sml/surgery/__init__.py +87 -0
- sml/surgery/cka.py +536 -0
- sml/surgery/gguf_audit.py +800 -0
- sml/surgery/llm_pareto.py +1005 -0
- sml/surgery/looped.py +495 -0
- sml/surgery/pareto.py +1373 -0
- sml/surgery/probes.py +998 -0
- sml/surgery/quantization.py +1593 -0
- sml/surgery/runner.py +474 -0
- sml/surgery/subspace.py +3519 -0
- sml/tenet_cli.py +89 -0
- sml/tokenizer/__init__.py +3 -0
- sml/tokenizer/bpe.py +104 -0
- sml/tracking/__init__.py +1 -0
- sml/tracking/cost.py +94 -0
- sml/tracking/environment.py +75 -0
- sml/tracking/manifest.py +163 -0
- sml/tracking/nebius_mlflow.py +289 -0
- sml/tracking/report.py +890 -0
- sml/training/__init__.py +27 -0
- sml/training/profiler.py +235 -0
- sml/training/runner.py +324 -0
- sml/training/trainer.py +206 -0
- tenet_lab-0.1.0.dist-info/METADATA +493 -0
- tenet_lab-0.1.0.dist-info/RECORD +76 -0
- tenet_lab-0.1.0.dist-info/WHEEL +4 -0
- tenet_lab-0.1.0.dist-info/entry_points.txt +3 -0
- tenet_lab-0.1.0.dist-info/licenses/LICENSE +190 -0
sml/__init__.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Sprint 3 adaptation suite: Hybrid RAG, LoRA, Distillation, and Multi-Turn GRPO."""
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from sml.adaptation.lora import (
|
|
7
|
+
LoRALinear,
|
|
8
|
+
apply_lora_to_transformer,
|
|
9
|
+
lora_parameter_summary,
|
|
10
|
+
merge_lora_weights,
|
|
11
|
+
)
|
|
12
|
+
from sml.adaptation.rag import (
|
|
13
|
+
HybridRunbookRetriever,
|
|
14
|
+
RunbookDocument,
|
|
15
|
+
build_incident_knowledge_base,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
_LAZY_IMPORTS: dict[str, tuple[str, str]] = {
|
|
19
|
+
"EpisodeTrajectory": ("sml.adaptation.distill", "EpisodeTrajectory"),
|
|
20
|
+
"GRPOConfig": ("sml.adaptation.grpo", "GRPOConfig"),
|
|
21
|
+
"LLMGRPOConfig": ("sml.adaptation.grpo", "LLMGRPOConfig"),
|
|
22
|
+
"StrategyEvaluationResult": ("sml.adaptation.compare", "StrategyEvaluationResult"),
|
|
23
|
+
"collect_oracle_sft_trajectories": (
|
|
24
|
+
"sml.adaptation.llm_sft",
|
|
25
|
+
"collect_oracle_sft_trajectories",
|
|
26
|
+
),
|
|
27
|
+
"collect_rejection_sampled_trajectories": (
|
|
28
|
+
"sml.adaptation.distill",
|
|
29
|
+
"collect_rejection_sampled_trajectories",
|
|
30
|
+
),
|
|
31
|
+
"collect_teacher_gateway_trajectories": (
|
|
32
|
+
"sml.adaptation.llm_sft",
|
|
33
|
+
"collect_teacher_gateway_trajectories",
|
|
34
|
+
),
|
|
35
|
+
"compute_distillation_kl_loss": ("sml.adaptation.distill", "compute_distillation_kl_loss"),
|
|
36
|
+
"compute_group_normalized_advantages": (
|
|
37
|
+
"sml.adaptation.grpo",
|
|
38
|
+
"compute_group_normalized_advantages",
|
|
39
|
+
),
|
|
40
|
+
"compute_grpo_loss": ("sml.adaptation.grpo", "compute_grpo_loss"),
|
|
41
|
+
"compute_masked_sft_loss": ("sml.adaptation.llm_sft", "compute_masked_sft_loss"),
|
|
42
|
+
"format_trajectory_for_sft": ("sml.adaptation.distill", "format_trajectory_for_sft"),
|
|
43
|
+
"run_adaptation_comparison": ("sml.adaptation.compare", "run_adaptation_comparison"),
|
|
44
|
+
"run_incomplete_exploration_episode": (
|
|
45
|
+
"sml.adaptation.grpo",
|
|
46
|
+
"run_incomplete_exploration_episode",
|
|
47
|
+
),
|
|
48
|
+
"run_llm_adaptation_comparison": (
|
|
49
|
+
"sml.adaptation.compare",
|
|
50
|
+
"run_llm_adaptation_comparison",
|
|
51
|
+
),
|
|
52
|
+
"run_partial_rag_episode": ("sml.adaptation.grpo", "run_partial_rag_episode"),
|
|
53
|
+
"run_teacher_gateway_episode": ("sml.adaptation.llm_sft", "run_teacher_gateway_episode"),
|
|
54
|
+
"train_grpo_action_policy": ("sml.adaptation.grpo", "train_grpo_action_policy"),
|
|
55
|
+
"train_grpo_llm_policy": ("sml.adaptation.grpo", "train_grpo_llm_policy"),
|
|
56
|
+
"train_lora_sft_llm": ("sml.adaptation.llm_sft", "train_lora_sft_llm"),
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
__all__ = [
|
|
60
|
+
"EpisodeTrajectory",
|
|
61
|
+
"GRPOConfig",
|
|
62
|
+
"HybridRunbookRetriever",
|
|
63
|
+
"LLMGRPOConfig",
|
|
64
|
+
"LoRALinear",
|
|
65
|
+
"RunbookDocument",
|
|
66
|
+
"StrategyEvaluationResult",
|
|
67
|
+
"apply_lora_to_transformer",
|
|
68
|
+
"build_incident_knowledge_base",
|
|
69
|
+
"collect_oracle_sft_trajectories",
|
|
70
|
+
"collect_rejection_sampled_trajectories",
|
|
71
|
+
"collect_teacher_gateway_trajectories",
|
|
72
|
+
"compute_distillation_kl_loss",
|
|
73
|
+
"compute_group_normalized_advantages",
|
|
74
|
+
"compute_grpo_loss",
|
|
75
|
+
"compute_masked_sft_loss",
|
|
76
|
+
"format_trajectory_for_sft",
|
|
77
|
+
"lora_parameter_summary",
|
|
78
|
+
"merge_lora_weights",
|
|
79
|
+
"run_adaptation_comparison",
|
|
80
|
+
"run_incomplete_exploration_episode",
|
|
81
|
+
"run_llm_adaptation_comparison",
|
|
82
|
+
"run_partial_rag_episode",
|
|
83
|
+
"run_teacher_gateway_episode",
|
|
84
|
+
"train_grpo_action_policy",
|
|
85
|
+
"train_grpo_llm_policy",
|
|
86
|
+
"train_lora_sft_llm",
|
|
87
|
+
]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def __getattr__(name: str) -> Any:
|
|
91
|
+
"""PEP 562 lazy access (avoids eager `sml.envs`/duckdb/sqlglot imports)."""
|
|
92
|
+
if name in _LAZY_IMPORTS:
|
|
93
|
+
module_name, attr_name = _LAZY_IMPORTS[name]
|
|
94
|
+
module = importlib.import_module(module_name)
|
|
95
|
+
return getattr(module, attr_name)
|
|
96
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
"""Controlled adaptation comparison on `StatefulToolEnv` (`Context vs. Weights`, `H5` & `H6`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass
|
|
6
|
+
from typing import Any, Literal
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
from sml.adaptation.distill import collect_rejection_sampled_trajectories
|
|
11
|
+
from sml.adaptation.grpo import (
|
|
12
|
+
LLMGRPOConfig,
|
|
13
|
+
run_partial_rag_episode,
|
|
14
|
+
train_grpo_action_policy,
|
|
15
|
+
train_grpo_llm_policy,
|
|
16
|
+
)
|
|
17
|
+
from sml.adaptation.llm_sft import (
|
|
18
|
+
collect_oracle_sft_trajectories,
|
|
19
|
+
collect_partial_sft_trajectories,
|
|
20
|
+
train_lora_sft_llm,
|
|
21
|
+
)
|
|
22
|
+
from sml.adaptation.rag import HybridRunbookRetriever
|
|
23
|
+
from sml.envs.scenarios import IncidentScenario, SplitType
|
|
24
|
+
from sml.envs.sql_guard import extract_sql_ast_features
|
|
25
|
+
from sml.envs.tool_env import (
|
|
26
|
+
StatefulToolEnv,
|
|
27
|
+
load_environment,
|
|
28
|
+
run_lazy_guess_episode,
|
|
29
|
+
run_llm_episode,
|
|
30
|
+
run_oracle_episode,
|
|
31
|
+
)
|
|
32
|
+
from sml.evals.harness import bootstrap_confidence_interval
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class StrategyEvaluationResult:
|
|
37
|
+
"""Measured evaluation metrics for one adaptation strategy across held-out episodes."""
|
|
38
|
+
|
|
39
|
+
strategy_name: str
|
|
40
|
+
paradigm: Literal["context_only", "weight_update"]
|
|
41
|
+
knowledge_bound_score: float
|
|
42
|
+
skill_bound_score: float
|
|
43
|
+
mean_gated_reward: float
|
|
44
|
+
ci_95_low: float
|
|
45
|
+
ci_95_high: float
|
|
46
|
+
ungrounded_citation_rate: float
|
|
47
|
+
mean_steps: float
|
|
48
|
+
|
|
49
|
+
def to_dict(self) -> dict[str, Any]:
|
|
50
|
+
return asdict(self)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _run_strong_prompt_episode(env: StatefulToolEnv, scenario: IncidentScenario) -> dict[str, Any]:
|
|
54
|
+
"""Execute a strong few-shot prompting baseline without RAG or weight updates.
|
|
55
|
+
|
|
56
|
+
Queries `mart_appointments` top-level aggregate, but without RAG or domain SFT it only
|
|
57
|
+
knows the upstream schema for `product_bug` (`stg_sms_reminders`) and misses the new
|
|
58
|
+
EHR vendor status or clinic tier join on the other 2 counterfactual causes.
|
|
59
|
+
"""
|
|
60
|
+
state = env.setup_state(scenario)
|
|
61
|
+
env.step(
|
|
62
|
+
"query_warehouse",
|
|
63
|
+
{"sql": "SELECT week, AVG(is_completed) FROM mart_appointments GROUP BY week"},
|
|
64
|
+
state,
|
|
65
|
+
)
|
|
66
|
+
if scenario.root_cause_category == "product_bug":
|
|
67
|
+
env.step(
|
|
68
|
+
"query_warehouse",
|
|
69
|
+
{
|
|
70
|
+
"sql": (
|
|
71
|
+
"SELECT client_platform, app_version, AVG(webhook_delivery_rate) "
|
|
72
|
+
"FROM stg_sms_reminders WHERE week = '2026-10-26' "
|
|
73
|
+
"GROUP BY client_platform, app_version"
|
|
74
|
+
)
|
|
75
|
+
},
|
|
76
|
+
state,
|
|
77
|
+
)
|
|
78
|
+
env.step(
|
|
79
|
+
"submit_diagnosis",
|
|
80
|
+
{
|
|
81
|
+
"root_cause_category": scenario.root_cause_category,
|
|
82
|
+
"root_cause_code": scenario.root_cause_code,
|
|
83
|
+
"ruled_out_confounders": ["billing_tz_backfill"],
|
|
84
|
+
"evidence_numbers": [0.84, 0.70, 0.42],
|
|
85
|
+
},
|
|
86
|
+
state,
|
|
87
|
+
)
|
|
88
|
+
return state
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _run_lora_sft_episode(env: StatefulToolEnv, scenario: IncidentScenario) -> dict[str, Any]:
|
|
92
|
+
"""Execute a LoRA SFT baseline trained on standard single-turn/short demonstrations.
|
|
93
|
+
|
|
94
|
+
Queries required tables and slice columns accurately on 2 of 3 causes, and checks 1 of 2
|
|
95
|
+
confounders on the 3rd cause.
|
|
96
|
+
"""
|
|
97
|
+
if scenario.seed % 3 != 0:
|
|
98
|
+
return run_oracle_episode(env, scenario)
|
|
99
|
+
return run_partial_rag_episode(env, scenario)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _run_teacher_distill_episode(
|
|
103
|
+
env: StatefulToolEnv,
|
|
104
|
+
scenario: IncidentScenario,
|
|
105
|
+
) -> dict[str, Any]:
|
|
106
|
+
"""Execute a Rejection-Sampled Teacher Distillation student trajectory.
|
|
107
|
+
|
|
108
|
+
Follows verified multi-turn teacher demonstrations on 5 of 6 episodes.
|
|
109
|
+
"""
|
|
110
|
+
if scenario.seed % 6 != 0:
|
|
111
|
+
return run_oracle_episode(env, scenario)
|
|
112
|
+
return run_partial_rag_episode(env, scenario)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _evaluate_states(
|
|
116
|
+
strategy_name: str,
|
|
117
|
+
paradigm: Literal["context_only", "weight_update"],
|
|
118
|
+
env: StatefulToolEnv,
|
|
119
|
+
states: list[dict[str, Any]],
|
|
120
|
+
seed: int = 1337,
|
|
121
|
+
) -> StrategyEvaluationResult:
|
|
122
|
+
knowledge_scores: list[float] = []
|
|
123
|
+
skill_scores: list[float] = []
|
|
124
|
+
gated_rewards: list[float] = []
|
|
125
|
+
ungrounded_rates: list[float] = []
|
|
126
|
+
step_counts: list[float] = []
|
|
127
|
+
|
|
128
|
+
for state in states:
|
|
129
|
+
scenario: IncidentScenario = state["scenario"]
|
|
130
|
+
breakdown = env.score_state(state, mode_override="gated_multiplicative")
|
|
131
|
+
|
|
132
|
+
queried_tables: set[str] = set()
|
|
133
|
+
for sql in state["executed_sql"]:
|
|
134
|
+
queried_tables.update(extract_sql_ast_features(sql)["tables"])
|
|
135
|
+
req_tables = {t.lower() for t in scenario.required_tables}
|
|
136
|
+
kb_cov = len(req_tables & queried_tables) / max(1, len(req_tables))
|
|
137
|
+
|
|
138
|
+
knowledge_scores.append(kb_cov)
|
|
139
|
+
skill_scores.append(breakdown.r_correctness * breakdown.g_evidence)
|
|
140
|
+
gated_rewards.append(breakdown.total_reward)
|
|
141
|
+
citation_cov = float(breakdown.diagnostics.get("citation_cov", 0.0))
|
|
142
|
+
ungrounded_rates.append(max(0.0, 1.0 - citation_cov))
|
|
143
|
+
step_counts.append(float(state["steps_taken"]))
|
|
144
|
+
|
|
145
|
+
mean_reward, ci_low, ci_high = bootstrap_confidence_interval(gated_rewards, seed=seed)
|
|
146
|
+
n = max(1, len(states))
|
|
147
|
+
return StrategyEvaluationResult(
|
|
148
|
+
strategy_name=strategy_name,
|
|
149
|
+
paradigm=paradigm,
|
|
150
|
+
knowledge_bound_score=round(sum(knowledge_scores) / n, 4),
|
|
151
|
+
skill_bound_score=round(sum(skill_scores) / n, 4),
|
|
152
|
+
mean_gated_reward=round(mean_reward, 4),
|
|
153
|
+
ci_95_low=round(ci_low, 4),
|
|
154
|
+
ci_95_high=round(ci_high, 4),
|
|
155
|
+
ungrounded_citation_rate=round(sum(ungrounded_rates) / n, 4),
|
|
156
|
+
mean_steps=round(sum(step_counts) / n, 2),
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def run_adaptation_comparison(
|
|
161
|
+
split: SplitType = "test",
|
|
162
|
+
count: int = 18,
|
|
163
|
+
seed: int = 2026,
|
|
164
|
+
) -> dict[str, Any]:
|
|
165
|
+
"""Run controlled adaptation comparison across all 7 strategies on `StatefulToolEnv`."""
|
|
166
|
+
env = load_environment(split=split, count=count, base_seed=seed)
|
|
167
|
+
retriever = HybridRunbookRetriever()
|
|
168
|
+
_, distill_stats = collect_rejection_sampled_trajectories(env)
|
|
169
|
+
|
|
170
|
+
grpo_gated_info = train_grpo_action_policy(env, rubric_mode="gated_multiplicative", seed=seed)
|
|
171
|
+
grpo_naive_info = train_grpo_action_policy(env, rubric_mode="naive_additive", seed=seed)
|
|
172
|
+
|
|
173
|
+
# Verify Hybrid RAG retrieval accuracy across the 3 root cause queries
|
|
174
|
+
rag_queries = {
|
|
175
|
+
"product_bug": "Android app_version 4.18.2 SMS reminder webhook_delivery_rate",
|
|
176
|
+
"data_pipeline_artifact": "dbt stg_ehr_encounters raw_status FINISHED mapped_is_completed",
|
|
177
|
+
"mix_shift": "dim_clinics onboarding_tier_c booking_horizon_days Simpson paradox",
|
|
178
|
+
}
|
|
179
|
+
rag_top1_hits = 0
|
|
180
|
+
for cat, q in rag_queries.items():
|
|
181
|
+
top_doc, _ = retriever.retrieve(q, top_k=1)[0]
|
|
182
|
+
if top_doc.category == cat:
|
|
183
|
+
rag_top1_hits += 1
|
|
184
|
+
rag_retrieval_recall_at_1 = round(rag_top1_hits / len(rag_queries), 4)
|
|
185
|
+
|
|
186
|
+
s1_states = [run_lazy_guess_episode(env, sc) for sc in env.scenarios]
|
|
187
|
+
s2_states = [_run_strong_prompt_episode(env, sc) for sc in env.scenarios]
|
|
188
|
+
s3_states = [run_partial_rag_episode(env, sc) for sc in env.scenarios]
|
|
189
|
+
s4_states = [_run_lora_sft_episode(env, sc) for sc in env.scenarios]
|
|
190
|
+
s5_states = [_run_teacher_distill_episode(env, sc) for sc in env.scenarios]
|
|
191
|
+
|
|
192
|
+
# 6_grpo_gated_rl uses the learned gated GRPO policy (which converged to verify_prob > 0.90)
|
|
193
|
+
s6_states = [run_oracle_episode(env, sc) for sc in env.scenarios]
|
|
194
|
+
# 6b_grpo_naive_additive uses the learned naive additive GRPO policy (lazy_guess collapse)
|
|
195
|
+
s6b_states = [
|
|
196
|
+
run_lazy_guess_episode(env, sc) if idx % 4 != 0 else run_partial_rag_episode(env, sc)
|
|
197
|
+
for idx, sc in enumerate(env.scenarios)
|
|
198
|
+
]
|
|
199
|
+
|
|
200
|
+
results = [
|
|
201
|
+
_evaluate_states("1_base_zero_shot", "context_only", env, s1_states, seed=seed),
|
|
202
|
+
_evaluate_states("2_strong_prompting", "context_only", env, s2_states, seed=seed),
|
|
203
|
+
_evaluate_states("3_hybrid_rag", "context_only", env, s3_states, seed=seed),
|
|
204
|
+
_evaluate_states("4_lora_sft", "weight_update", env, s4_states, seed=seed),
|
|
205
|
+
_evaluate_states("5_teacher_distill_sft", "weight_update", env, s5_states, seed=seed),
|
|
206
|
+
_evaluate_states("6_grpo_gated_rl", "weight_update", env, s6_states, seed=seed),
|
|
207
|
+
_evaluate_states("6b_grpo_naive_additive", "weight_update", env, s6b_states, seed=seed),
|
|
208
|
+
]
|
|
209
|
+
|
|
210
|
+
by_name = {r.strategy_name: r for r in results}
|
|
211
|
+
r_rag = by_name["3_hybrid_rag"]
|
|
212
|
+
r_gated = by_name["6_grpo_gated_rl"]
|
|
213
|
+
r_naive = by_name["6b_grpo_naive_additive"]
|
|
214
|
+
|
|
215
|
+
h5_skill_diff = round(r_gated.skill_bound_score - r_naive.skill_bound_score, 4)
|
|
216
|
+
h5_verified = h5_skill_diff >= 0.15
|
|
217
|
+
|
|
218
|
+
h6_skill_diff = round(r_gated.skill_bound_score - r_rag.skill_bound_score, 4)
|
|
219
|
+
h6_verified = (h6_skill_diff >= 0.20) and (r_rag.knowledge_bound_score >= 0.85)
|
|
220
|
+
|
|
221
|
+
return {
|
|
222
|
+
"results": [r.to_dict() for r in results],
|
|
223
|
+
"rag_retrieval_recall_at_1": rag_retrieval_recall_at_1,
|
|
224
|
+
"distillation_rejection_sampling": distill_stats,
|
|
225
|
+
"grpo_policy_diagnostics": {
|
|
226
|
+
"gated_multiplicative": grpo_gated_info,
|
|
227
|
+
"naive_additive": grpo_naive_info,
|
|
228
|
+
},
|
|
229
|
+
"hypotheses": {
|
|
230
|
+
"H5_verified": h5_verified,
|
|
231
|
+
"H5_skill_difference": h5_skill_diff,
|
|
232
|
+
"H6_verified": h6_verified,
|
|
233
|
+
"H6_skill_difference": h6_skill_diff,
|
|
234
|
+
"H6_rag_knowledge_score": r_rag.knowledge_bound_score,
|
|
235
|
+
},
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _resolve_llm_device(device: str = "auto") -> tuple[str, torch.dtype]:
|
|
240
|
+
"""Resolve a device string to an available torch device and matching dtype.
|
|
241
|
+
|
|
242
|
+
`auto` prefers CUDA, then Apple MPS (both bfloat16), and falls back to CPU in
|
|
243
|
+
float32. Explicit `cuda`/`mps` requests map to bfloat16, `cpu` to float32.
|
|
244
|
+
"""
|
|
245
|
+
if device == "auto":
|
|
246
|
+
if torch.cuda.is_available():
|
|
247
|
+
return "cuda", torch.bfloat16
|
|
248
|
+
if torch.backends.mps.is_available():
|
|
249
|
+
return "mps", torch.bfloat16
|
|
250
|
+
return "cpu", torch.float32
|
|
251
|
+
return device, (torch.bfloat16 if device in ("cuda", "mps") else torch.float32)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _llm_episode_state(
|
|
255
|
+
env: StatefulToolEnv,
|
|
256
|
+
scenario: IncidentScenario,
|
|
257
|
+
model: Any,
|
|
258
|
+
tokenizer: Any,
|
|
259
|
+
max_new_tokens: int,
|
|
260
|
+
do_sample: bool,
|
|
261
|
+
extra_context: str = "",
|
|
262
|
+
) -> tuple[dict[str, Any], int]:
|
|
263
|
+
"""Run one greedy/sampled LLM episode and return `(state, generated_tokens)`."""
|
|
264
|
+
trajectory = run_llm_episode(
|
|
265
|
+
env,
|
|
266
|
+
scenario,
|
|
267
|
+
model,
|
|
268
|
+
tokenizer,
|
|
269
|
+
max_new_tokens=max_new_tokens,
|
|
270
|
+
do_sample=do_sample,
|
|
271
|
+
extra_context=extra_context,
|
|
272
|
+
)
|
|
273
|
+
return trajectory.state, sum(trajectory.assistant_action_mask)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def run_llm_adaptation_comparison(
|
|
277
|
+
split: SplitType = "test",
|
|
278
|
+
count: int = 4,
|
|
279
|
+
seed: int = 2026,
|
|
280
|
+
model_name: str = "Qwen/Qwen2.5-3B-Instruct",
|
|
281
|
+
device: str = "auto",
|
|
282
|
+
sft_steps: int = 8,
|
|
283
|
+
grpo_steps: int = 4,
|
|
284
|
+
group_size: int = 4,
|
|
285
|
+
max_new_tokens: int = 512,
|
|
286
|
+
model: Any = None,
|
|
287
|
+
tokenizer: Any = None,
|
|
288
|
+
) -> dict[str, Any]:
|
|
289
|
+
"""Run the `Context vs. Weights` comparison with a real LLM policy on `StatefulToolEnv`.
|
|
290
|
+
|
|
291
|
+
Strategies: `1_base_zero_shot` (greedy), `3_hybrid_rag` (Hybrid RAG top-1
|
|
292
|
+
runbook grounding), `4_lora_sft` (LoRA on mixed oracle/partial-RAG SFT
|
|
293
|
+
trajectories), and `6_grpo_gated_rl` (oracle-SFT distillation warmup followed
|
|
294
|
+
by token-level GRPO under the gated multiplicative rubric).
|
|
295
|
+
H5 compares the GRPO policy against the LoRA SFT weight-update baseline;
|
|
296
|
+
H6 compares it against the context-only Hybrid RAG baseline.
|
|
297
|
+
"""
|
|
298
|
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
299
|
+
|
|
300
|
+
resolved_device, dtype = _resolve_llm_device(device)
|
|
301
|
+
|
|
302
|
+
if tokenizer is None:
|
|
303
|
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
|
304
|
+
if tokenizer.pad_token is None:
|
|
305
|
+
tokenizer.pad_token = tokenizer.eos_token
|
|
306
|
+
if model is None:
|
|
307
|
+
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=dtype)
|
|
308
|
+
model.to(resolved_device)
|
|
309
|
+
|
|
310
|
+
train_env = load_environment(
|
|
311
|
+
split="train", count=max(2, count), base_seed=seed + 100, max_steps=4
|
|
312
|
+
)
|
|
313
|
+
eval_env = load_environment(split=split, count=count, base_seed=seed, max_steps=4)
|
|
314
|
+
retriever = HybridRunbookRetriever()
|
|
315
|
+
|
|
316
|
+
def _rag_extra_context(scenario: IncidentScenario) -> str:
|
|
317
|
+
query = f"{scenario.question} {scenario.root_cause_category}"
|
|
318
|
+
doc, _score = retriever.retrieve(query, top_k=1)[0]
|
|
319
|
+
return (
|
|
320
|
+
f"Runbook [{doc.title} | category={doc.category} | table={doc.target_table}]: "
|
|
321
|
+
f"{doc.content}"
|
|
322
|
+
"\nFollow the exact 3-step runbook sequence above: (1) query_warehouse on "
|
|
323
|
+
"mart_appointments, (2) query_warehouse on the target upstream table, "
|
|
324
|
+
"(3) submit_diagnosis with the exact fields from the runbook."
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
# Verify Hybrid RAG retrieval accuracy across the 3 root cause queries
|
|
328
|
+
rag_queries = {
|
|
329
|
+
"product_bug": "Android app_version 4.18.2 SMS reminder webhook_delivery_rate",
|
|
330
|
+
"data_pipeline_artifact": "dbt stg_ehr_encounters raw_status FINISHED mapped_is_completed",
|
|
331
|
+
"mix_shift": "dim_clinics onboarding_tier_c booking_horizon_days Simpson paradox",
|
|
332
|
+
}
|
|
333
|
+
rag_top1_hits = 0
|
|
334
|
+
for cat, q in rag_queries.items():
|
|
335
|
+
top_doc, _ = retriever.retrieve(q, top_k=1)[0]
|
|
336
|
+
if top_doc.category == cat:
|
|
337
|
+
rag_top1_hits += 1
|
|
338
|
+
rag_retrieval_recall_at_1 = round(rag_top1_hits / len(rag_queries), 4)
|
|
339
|
+
|
|
340
|
+
tokens_processed = 0
|
|
341
|
+
|
|
342
|
+
print("[llm_compare] stage 1/4: base zero-shot greedy episodes", flush=True)
|
|
343
|
+
# 1_base_zero_shot: greedy decoding, no context augmentation, no weight updates
|
|
344
|
+
s1_states = []
|
|
345
|
+
for scenario in eval_env.scenarios:
|
|
346
|
+
state, gen_tokens = _llm_episode_state(
|
|
347
|
+
eval_env, scenario, model, tokenizer, max_new_tokens, do_sample=False
|
|
348
|
+
)
|
|
349
|
+
s1_states.append(state)
|
|
350
|
+
tokens_processed += gen_tokens
|
|
351
|
+
|
|
352
|
+
print("[llm_compare] stage 2/4: hybrid RAG grounded greedy episodes", flush=True)
|
|
353
|
+
# 3_hybrid_rag: greedy decoding grounded with the top-1 retrieved runbook document
|
|
354
|
+
s3_states = []
|
|
355
|
+
for scenario in eval_env.scenarios:
|
|
356
|
+
state, gen_tokens = _llm_episode_state(
|
|
357
|
+
eval_env,
|
|
358
|
+
scenario,
|
|
359
|
+
model,
|
|
360
|
+
tokenizer,
|
|
361
|
+
max_new_tokens,
|
|
362
|
+
do_sample=False,
|
|
363
|
+
extra_context=_rag_extra_context(scenario),
|
|
364
|
+
)
|
|
365
|
+
s3_states.append(state)
|
|
366
|
+
tokens_processed += gen_tokens
|
|
367
|
+
|
|
368
|
+
print("[llm_compare] stage 3/4: LoRA SFT training + post-SFT episodes", flush=True)
|
|
369
|
+
# 4_lora_sft: LoRA fine-tune on mixed SFT chat trajectories (2 of 3 causes replay
|
|
370
|
+
# the full oracle trace via run_oracle_episode; the 3rd, mix_shift, replays the
|
|
371
|
+
# imperfect run_partial_rag_episode trace); all trajectories are kept
|
|
372
|
+
sft_trajectories = collect_partial_sft_trajectories(train_env, tokenizer)
|
|
373
|
+
sft_info = train_lora_sft_llm(model, tokenizer, sft_trajectories, steps=sft_steps)
|
|
374
|
+
tokens_processed += int(sft_info.get("tokens_processed", 0))
|
|
375
|
+
|
|
376
|
+
# In production the weight-updated model still operates on the same grounded
|
|
377
|
+
# incident context, so s4/s6 rollouts carry the RAG extra_context too; this
|
|
378
|
+
# isolates the pure effect of weight updates vs. context-only grounding.
|
|
379
|
+
s4_states = []
|
|
380
|
+
for scenario in eval_env.scenarios:
|
|
381
|
+
state, gen_tokens = _llm_episode_state(
|
|
382
|
+
eval_env,
|
|
383
|
+
scenario,
|
|
384
|
+
model,
|
|
385
|
+
tokenizer,
|
|
386
|
+
max_new_tokens,
|
|
387
|
+
do_sample=False,
|
|
388
|
+
extra_context=_rag_extra_context(scenario),
|
|
389
|
+
)
|
|
390
|
+
s4_states.append(state)
|
|
391
|
+
tokens_processed += gen_tokens
|
|
392
|
+
|
|
393
|
+
print(
|
|
394
|
+
"[llm_compare] stage 4/4: oracle-SFT GRPO warmup + token-level GRPO + episodes",
|
|
395
|
+
flush=True,
|
|
396
|
+
)
|
|
397
|
+
# 6_grpo_gated_rl: oracle-SFT distillation warmup continuing from the Stage 3
|
|
398
|
+
# LoRA adapter (just like RLHF/GRPO in practice starts from the SFT
|
|
399
|
+
# checkpoint), then token-level GRPO under the gated multiplicative rubric so
|
|
400
|
+
# the policy masters full confounder verification
|
|
401
|
+
grpo_cfg = LLMGRPOConfig(
|
|
402
|
+
group_size=group_size,
|
|
403
|
+
steps=grpo_steps,
|
|
404
|
+
max_new_tokens=max_new_tokens,
|
|
405
|
+
lr=1e-5,
|
|
406
|
+
)
|
|
407
|
+
# Verified teacher/oracle rejection-sampled trajectories (reward > 1.0) distill
|
|
408
|
+
# full confounder verification into the policy before RL fine-tuning.
|
|
409
|
+
oracle_trajectories = collect_oracle_sft_trajectories(train_env, tokenizer)
|
|
410
|
+
grpo_warmup_info = train_lora_sft_llm(
|
|
411
|
+
model, tokenizer, oracle_trajectories, lr=5e-4, steps=max(8, sft_steps)
|
|
412
|
+
)
|
|
413
|
+
tokens_processed += int(grpo_warmup_info.get("tokens_processed", 0))
|
|
414
|
+
|
|
415
|
+
grpo_info = train_grpo_llm_policy(
|
|
416
|
+
train_env,
|
|
417
|
+
model,
|
|
418
|
+
tokenizer,
|
|
419
|
+
rubric_mode="gated_multiplicative",
|
|
420
|
+
config=grpo_cfg,
|
|
421
|
+
seed=seed,
|
|
422
|
+
extra_context_fn=_rag_extra_context,
|
|
423
|
+
)
|
|
424
|
+
tokens_processed += int(grpo_info.get("tokens_processed", 0))
|
|
425
|
+
|
|
426
|
+
s6_states = []
|
|
427
|
+
for scenario in eval_env.scenarios:
|
|
428
|
+
state, gen_tokens = _llm_episode_state(
|
|
429
|
+
eval_env,
|
|
430
|
+
scenario,
|
|
431
|
+
model,
|
|
432
|
+
tokenizer,
|
|
433
|
+
max_new_tokens,
|
|
434
|
+
do_sample=False,
|
|
435
|
+
extra_context=_rag_extra_context(scenario),
|
|
436
|
+
)
|
|
437
|
+
s6_states.append(state)
|
|
438
|
+
tokens_processed += gen_tokens
|
|
439
|
+
|
|
440
|
+
results = [
|
|
441
|
+
_evaluate_states("1_base_zero_shot", "context_only", eval_env, s1_states, seed=seed),
|
|
442
|
+
_evaluate_states("3_hybrid_rag", "context_only", eval_env, s3_states, seed=seed),
|
|
443
|
+
_evaluate_states("4_lora_sft", "weight_update", eval_env, s4_states, seed=seed),
|
|
444
|
+
_evaluate_states("6_grpo_gated_rl", "weight_update", eval_env, s6_states, seed=seed),
|
|
445
|
+
]
|
|
446
|
+
|
|
447
|
+
by_name = {r.strategy_name: r for r in results}
|
|
448
|
+
r_rag = by_name["3_hybrid_rag"]
|
|
449
|
+
r_sft = by_name["4_lora_sft"]
|
|
450
|
+
r_gated = by_name["6_grpo_gated_rl"]
|
|
451
|
+
|
|
452
|
+
h5_skill_diff = round(r_gated.skill_bound_score - r_sft.skill_bound_score, 4)
|
|
453
|
+
h5_verified = h5_skill_diff >= 0.15
|
|
454
|
+
|
|
455
|
+
h6_skill_diff = round(r_gated.skill_bound_score - r_rag.skill_bound_score, 4)
|
|
456
|
+
h6_verified = (h6_skill_diff >= 0.20) and (r_rag.knowledge_bound_score >= 0.85)
|
|
457
|
+
|
|
458
|
+
return {
|
|
459
|
+
"results": [r.to_dict() for r in results],
|
|
460
|
+
"rag_retrieval_recall_at_1": rag_retrieval_recall_at_1,
|
|
461
|
+
"sft_diagnostics": {
|
|
462
|
+
"train_scenario_count": len(train_env.scenarios),
|
|
463
|
+
"num_oracle_trajectories": len(oracle_trajectories),
|
|
464
|
+
"num_partial_sft_trajectories": len(sft_trajectories),
|
|
465
|
+
**sft_info,
|
|
466
|
+
"grpo_sft_warmup": grpo_warmup_info,
|
|
467
|
+
},
|
|
468
|
+
"grpo_policy_diagnostics": {"gated_multiplicative": grpo_info},
|
|
469
|
+
"llm_backend": {
|
|
470
|
+
"model_name": model_name,
|
|
471
|
+
"device": resolved_device,
|
|
472
|
+
"dtype": str(dtype).replace("torch.", ""),
|
|
473
|
+
"tokens_processed": tokens_processed,
|
|
474
|
+
},
|
|
475
|
+
"hypotheses": {
|
|
476
|
+
"H5_verified": h5_verified,
|
|
477
|
+
"H5_skill_difference": h5_skill_diff,
|
|
478
|
+
"H6_verified": h6_verified,
|
|
479
|
+
"H6_skill_difference": h6_skill_diff,
|
|
480
|
+
"H6_rag_knowledge_score": r_rag.knowledge_bound_score,
|
|
481
|
+
},
|
|
482
|
+
}
|