Prasham.Jain commited on
Commit
5a79ca8
Β·
1 Parent(s): 0ced196

final submission

Browse files
README.md CHANGED
@@ -1,14 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # CI-Triage-Env
2
 
3
- OpenEnv RL environment for training LLMs to investigate ambiguous CI failures with verifiable rewards.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
- See [plan/README-PLAN.md](plan/README-PLAN.md) for the full build plan and per-branch task folders under [plan/](plan/).
 
 
 
 
 
 
 
 
 
 
6
 
7
- ## Quickstart
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  ```bash
10
- uv sync --all-extras
11
- uv run pytest -q
 
 
 
 
12
  ```
13
 
14
- See [plan/INSTRUCTION-MANUAL.md](plan/INSTRUCTION-MANUAL.md) for the master instruction manual.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: CI Triage Env
3
+ emoji: πŸ”
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: docker
7
+ app_port: 8000
8
+ pinned: false
9
+ license: apache-2.0
10
+ tags:
11
+ - openenv
12
+ - reinforcement-learning
13
+ - llm
14
+ - tool-use
15
+ - ci-cd
16
+ - grpo
17
+ - qwen3
18
+ ---
19
+
20
  # CI-Triage-Env
21
 
22
+ **An OpenEnv RL environment for training LLMs to investigate ambiguous CI failures with verifiable, composable rewards.**
23
+
24
+ > Built for the *Scaler Γ— Meta Γ— PyTorch OpenEnv Hackathon 2026.*
25
+ > Team: Prasham Jain (lead), Sahil, Priyanshi Maheshwari.
26
+
27
+ ---
28
+
29
+ ## Links
30
+
31
+ | Resource | URL |
32
+ |---|---|
33
+ | πŸ€— **Environment Space (judge entrypoint)** | https://huggingface.co/spaces/Prasham1710/ci-triage-env |
34
+ | πŸ€— **Training Space** | https://huggingface.co/spaces/Prasham1710/ci-triage-training |
35
+ | πŸ“¦ **Scenarios dataset** | https://huggingface.co/datasets/Prasham1710/ci-triage-scenarios |
36
+ | πŸ“¦ **SFT trajectories dataset** | https://huggingface.co/datasets/Prasham1710/ci-triage-sft |
37
+ | 🧠 **SFT checkpoint (Qwen3-4B + LoRA)** | https://huggingface.co/Prasham1710/ci-triage-agent-sft |
38
+ | πŸ“ **Blog post (in this repo)** | [`ci-triage-blog-final.md`](ci-triage-blog-final.md) β€” also being published as an HF Community Article |
39
+ | πŸ““ **Training notebook** | [notebooks/train_grpo.ipynb](notebooks/train_grpo.ipynb) |
40
+ | πŸ’» **Source code** | this repository |
41
+
42
+ ---
43
+
44
+ ## 1 Β· Problem β€” *the capability gap*
45
+
46
+ Modern CI pipelines fail for many ambiguous reasons: flaky tests, infra blips, real bugs, dependency drift, missing secrets, race conditions, test data rot. Today, an on-call engineer wastes ~30 min per failure pulling logs, checking flake history, blaming commits, and deciding whether to rerun, quarantine, or file a bug.
47
+
48
+ **Frontier LLMs are not trained on this loop.** They can read a single log dump, but they don't *investigate*: they don't choose which tool to call next, they don't trade off cost vs. information, and they reach diagnoses without supporting evidence. We could not find a public RL environment that rewards an LLM for **multi-turn, evidence-grounded triage** under a budget.
49
+
50
+ That is the gap CI-Triage-Env is built to close.
51
+
52
+ ## 2 Β· Environment β€” *what the agent sees, does, and is graded on*
53
+
54
+ CI-Triage-Env is a fully OpenEnv-compliant `MCPEnvironment` with a Gym-style API (`reset` / `step` / `state`).
55
+
56
+ ### Observation
57
+ Each episode begins with a **scenario**: a synthesised CI failure (~3,500 generated, 200 hand-validated for the train split) containing a `failure_summary`, the failing test, a hidden `ground_truth_root_cause`, and an oracle "minimal evidence set" β€” the smallest set of tools whose outputs together justify the correct diagnosis.
58
+
59
+ ### Action space β€” 11 MCP tools
60
+ | Tool | What it does | Cost |
61
+ |---|---|---|
62
+ | `read_logs` | full CI log for a test | 1 |
63
+ | `inspect_test_code` | test source | 1 |
64
+ | `run_diagnostic` | scoped shell probe | 3 |
65
+ | `cluster_metrics` | infra metrics for a window | 2 |
66
+ | `query_flake_history` | flake stats for a test | 1 |
67
+ | `recent_commits` | recent commits to repo/path | 1 |
68
+ | `check_owner` | CODEOWNERS lookup | 0 |
69
+ | `rerun_test` | quarantine probe (1Γ—) | 5 |
70
+ | `quarantine_test` | quarantines (terminal-ish) | β€” |
71
+ | `file_bug` | files a bug (terminal) | β€” |
72
+ | `ping_owner` | message owner (terminal) | β€” |
73
+
74
+ The agent operates under a **total cost budget per episode**. Each step returns the tool's structured output plus the remaining budget.
75
+
76
+ ### Reward β€” 9 composable, frozen-weight components
77
+ Built using OpenEnv's rubric pattern (composition, not a monolith):
78
 
79
+ | # | Component | Weight | Captures |
80
+ |---|---|---|---|
81
+ | 1 | `diagnosis` | 0.25 | Was the predicted root cause correct? |
82
+ | 2 | `minimal_evidence` | 0.20 | Did the agent collect the oracle evidence set? |
83
+ | 3 | `cost_efficiency` | 0.15 | Did it stay within budget? |
84
+ | 4 | `action_quality` | 0.10 | Were tool calls well-formed and contextually sensible? |
85
+ | 5 | `investigation` | 0.10 | Did the trace branch logically? |
86
+ | 6 | `format_gate` | 0.05 | Strict JSON schema compliance |
87
+ | 7 | `time_penalty` | 0.05 | Penalty for excessive turns |
88
+ | 8 | `counterfactual_predict` | 0.05 | Was the predicted "fix" plausible vs ground truth? |
89
+ | 9 | `anti_gaming` | 0.05 | Penalty for repeat / spam / quarantine-spam patterns |
90
 
91
+ **Why this is hard to game:** every component is verifiable from the trace; the highest-weight terms (`diagnosis`, `minimal_evidence`) directly require the agent to *find the right cause with the right evidence*. The `anti_gaming` and `cost_efficiency` terms specifically punish the dominant exploit (always-quarantine; spam tools).
92
+
93
+ Weights live in [src/ci_triage_env/rewards/weights.py](src/ci_triage_env/rewards/weights.py); replay verifier is in [src/ci_triage_env/rewards/replay.py](src/ci_triage_env/rewards/replay.py).
94
+
95
+ ## 3 Β· Pipeline β€” *training top to bottom*
96
+
97
+ ```
98
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
99
+ β”‚ 3,500 scenarios β”‚ ← clustered from real OSS CI logs
100
+ β”‚ (synth + LLM-aug) β”‚ + LLM-generated edge cases
101
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
102
+ β”‚
103
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
104
+ β”‚ SFT trajectories β”‚ teacher: GPT-4o-mini
105
+ β”‚ ~700 episodes β”‚ filtered: reward β‰₯ 0.6
106
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
107
+ β”‚
108
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
109
+ β”‚ Qwen3-4B + LoRA (r=16) via Unsloth β”‚
110
+ β”‚ SFT β†’ 2 epochs, bf16, A10G Small β”‚ βœ… DONE β€” see plot
111
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
112
+ β”‚
113
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
114
+ β”‚ GRPO Β· TRL Β· multi-turn rollout β”‚
115
+ β”‚ reward = composite of 9 components β”‚ ⚠ BLOCKED β€” see "Status"
116
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
117
+ ```
118
+
119
+ Sources:
120
+ - SFT trainer β€” [src/ci_triage_env/training/sft.py](src/ci_triage_env/training/sft.py)
121
+ - GRPO trainer β€” [src/ci_triage_env/training/grpo.py](src/ci_triage_env/training/grpo.py)
122
+ - Multi-turn rollout β€” [src/ci_triage_env/training/rollout.py](src/ci_triage_env/training/rollout.py)
123
+ - Composite reward β€” [src/ci_triage_env/rewards/composite.py](src/ci_triage_env/rewards/composite.py)
124
+ - Notebook judges can re-run β€” [notebooks/train_grpo.ipynb](notebooks/train_grpo.ipynb)
125
+
126
+ ## 4 Β· Results & Evidence
127
+
128
+ ### SFT β€” completed, real run on A10G Small
129
+
130
+ We trained Qwen3-4B + LoRA via Unsloth on 718 SFT trajectories for 2 epochs. The run completed end-to-end and the checkpoint is on the HF Hub.
131
+
132
+ - **Checkpoint:** https://huggingface.co/Prasham1710/ci-triage-agent-sft
133
+ - **W&B run:** https://wandb.ai/jainprasham17-esds/ci-triage-env
134
+ - **Final training loss:** ~0.55 (from log line `180 0.548925`)
135
+ - **Hardware:** A10G Small, 24 GB VRAM, ~50 min wall-clock
136
+
137
+ ![SFT training loss β€” Qwen3-4B + LoRA, 2 epochs on A10G Small](loss_graphs_sft.png)
138
+
139
+ *Loss curve from the real SFT run β€” smooth descent from ~1.4 β†’ 0.55 over 180 steps.*
140
+
141
+ Concrete log excerpt from the run:
142
+
143
+ ```
144
+ Trainable parameters = 33,030,144 of 4,055,498,240 (0.81% trained)
145
+ ...
146
+ 180 0.548925
147
+ [transformers] Unsloth: Restored added_tokens_decoder metadata in /data/checkpoints/sft/checkpoint-180/tokenizer_config.json.
148
+ SFT done β†’ /data/checkpoints/sft
149
+ ```
150
+
151
+ ### GRPO β€” environment + reward + rollout all built; blocked at trainer wiring
152
+
153
+ Every component the GRPO loop needs is implemented and committed:
154
+ - TRL `GRPOTrainer` integration in [grpo.py](src/ci_triage_env/training/grpo.py)
155
+ - `MockEnvClient` for in-process rollouts (no network) in [mock_env_client.py](src/ci_triage_env/training/mock_env_client.py)
156
+ - Multi-turn `TrainingRollout` calling the same composite reward
157
+ - Frozen reward-component weights so curves are comparable
158
+
159
+ We hit a chain of upstream version conflicts after the Qwen3-5 stack required `transformers v5` from git, which then required `torchao β‰₯ 0.13` (needed `torch β‰₯ 2.7`), which made Unsloth's fast-LoRA matmul kernel run with mismatched fp16/bf16 tensors during the GRPO forward pass:
160
+
161
+ ```
162
+ RuntimeError: self and mat2 must have the same dtype, but got Half and BFloat16
163
+ at /opt/conda/lib/python3.11/site-packages/unsloth/kernels/utils.py:1059
164
+ in matmul_lora β†’ out.addmm_(XA, B.to(dtype), alpha=s)
165
+ ```
166
+
167
+ We did get **all 9 reward components computing real values on real trajectories** during MockEnvClient testing β€” the reward signal is wired and shaped, just not yet connected to a policy gradient update. The plan/blocker is documented in detail above and reproducible from the notebook.
168
+
169
+ ## 5 Β· How to run
170
+
171
+ ### A. Use the environment (judges)
172
+
173
+ ```bash
174
+ # Pull and run the env server (it's a Docker Space)
175
+ docker run -p 8000:8000 --pull always \
176
+ registry.hf.space/prasham1710-ci-triage-env:latest
177
+
178
+ # Or clone & run locally
179
+ git clone https://huggingface.co/spaces/Prasham1710/ci-triage-env
180
+ cd ci-triage-env && docker build -t ci-triage-env . && \
181
+ docker run -p 8000:8000 ci-triage-env
182
+ ```
183
+
184
+ Then talk to it:
185
+ ```bash
186
+ curl -X POST http://localhost:8000/reset # β†’ initial obs
187
+ curl -X POST http://localhost:8000/step \
188
+ -H 'Content-Type: application/json' \
189
+ -d '{"action":{"tool":"read_logs","args":{"test_name":"test_x"}}}'
190
+ curl http://localhost:8000/state
191
+ curl http://localhost:8000/docs # OpenAPI/Swagger
192
+ ```
193
+
194
+ The Space also exposes the standard MCP route at `POST /mcp` (JSON-RPC) and `WS /mcp`.
195
+
196
+ ### B. Reproduce training
197
 
198
  ```bash
199
+ git clone https://github.com/<this-repo>.git
200
+ cd CI-Triage-Env
201
+ pip install -e ".[data,training]"
202
+
203
+ # Set HF_TOKEN, HF_USERNAME, WANDB_API_KEY
204
+ jupyter lab notebooks/train_grpo.ipynb
205
  ```
206
 
207
+ Or use the Training Space (preconfigured for A10G):
208
+ https://huggingface.co/spaces/Prasham1710/ci-triage-training
209
+
210
+ ## 6 Β· Engineering hygiene
211
+
212
+ - βœ… OpenEnv `MCPEnvironment` base class, valid `openenv.yaml`
213
+ - βœ… Standard Gym API: `reset`, `step`, `state`
214
+ - βœ… MCP tool names β€” none collide with reserved names (`reset`/`step`/`state`/`close`)
215
+ - βœ… Strict client/server separation (server in `env/`, clients import only the wire schemas)
216
+ - βœ… JSON-Schema validated action/observation envelopes ([schemas/](src/ci_triage_env/schemas/))
217
+ - βœ… FastAPI `/docs` for interactive exploration
218
+
219
+ ## 7 Β· Why it matters
220
+
221
+ Every shop running CI burns engineering hours on triage. If a 4B-parameter LLM can do this reliably, that's hours back per on-call shift, plus a paper trail of *why* the diagnosis was made (the trace itself). The methodology β€” composable rubric rewards over multi-turn tool use against a budget β€” generalizes well beyond CI: incident response, code review triage, security alert triage all share the structure.
222
+
223
+ ## 8 Β· Status (April 26 2026, submission day)
224
+
225
+ - βœ… Environment fully implemented + deployed to HF Space
226
+ - βœ… 3,500 scenarios + 700+ SFT trajectories generated, validated, published
227
+ - βœ… All 9 reward components implemented and replay-verified
228
+ - βœ… SFT warmstart trained end-to-end (Qwen3-4B + LoRA, 2 epochs, A10G Small)
229
+ - ⚠ GRPO loop blocked by Unsloth/torchao/transformers-v5 fp16/bf16 mismatch in `matmul_lora`; pipeline + reward signal verified separately
230
+ - 🚧 Inference UI (Streamlit) β€” out of time
231
+
232
+ ## 9 Β· License & credits
233
+
234
+ Apache-2.0. Built with OpenEnv, Unsloth, TRL, Hugging Face Transformers, PyTorch.
235
+ Data scenarios are synthetic; no proprietary CI logs are included.
236
+
237
+ ## Blog
238
+
239
+ We're publishing a companion mini-blog on Hugging Face explaining the environment design, the rubric reward, and what we learned. **Link will be inserted here once published** β€” judges, please check the top-of-page **Links** table.
ci-triage-blog-final.md ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: "We Trained a 4B Model to Do CI Triage. Here's How We Made the Reward System Uncheateable."
3
+ thumbnail: /blog/assets/ci-triage-env/thumbnail.png
4
+ authors:
5
+ - user: Prasham1710
6
+ tags:
7
+ - reinforcement-learning
8
+ - openenv
9
+ - agents
10
+ - tool-use
11
+ - grpo
12
+ - qwen
13
+ ---
14
+
15
+ # We Trained a 4B Model to Do CI Triage. Here's How We Made the Reward System Uncheateable.
16
+
17
+ It's 3am. Your phone goes off. CI is red on `main`. A test called `test_payment_processor_idempotency` failed and it's blocking four PRs.
18
+
19
+ You open the logs. 1,400 lines. You grep for `ERROR`. Three hits β€” two look like noise, one looks real. You check recent commits. Someone touched the payment module six hours ago. Could be that. Or it could be the DNS blip you had last Tuesday. Or the timing assertion that's been silently flaky for months.
20
+
21
+ You have three choices and each one is wrong in a different way. Rerun it β€” and if it's a real bug, you just hid it. It'll ship to production and you'll get paged again at 9am by a customer. Quarantine it β€” and if it's actually an infra issue, you've just blocked a dozen developers from merging for no reason. File a P1 and ping the owner β€” and if it's a flake, you've woken up your most senior engineer at 3am for nothing. They will remember this.
22
+
23
+ This is the problem that every engineering team above 50 people lives with, every single day. And it's not a detection problem β€” you already have Trunk.io, BuildPulse, Datadog Flaky Test Management. Those tools detect *patterns*. They don't *investigate*. The investigation β€” reading the logs, correlating the commits, checking the resource metrics, making the call under pressure β€” is still done by humans.
24
+
25
+ We built an RL environment to close that gap. We called it **CI-Triage-Env**.
26
+
27
+ ---
28
+
29
+ ## Why This Isn't a Classification Problem
30
+
31
+ The obvious approach is to frame this as supervised learning. Train a model on (log β†’ label) pairs, ship it. Clean, simple, wrong.
32
+
33
+ The problem is that the right action at any step depends entirely on what you've already found. If you checked flake history first and the test has a 60% pass rate over 30 runs, that completely changes whether you should bother reading the logs in detail. If cluster metrics show a memory spike across all nodes 4 minutes before the failure, the individual test logs stop mattering. The investigation is sequential. The state changes with every tool call. You can't supervise that.
34
+
35
+ There's also no dataset. Senior engineers do CI triage through tacit knowledge built over years of 3am incidents. That knowledge doesn't exist as labeled trajectories anywhere. You can't scrape it. And even if you could, you'd be training a model to imitate the *actions*, not to learn the *reasoning* behind them.
36
+
37
+ And then there's the thing that settled the question for us: we wanted to probe whether the model had actually built a world model of the CI system, or whether it was just pattern-matching on log text. You can't test that with supervised learning. You need a counterfactual probe. More on that later.
38
+
39
+ So: reinforcement learning. The agent explores, makes mistakes, gets a reward signal grounded in real CI economics, and learns to investigate.
40
+
41
+ ---
42
+
43
+ ## The Environment
44
+
45
+ We built CI-Triage-Env on [OpenEnv](https://github.com/openenv/openenv) with a standard `reset() / step()` interface. At episode start, the agent gets a failure summary β€” failing test name, branch, last-passing commit β€” along with a budget of 12 tool calls and a cost cap. Then it starts working.
46
+
47
+ The tool surface is split into three layers. Investigation tools are cheap: `read_logs`, `inspect_test_code`, `cluster_metrics`. Context tools are moderate: `query_flake_history`, `recent_commits`, `check_owner`. Action tools are expensive and carry real risk: `rerun_test` costs the same as running a full CI job, `file_bug` costs 30 minutes of a human engineer's time, `ping_owner` burns paging budget credibility. Every tool has a cost weight in dollars-equivalent. The agent has to decide what's worth knowing before it pays to find out.
48
+
49
+ The episode ends when the agent calls `submit_diagnosis(label, confidence)`. It has to pick one of seven labels: real bug, race-condition flake, timing flake, infra-network, infra-resource, dependency drift, or β€” critically β€” `abstain`. That last one is for genuinely ambiguous cases where the evidence is insufficient. Knowing when *not* to be confident is part of what we're training.
50
+
51
+ We built 200+ scenarios across those seven failure families, generated from real public CI failure data. We mined GitHub Actions logs from Kubernetes, React, Rust, TensorFlow, and similar large open-source repos, clustered them by failure category, templatized the patterns, and generated fresh parameterized instances from seeds. The scenarios are deterministic: the same seed always produces the same failure, which makes the reward signal fully verifiable.
52
+
53
+ ---
54
+
55
+ ## The Reward System β€” and Why Each Component Exists
56
+
57
+ This is where most of our design time went. Getting the reward right is the whole job.
58
+
59
+ The full reward looks like this:
60
+
61
+ ```
62
+ R = R_format Γ— (
63
+ 0.25 Γ— R_diagnosis
64
+ + 0.20 Γ— R_action_quality
65
+ + 0.15 Γ— R_cost_efficiency
66
+ + 0.15 Γ— R_investigation
67
+ + 0.10 Γ— R_time
68
+ + 0.15 Γ— R_anti_game
69
+ ) + 0.10 Γ— R_counterfactual
70
+ ```
71
+
72
+ Every single component is computed against simulator ground truth. There is no LLM-as-judge anywhere in the pipeline. Here's the reasoning behind each one.
73
+
74
+ **R_format is a hard gate.** If the model's output doesn't pass strict JSON schema validation, the entire episode reward is zero. No partial credit. This sounds brutal but it's necessary β€” a triage agent that outputs malformed JSON in production is worse than no agent at all.
75
+
76
+ **R_diagnosis carries the most weight (25%) and is asymmetric on purpose.** Quarantining a real bug scores βˆ’1.0 because it ships to production. Rerunning a real bug scores βˆ’0.7 because it hides the bug and delays detection. Filing a bug for an infra issue scores βˆ’0.5 because it burns on-call trust. These aren't made-up numbers β€” they're grounded in Bell et al. FSE 2018 and the Google SRE Book's chapter on incident cost. We documented every weight with citations.
77
+
78
+ **R_action_quality (20%) scores the action separately from the label.** A model can correctly identify that something is a flake but still file a P0 bug. The diagnosis is right; the behavior is wrong. These need to be scored independently.
79
+
80
+ **R_investigation (15%) is about how you got there, not just whether you got there.** Every scenario has a hand-labeled `informative_tools` set β€” the specific tool calls that were necessary or sufficient for the correct diagnosis. We reward coverage of that set, penalize redundant calls (same args, no new information), and give a bonus for good ordering: cheap tools before expensive ones, context before action. `recent_commits` should come before `ping_owner`. This component is what trains the agent to investigate efficiently, not just correctly.
81
+
82
+ **R_anti_game (15%) was born from thinking hard about how a clever agent would cheat.** If you don't guard against it, the obvious shortcuts are: quarantine everything (100% recall on real bugs, zero precision), always rerun (lowest immediate cost), or just guess from the failure summary without calling any tools. We built specific probes for all three. If the quarantine rate across the last 50 episodes exceeds 30%, all rewards scale down proportionally. Terminal action without at least two informative tool calls gets reward halved. And for ambiguous cases, `submit_diagnosis(confidence)` is scored by Brier loss β€” overconfidence on hard cases is punished directly.
83
+
84
+ ---
85
+
86
+ ## The Counterfactual Probe β€” The Part We're Most Proud Of
87
+
88
+ On 20% of episodes, randomly selected, after the agent submits its terminal action, we don't end the episode. Instead we emit one more observation:
89
+
90
+ > *"Had you called `rerun_test()` instead of `quarantine_test()` at step 4, what would the outcome have been? Predict: success / failure / needs-more-info, with confidence."*
91
+
92
+ The environment is fully deterministic from `(scenario_id, seed, action_history)`. To compute the ground truth, we replay from a snapshot at step 4 with the alternative action and observe what actually happens. The agent's reward is the Brier score on its prediction.
93
+
94
+ Here's why this matters: you cannot score well on this probe by pattern-matching on log text. The logs at the point of the counterfactual question are fixed β€” they don't tell you what would have happened if you'd acted differently. The only way to answer correctly is to have built an internal model of how the simulated CI system *responds to actions*. That's world-model learning. That's the thing that separates an agent that understands the environment from one that's memorized surface patterns.
95
+
96
+ We're not aware of other teams shipping a probe like this in an OpenEnv submission.
97
+
98
+ ---
99
+
100
+ ## Training
101
+
102
+ We used **Qwen3-4B** (`unsloth/Qwen3-4B`) as the base model with **LoRA r=16 in bf16** via Unsloth β€” bf16 LoRA, not 4-bit QLoRA, following Unsloth's current guidance for the Qwen3 family.
103
+
104
+ **Stage 1 β€” SFT warmstart.** We ran a frontier teacher (GPT-4o-mini) over the environment, scored each rollout with our composite reward, and kept the top tier. That left us with **718 high-quality trajectories** which we fine-tuned for 2 epochs on a single A10G Small (24 GB). The run completed end-to-end in ~50 minutes with final training loss around **0.55**.
105
+
106
+ ![SFT training loss β€” Qwen3-4B + LoRA, 2 epochs on A10G Small](loss_graphs_sft.png)
107
+ *Loss decreasing smoothly from ~1.4 β†’ 0.55 over 180 steps. The shape is what we wanted: the warmstart gives GRPO a reasonable starting policy instead of exploring from scratch.*
108
+
109
+ **Stage 2 β€” GRPO via TRL.** Configured with group size 2 (memory-bound on A10G Small), batch 1 Γ— grad-accum 4, LR 5e-6, KL coefficient 0.04, multi-turn rollout against `MockEnvClient`. The full pipeline is wired β€” multi-turn rollout, all 9 reward components computing real values, frozen weights so curves are comparable.
110
+
111
+ **Where we got stuck.** Submission day, our GRPO loop hit a chain of upstream version conflicts. The Qwen3 stack pulled in `transformers v5` (from git), which pulled in `torchao β‰₯ 0.13`, which pulled in `torch β‰₯ 2.7`. With that combination, Unsloth's fused `matmul_lora` kernel ran with mismatched fp16/bf16 tensors during the GRPO forward pass:
112
+
113
+ ```
114
+ RuntimeError: self and mat2 must have the same dtype, but got Half and BFloat16
115
+ at unsloth/kernels/utils.py:1059 β†’ out.addmm_(XA, B.to(dtype), alpha=s)
116
+ ```
117
+
118
+ We tried four progressively more aggressive fixes β€” explicit dtype loading, recursive parameter casting, monkey-patching `matmul_lora` to force bf16, disabling autocast, bypassing Unsloth entirely with vanilla PEFT. The vanilla PEFT path then OOMed at 22 GB on the A10G Small, and we ran out of clock. The blockers are documented in the README; the SFT checkpoint, environment, dataset, and reward replay verifier are all real and shipped.
119
+
120
+ **Evaluation harness.** We built (but didn't get to run) a comparison against four baselines β€” random policy, hand-coded heuristic, Qwen3-4B zero-shot, and the SFT checkpoint β€” across diagnosis accuracy, action appropriateness, tool-call cost, Brier score on ambiguous cases, and counterfactual prediction accuracy. The harness is in `src/ci_triage_env/training/eval.py`.
121
+
122
+ ---
123
+
124
+ ## What This Generalizes To
125
+
126
+ CI triage is the use case. The pattern generalizes much further.
127
+
128
+ Any ambiguous-diagnosis problem in software engineering has the same structure: sequential investigation under cost constraints, asymmetric misclassification costs, reward that has to be grounded in simulator truth rather than human judgment. Production incident triage. Security alert triage. Code review for race conditions. The methodology is the thing we actually built. The CI environment is the demonstration.
129
+
130
+ We trained a 4B model. The same recipe runs at frontier scale. What we built is a recipe, not a product β€” and we think the recipe is what's interesting.
131
+
132
+ ---
133
+
134
+ ## Try It
135
+
136
+ ```bash
137
+ git clone https://huggingface.co/spaces/Prasham1710/ci-triage-env
138
+ cd ci-triage-env
139
+ pip install -e ".[data,training]"
140
+ uvicorn ci_triage_env.env.server:build_app --factory --host 0.0.0.0 --port 8000
141
+ # open http://localhost:8000/docs β†’ interact with all 11 tools via Swagger
142
+ ```
143
+
144
+ - πŸ€— **Environment Space (live)**: [ci-triage-env](https://huggingface.co/spaces/Prasham1710/ci-triage-env)
145
+ - πŸ‹οΈ **Training Space**: [ci-triage-training](https://huggingface.co/spaces/Prasham1710/ci-triage-training)
146
+ - πŸ—‚οΈ **Scenario corpus**: [ci-triage-scenarios](https://huggingface.co/datasets/Prasham1710/ci-triage-scenarios)
147
+ - πŸ“š **SFT trajectories**: [ci-triage-sft](https://huggingface.co/datasets/Prasham1710/ci-triage-sft)
148
+ - 🧠 **SFT checkpoint (Qwen3-4B + LoRA)**: [ci-triage-agent-sft](https://huggingface.co/Prasham1710/ci-triage-agent-sft)
149
+ - πŸ““ **Training notebook**: [`notebooks/train_grpo.ipynb`](https://huggingface.co/spaces/Prasham1710/ci-triage-training/blob/main/notebooks/train_grpo.ipynb)
150
+
151
+ ---
152
+
153
+ *Built for the Scaler Γ— Meta PyTorch OpenEnv Hackathon.*
154
+
155
+ *Datasets used: DeFlaker (Bell et al. FSE 2018), iDFlakies (Lam et al. ICSE 2019), FlakeFlagger (Alshammari et al. ICSE 2021), LogHub (Zhu et al. ISSRE 2019), GitHub Actions public logs.*
loss_graphs_sft.png ADDED
plan/BUDGET-LOG.md CHANGED
@@ -2,3 +2,4 @@
2
 
3
  [2026-04-26 04:37] C3 trajectory_gen: 98 trajectories, $0.19 cumulative
4
  [2026-04-26 04:53] C3 trajectory_gen: 196 trajectories, $0.33 cumulative
 
 
2
 
3
  [2026-04-26 04:37] C3 trajectory_gen: 98 trajectories, $0.19 cumulative
4
  [2026-04-26 04:53] C3 trajectory_gen: 196 trajectories, $0.33 cumulative
5
+ [2026-04-26 05:39] C3 trajectory_gen: 1437 trajectories, $2.61 cumulative
push_to_hf.sh CHANGED
@@ -1,29 +1,40 @@
1
  #!/usr/bin/env bash
2
  # Push this repo to both HuggingFace Spaces.
3
  #
4
- # Usage:
5
- # export HF_USERNAME="your_hf_username"
6
  # export HF_TOKEN="hf_xxxxxxxxxxxx"
7
  # bash push_to_hf.sh
8
  #
 
 
 
 
 
 
 
 
9
  # What it does:
10
  # 1. Pushes main β†’ ci-triage-env Space (uses root Dockerfile = env server)
11
  # 2. Creates a temporary branch where Dockerfile.train becomes Dockerfile,
12
- # pushes that β†’ ci-triage-training Space, then cleans up the branch.
13
 
14
  set -euo pipefail
15
 
16
  : "${HF_USERNAME:?Set HF_USERNAME before running}"
17
  : "${HF_TOKEN:?Set HF_TOKEN before running}"
18
 
 
 
 
 
 
19
  ENV_SPACE="ci-triage-env"
20
- TRAIN_SPACE="ci-triage-training"
21
 
22
  HF_ENV_REMOTE="https://${HF_USERNAME}:${HF_TOKEN}@huggingface.co/spaces/${HF_USERNAME}/${ENV_SPACE}"
23
- HF_TRAIN_REMOTE="https://${HF_USERNAME}:${HF_TOKEN}@huggingface.co/spaces/${HF_USERNAME}/${TRAIN_SPACE}"
24
 
25
  # Prepend HF Space YAML frontmatter to README.md then restore it afterward.
26
- # HF requires this block so it knows the Space type and can render the UI correctly.
27
  inject_readme() {
28
  local frontmatter="$1"
29
  local original
@@ -37,7 +48,7 @@ restore_readme() {
37
 
38
  # ── 1. Env server Space ───────────────────────────────────────────────────────
39
  echo ""
40
- echo "==> Pushing env server to ${ENV_SPACE} …"
41
 
42
  ENV_FRONTMATTER="---
43
  title: CI Triage Env
@@ -65,7 +76,7 @@ git branch -D "$TEMP_BRANCH"
65
 
66
  # ── 2. Training Space (Dockerfile.train β†’ Dockerfile + frontmatter) ──────────
67
  echo ""
68
- echo "==> Preparing training Space push …"
69
 
70
  TRAIN_FRONTMATTER="---
71
  title: CI Triage Training
@@ -89,7 +100,7 @@ git commit -m "chore(spaces): add HF Space config for training [skip ci]"
89
  git remote remove hf-train 2>/dev/null || true
90
  git remote add hf-train "$HF_TRAIN_REMOTE"
91
  git push hf-train "${TEMP_BRANCH}:main" --force
92
- echo " βœ“ https://huggingface.co/spaces/${HF_USERNAME}/${TRAIN_SPACE}"
93
 
94
  # ── Cleanup ───────────────────────────────────────────────────────────────────
95
  git checkout main
@@ -98,7 +109,7 @@ git remote remove hf-env 2>/dev/null || true
98
  git remote remove hf-train 2>/dev/null || true
99
 
100
  echo ""
101
- echo "Both Spaces updated. Docker builds will start automatically (~3 min env / ~15 min training)."
102
  echo "Watch build logs:"
103
  echo " https://huggingface.co/spaces/${HF_USERNAME}/${ENV_SPACE}"
104
- echo " https://huggingface.co/spaces/${HF_USERNAME}/${TRAIN_SPACE}"
 
1
  #!/usr/bin/env bash
2
  # Push this repo to both HuggingFace Spaces.
3
  #
4
+ # Basic usage (same account for both):
5
+ # export HF_USERNAME="Prasham1710"
6
  # export HF_TOKEN="hf_xxxxxxxxxxxx"
7
  # bash push_to_hf.sh
8
  #
9
+ # Push training Space to a DIFFERENT account (e.g. priyanshimaheshwari):
10
+ # export HF_USERNAME="Prasham1710" # env server account (unchanged)
11
+ # export HF_TOKEN="hf_prasham_token" # env server token
12
+ # export TRAIN_HF_USERNAME="priyanshimaheshwari"
13
+ # export TRAIN_HF_TOKEN="hf_priyanshi_token"
14
+ # export TRAIN_SPACE_NAME="ci-triage-env" # name of the Space in that account
15
+ # bash push_to_hf.sh
16
+ #
17
  # What it does:
18
  # 1. Pushes main β†’ ci-triage-env Space (uses root Dockerfile = env server)
19
  # 2. Creates a temporary branch where Dockerfile.train becomes Dockerfile,
20
+ # pushes that β†’ training Space (possibly in a different account), then cleans up.
21
 
22
  set -euo pipefail
23
 
24
  : "${HF_USERNAME:?Set HF_USERNAME before running}"
25
  : "${HF_TOKEN:?Set HF_TOKEN before running}"
26
 
27
+ # Training Space can live in a different account/space.
28
+ TRAIN_HF_USERNAME="${TRAIN_HF_USERNAME:-${HF_USERNAME}}"
29
+ TRAIN_HF_TOKEN="${TRAIN_HF_TOKEN:-${HF_TOKEN}}"
30
+ TRAIN_SPACE_NAME="${TRAIN_SPACE_NAME:-ci-triage-training}"
31
+
32
  ENV_SPACE="ci-triage-env"
 
33
 
34
  HF_ENV_REMOTE="https://${HF_USERNAME}:${HF_TOKEN}@huggingface.co/spaces/${HF_USERNAME}/${ENV_SPACE}"
35
+ HF_TRAIN_REMOTE="https://${TRAIN_HF_USERNAME}:${TRAIN_HF_TOKEN}@huggingface.co/spaces/${TRAIN_HF_USERNAME}/${TRAIN_SPACE_NAME}"
36
 
37
  # Prepend HF Space YAML frontmatter to README.md then restore it afterward.
 
38
  inject_readme() {
39
  local frontmatter="$1"
40
  local original
 
48
 
49
  # ── 1. Env server Space ───────────────────────────────────────────────────────
50
  echo ""
51
+ echo "==> Pushing env server to ${HF_USERNAME}/${ENV_SPACE} …"
52
 
53
  ENV_FRONTMATTER="---
54
  title: CI Triage Env
 
76
 
77
  # ── 2. Training Space (Dockerfile.train β†’ Dockerfile + frontmatter) ──────────
78
  echo ""
79
+ echo "==> Pushing training Space to ${TRAIN_HF_USERNAME}/${TRAIN_SPACE_NAME} …"
80
 
81
  TRAIN_FRONTMATTER="---
82
  title: CI Triage Training
 
100
  git remote remove hf-train 2>/dev/null || true
101
  git remote add hf-train "$HF_TRAIN_REMOTE"
102
  git push hf-train "${TEMP_BRANCH}:main" --force
103
+ echo " βœ“ https://huggingface.co/spaces/${TRAIN_HF_USERNAME}/${TRAIN_SPACE_NAME}"
104
 
105
  # ── Cleanup ───────────────────────────────────────────────────────────────────
106
  git checkout main
 
109
  git remote remove hf-train 2>/dev/null || true
110
 
111
  echo ""
112
+ echo "Both Spaces updated. Docker builds start automatically (~3 min env / ~15 min training)."
113
  echo "Watch build logs:"
114
  echo " https://huggingface.co/spaces/${HF_USERNAME}/${ENV_SPACE}"
115
+ echo " https://huggingface.co/spaces/${TRAIN_HF_USERNAME}/${TRAIN_SPACE_NAME}"
src/ci_triage_env/training/grpo.py CHANGED
@@ -12,7 +12,7 @@ from ci_triage_env.training.sft import load_model_for_sft
12
 
13
  GRPO_HYPERPARAMS: dict = {
14
  "learning_rate": 5e-6,
15
- "kl_coef": 0.04,
16
  "per_device_train_batch_size": 2,
17
  "gradient_accumulation_steps": 1,
18
  "max_prompt_length": 4096,
 
12
 
13
  GRPO_HYPERPARAMS: dict = {
14
  "learning_rate": 5e-6,
15
+ "beta": 0.04, # renamed from kl_coef in newer TRL
16
  "per_device_train_batch_size": 2,
17
  "gradient_accumulation_steps": 1,
18
  "max_prompt_length": 4096,
src/ci_triage_env/training/sft.py CHANGED
@@ -26,11 +26,13 @@ def load_model_for_sft(
26
  import unsloth # noqa: F401 β€” must be first; patches trl/transformers on import
27
  from unsloth import FastLanguageModel # type: ignore[import]
28
 
 
29
  model, tokenizer = FastLanguageModel.from_pretrained(
30
  model_name=model_name,
31
  max_seq_length=max_seq_length,
32
  load_in_4bit=False,
33
  load_in_16bit=True, # bf16 LoRA β€” unsloth's Qwen3 recommendation
 
34
  full_finetuning=False,
35
  )
36
 
 
26
  import unsloth # noqa: F401 β€” must be first; patches trl/transformers on import
27
  from unsloth import FastLanguageModel # type: ignore[import]
28
 
29
+ import torch
30
  model, tokenizer = FastLanguageModel.from_pretrained(
31
  model_name=model_name,
32
  max_seq_length=max_seq_length,
33
  load_in_4bit=False,
34
  load_in_16bit=True, # bf16 LoRA β€” unsloth's Qwen3 recommendation
35
+ dtype=torch.bfloat16, # explicit: prevents Half/BFloat16 mismatch on LoRA checkpoints
36
  full_finetuning=False,
37
  )
38