pushpam14 commited on
Commit
7bef84f
Β·
verified Β·
1 Parent(s): 08ad9c8

Sync TECHNICAL_ARCHITECTURE.md (technical architecture doc + cross-links)

Browse files
Files changed (1) hide show
  1. TECHNICAL_ARCHITECTURE.md +602 -0
TECHNICAL_ARCHITECTURE.md ADDED
@@ -0,0 +1,602 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Technical Architecture & Build Flow
2
+
3
+ > Companion to [`README.md`](README.md) (judge-facing) and [`BLOG.md`](BLOG.md) (writeup). This document is the deep technical reference: every tool, every architectural decision, every dataflow diagram. Use it as interview Q&A material β€” each section answers "what tool, why, and what role does it play".
4
+
5
+ ---
6
+
7
+ ## 1. System overview β€” one diagram
8
+
9
+ ```mermaid
10
+ flowchart TB
11
+ subgraph Dev["πŸ’» Local Dev (laptop)"]
12
+ Code[Python source<br/>server/ Β· models.py Β· client.py Β· inference.py]
13
+ Tests[pytest 28 tests]
14
+ EnvFile[.env<br/>HF_TOKEN, WANDB_API_KEY]
15
+ Code --> Tests
16
+ end
17
+
18
+ subgraph GitHub["πŸ“¦ GitHub"]
19
+ Repo["kumarpushpam17-personal/Hackathon"]
20
+ end
21
+
22
+ subgraph HFSpace["πŸš€ HuggingFace Spaces (CPU runtime)"]
23
+ Docker["Dockerfile β†’ uvicorn"]
24
+ FastAPI["FastAPI + WebSocket<br/>/reset Β· /step Β· /state Β· /docs Β· /health"]
25
+ EnvServer["ValidatorEnvironment<br/>(OpenEnv Environment subclass)"]
26
+ Docker --> FastAPI --> EnvServer
27
+ end
28
+
29
+ subgraph HFJobs["⚑ HuggingFace Jobs (L4 GPU)"]
30
+ Bootstrap["run_in_hf_jobs.py<br/>self-bootstrapping launcher"]
31
+ TrainScript["training/train.py<br/>(GRPO loop)"]
32
+ Bootstrap --> TrainScript
33
+ end
34
+
35
+ subgraph HFHub["πŸ€— HuggingFace Hub"]
36
+ Adapter["pushpam14/api-contract-validator-grpo-7b<br/>(LoRA adapter, 162 MB)"]
37
+ Artifacts["training_artifacts/<br/>reward_curve.png Β· training_state.json"]
38
+ Scores["trained_scores.json"]
39
+ end
40
+
41
+ subgraph WandB["πŸ“Š WandB"]
42
+ Run["openenv-contract-guardian/runs/gch0eg3k<br/>(public, immutable, 300 steps)"]
43
+ end
44
+
45
+ subgraph Inference["πŸ”Œ LLM Providers"]
46
+ Router["HF Router (Inference Providers)<br/>Qwen2.5-72B / 7B baselines"]
47
+ end
48
+
49
+ Dev -->|git push| Repo
50
+ Repo -->|HfApi.upload_folder| HFSpace
51
+ Bootstrap -->|git clone --depth 1| Repo
52
+ TrainScript -->|env grader = reward fn| FastAPI
53
+ TrainScript -->|live metrics| Run
54
+ TrainScript -->|push adapter| Adapter
55
+ TrainScript -->|push results| Artifacts
56
+
57
+ inference[inference.py / run_trained_inference.py] -->|/reset, /step| FastAPI
58
+ inference -->|baseline LLM calls| Router
59
+ inference -->|trained LLM via Unsloth| Adapter
60
+ inference -->|writes| Scores
61
+
62
+ Scores -->|input to| Plot[plot.py]
63
+ Artifacts -->|input to| Plot
64
+ Plot -->|writes| Plots[results/before_after.png<br/>results/reward_curve.png]
65
+ Plots -->|git commit| Repo
66
+ ```
67
+
68
+ ---
69
+
70
+ ## 2. The tech stack β€” tool by tool
71
+
72
+ Every dependency, what it does, and why we chose it.
73
+
74
+ ### Core environment (server side)
75
+
76
+ | Tool | Version | Role | Why this and not alternatives |
77
+ |---|---|---|---|
78
+ | **Python** | 3.10+ | Language | Required by `openenv-core`; broad library support |
79
+ | **`openenv-core[core]`** | β‰₯ 0.2.2 | RL environment framework | Hackathon mandate; provides `Environment` base class, `EnvClient`, FastAPI scaffolding, WebSocket session management |
80
+ | **FastAPI** | latest | HTTP/WebSocket server | Auto-generates OpenAPI schema; required by openenv-core's `create_app` |
81
+ | **Pydantic v2** | β‰₯ 2 | Data models for `Action`, `Observation`, `State` | Required by openenv; provides JSON-schema validation for /step and /reset request bodies |
82
+ | **Uvicorn** | β‰₯ 0.24 | ASGI runtime | Standard for FastAPI; runs in our Dockerfile `CMD` |
83
+ | **Python `logging`** | stdlib | Structured episode logs (JSON to stdout + `logs/episodes.jsonl`) | Built-in, zero dependency; lets `docker logs` show every reset/step |
84
+
85
+ ### Agent / inference side
86
+
87
+ | Tool | Version | Role | Why this and not alternatives |
88
+ |---|---|---|---|
89
+ | **`openai`** (HF router compatible) | β‰₯ 1.0 | LLM client for baselines (Qwen-72B / 7B via HF Inference Providers) | Same API for hosted Qwen models without local GPU; `inference.py` uses `client.chat.completions.create` |
90
+ | **`python-dotenv`** | β‰₯ 1.0 | Load `HF_TOKEN`, `WANDB_API_KEY` from gitignored `.env` | Keeps secrets out of git; auto-loaded at script start |
91
+ | **`huggingface_hub`** | β‰₯ 1.0 | File upload (Space deploy, adapter push, artifact push), file download (pull plots back from adapter repo) | Official HF SDK; used by `HfApi.upload_folder`, `upload_file`, `hf_hub_download` |
92
+
93
+ ### Training pipeline
94
+
95
+ | Tool | Version | Role | Why this and not alternatives |
96
+ |---|---|---|---|
97
+ | **`trl`** | β‰₯ 0.13 | `GRPOTrainer` + `GRPOConfig` for the GRPO algorithm | Hackathon mandate; HF's official RL trainer with first-class GRPO support |
98
+ | **`unsloth`** | latest | 4-bit model loading + 2Γ— faster LoRA fine-tuning + memory offload | Lets us fit Qwen-7B on a 24 GB L4; 4-bit + LoRA r=16 = trainable params drop from 7.6 B to 40 M |
99
+ | **`torch`** | β‰₯ 2.0 | Backend for unsloth + trl | Mandatory dep for both |
100
+ | **`bitsandbytes`** | latest | Underlying 4-bit quantization | Required by Unsloth for `load_in_4bit=True` |
101
+ | **`xformers`** | latest | Memory-efficient attention | Auto-installed by Unsloth; falls back to vanilla on T4 |
102
+ | **`peft`** | (transitive) | LoRA adapter creation/serialization | Used by Unsloth's `get_peft_model`; produces the 162 MB `adapter_model.safetensors` |
103
+ | **`datasets`** | latest | `Dataset.from_list` for the GRPO prompt dataset | Required by `GRPOTrainer.train_dataset` |
104
+ | **`wandb`** | β‰₯ 0.16 | Experimental tracking β€” every step's reward, loss, KL, gradient norm | Public dashboard for judges; immutable history; required for the "evidence of training" criterion |
105
+
106
+ ### Plotting & analysis
107
+
108
+ | Tool | Version | Role |
109
+ |---|---|---|
110
+ | **`matplotlib`** | β‰₯ 3.10 | `reward_curve.png` (training metrics) + `before_after.png` (3-bar baseline-vs-trained) |
111
+ | **`numpy`** | β‰₯ 1.24 | Bar-chart x-axis math in `plot.py` |
112
+
113
+ ### Hosting & infrastructure
114
+
115
+ | Service | Role | Why |
116
+ |---|---|---|
117
+ | **HuggingFace Spaces** | Hosts the live OpenEnv server (CPU basic, free tier) | Required by hackathon; one-click deploy via `HfApi.upload_folder`; auto-builds Docker image; gives a public `*.hf.space` endpoint |
118
+ | **HuggingFace Hub** | Hosts trained adapter + training artifacts (reward_curve.png, training_state.json, trained_scores.json) | Free for public models; `HfApi.upload_file` from inside the training job |
119
+ | **HuggingFace Jobs** | On-demand cloud GPU runtime (used L4 24 GB at $0.80/hr) | Faster + more reliable than Colab Free; doesn't time out; supports inline PEP-723 dependency declarations via `hf jobs uv run` |
120
+ | **HF Inference Providers (router)** | Serverless inference for Qwen2.5-72B / 7B baselines | Free tier covers ~9 tasks of ~10 calls each; no GPU needed for baselines |
121
+ | **WandB** | Public, immutable experiment tracking | Free; satisfies "experimental tracking turned on" requirement; URL: `wandb.ai/.../runs/gch0eg3k` |
122
+ | **Docker** | Containerization for the OpenEnv server | Required by HF Spaces (`sdk: docker` in README frontmatter); reproducible build |
123
+ | **GitHub** | Source-of-truth + the URL the HF Job clones from | Public, free; supports raw-content URLs for plot embeds |
124
+ | **`uv` (PyPI installer used in HF Jobs)** | Fast Python dep installer (~500 ms for 177 packages) | Default tool for `hf jobs uv run`; PEP-723 inline deps make our launcher self-contained |
125
+
126
+ ### Local development
127
+
128
+ | Tool | Role |
129
+ |---|---|
130
+ | **pytest** | 28-test suite across all 9 tasks (Phase 1 + Phase 2 + Phase 3 + cascade) |
131
+ | **`openenv` CLI** | `openenv validate` β€” confirms our env meets the OpenEnv spec |
132
+ | **`hf` CLI** | `hf jobs uv run`, `hf jobs logs --follow`, `hf jobs inspect`, `hf auth login` |
133
+ | **`huggingface-cli` CLI** | `huggingface-cli whoami`, alternative login |
134
+ | **Git** | Version control |
135
+
136
+ ---
137
+
138
+ ## 3. Build flow β€” step by step
139
+
140
+ The order in which the project was actually constructed.
141
+
142
+ ```mermaid
143
+ flowchart LR
144
+ A[1. Pydantic models<br/>Action / Obs / State] --> B[2. spec_generator.py<br/>Phase 1 task scenarios]
145
+ B --> C[3. environment.py<br/>reset / step / state]
146
+ C --> D[4. rewards.py<br/>composable Rubric]
147
+ D --> E[5. app.py<br/>FastAPI wiring]
148
+ E --> F[6. client.py<br/>EnvClient subclass]
149
+ F --> G[7. inference.py<br/>baseline runner]
150
+ G --> H[8. tests/<br/>28 tests]
151
+ H --> I[9. Phase 2/3<br/>service_graph + impact_tracer + fix_validator]
152
+ I --> J[10. Dockerfile<br/>containerize]
153
+ J --> K[11. HF Space deploy<br/>upload_folder]
154
+ K --> L[12. baseline runner<br/>72B + 7B at temp 0.7]
155
+ L --> M[13. training/train.py<br/>GRPO + LoRA + Unsloth]
156
+ M --> N[14. run_in_hf_jobs.py<br/>self-bootstrapping launcher]
157
+ N --> O[15. Submit HF Job<br/>L4, 300 steps]
158
+ O --> P[16. Push adapter +<br/>plots to HF Hub]
159
+ P --> Q[17. run_trained_inference.py<br/>per-task scores]
160
+ Q --> R[18. plot.py<br/>3-way before_after.png]
161
+ R --> S[19. README + BLOG<br/>+ STORY + this doc]
162
+ S --> T[20. Sync everything<br/>to HF Space + GitHub]
163
+ ```
164
+
165
+ ---
166
+
167
+ ## 4. Runtime architecture β€” what happens at /reset and /step
168
+
169
+ ### Reset sequence (one episode start)
170
+
171
+ ```mermaid
172
+ sequenceDiagram
173
+ participant Client as Agent / Judge curl
174
+ participant FastAPI
175
+ participant Env as ValidatorEnvironment
176
+ participant Gen as spec_generator.py / service_graph.py
177
+
178
+ Client->>FastAPI: POST /reset {task_name, seed}
179
+ FastAPI->>Env: env.reset(task_name, seed, episode_id)
180
+ alt Phase 1 task
181
+ Env->>Gen: generate_scenario_for_task(task, seed)
182
+ Gen-->>Env: TaskScenario (api_spec + payload + planted violations)
183
+ else Phase 2/3 task
184
+ Env->>Gen: get_cascade_scenario(seed)
185
+ Gen-->>Env: CascadeScenario (producer specs + consumers + ground truth)
186
+ end
187
+ Env->>Env: log episode_start (JSON to stdout)
188
+ Env-->>FastAPI: ValidatorObservation
189
+ FastAPI-->>Client: 200 OK + JSON observation
190
+ ```
191
+
192
+ ### Step sequence (one agent action)
193
+
194
+ ```mermaid
195
+ sequenceDiagram
196
+ participant Client as Agent
197
+ participant FastAPI
198
+ participant Env as ValidatorEnvironment
199
+ participant Grader as rewards.py + impact_tracer + fix_validator
200
+
201
+ Client->>FastAPI: POST /step {action: ValidatorAction}
202
+ FastAPI->>Env: env.step(action)
203
+ Env->>Env: dispatch by action.action_type
204
+ alt action_type=report_violation
205
+ Env->>Grader: compute_step_reward (Phase 1 rubric)
206
+ else action_type=trace_impact
207
+ Env->>Grader: trace_impact() + phase2_trace_rubric
208
+ else action_type=propose_fix / validate_fix
209
+ Env->>Grader: validate_fix() + phase3_fix_rubric
210
+ end
211
+ Grader-->>Env: RewardBreakdown / Rubric
212
+ Env->>Env: log step (JSON), update state, check done
213
+ Env-->>FastAPI: ValidatorObservation (reward, done, feedback)
214
+ FastAPI-->>Client: 200 OK
215
+ ```
216
+
217
+ ### What lives where in the server
218
+
219
+ ```
220
+ api_contract_validator/server/
221
+ β”œβ”€β”€ app.py FastAPI wiring (create_app + landing page + OpenAPI patcher)
222
+ β”œβ”€β”€ environment.py reset/step/state dispatch by phase
223
+ β”œβ”€β”€ logging_setup.py JSON logger config
224
+ β”œβ”€β”€ spec_generator.py Phase 1 β€” 6 detection task generators with planted violations
225
+ β”œβ”€β”€ service_graph.py Phase 2/3 β€” 2 cascade scenarios with producer + consumers
226
+ β”œβ”€β”€ impact_tracer.py Phase 2 β€” precision/recall/F1 grader
227
+ β”œβ”€β”€ fix_validator.py Phase 3 β€” 5-strategy backward-compat verification
228
+ └── rewards.py Composable Rubric API + 14 independent reward signals
229
+ ```
230
+
231
+ ---
232
+
233
+ ## 5. Training pipeline architecture β€” GRPO with env-as-grader
234
+
235
+ ```mermaid
236
+ flowchart LR
237
+ subgraph Setup["Setup (once per job)"]
238
+ A1[hf jobs uv run] --> A2[uv resolves<br/>177 packages]
239
+ A2 --> A3[git clone repo<br/>via run_in_hf_jobs.py]
240
+ A3 --> A4[load Qwen-7B-4bit<br/>via Unsloth]
241
+ A4 --> A5[wrap with LoRA r=16<br/>40 M trainable params]
242
+ A5 --> A6[build dataset<br/>50 prompts Γ— 6 tasks]
243
+ end
244
+
245
+ subgraph Loop["GRPO loop (300 steps)"]
246
+ B1[Sample batch of prompts] --> B2[Generate 4 completions per prompt<br/>via model.generate]
247
+ B2 --> B3[Parse JSON action<br/>via parse_llm_response]
248
+ B3 --> B4[Open fresh WebSocket<br/>per reward_fn call]
249
+ B4 --> B5[reset + step on HF Space env<br/>env grader returns reward]
250
+ B5 --> B6[GRPO ranks completions<br/>by reward, updates LoRA]
251
+ B6 --> B7[Log metrics to WandB<br/>reward, loss, KL, grad_norm]
252
+ B7 --> B1
253
+ end
254
+
255
+ subgraph Output["After 300 steps"]
256
+ C1[matplotlib<br/>plot reward_curve.png]
257
+ C2[push adapter<br/>HfApi.upload_folder]
258
+ C3[push reward_curve +<br/>training_state.json<br/>HfApi.upload_file]
259
+ C4[os._exit 0<br/>clean exit]
260
+ C1 --> C2 --> C3 --> C4
261
+ end
262
+
263
+ Setup --> Loop --> Output
264
+ ```
265
+
266
+ ### Why per-call WebSocket (not persistent)
267
+
268
+ HF Spaces drops idle WebSockets after ~30s. GRPO's pause between batches (model gen + backprop) is longer than that. Sharing one persistent WebSocket made every batch after the first fail with `1011 keepalive timeout`. The fix in `train.py` β€” open a fresh `ValidatorEnv` inside each `reward_fn` invocation, close at end. ~50 ms overhead per batch, eliminates the failure mode.
269
+
270
+ ### Why fp16 (not bf16)
271
+
272
+ L4 supports both, but Unsloth's gradient-checkpointed fast-LoRA kernel mixes fp16 (Half) and fp32 (Float) under bf16 autocast β†’ `addmm_` dtype mismatch β†’ crash. We forced fp16 globally; works on both T4 and L4 cleanly.
273
+
274
+ ### Why GRPO (not SFT or DPO)
275
+
276
+ We have a *verifiable environment grader*, not labeled (prompt, ideal_action) pairs. SFT would require us to manually label correct answers β€” throwing away the env's role as the source of truth. GRPO ranks multiple completions per prompt and pushes toward the higher-reward ones. That's exactly what our 14-component rubric provides.
277
+
278
+ ---
279
+
280
+ ## 6. Deployment architecture
281
+
282
+ ```mermaid
283
+ flowchart TB
284
+ subgraph Local["Laptop"]
285
+ Source[Python source]
286
+ Tests[pytest]
287
+ Source --> Tests
288
+ Tests -->|βœ… 28/28| Push
289
+ end
290
+
291
+ Push[git push] --> GitHub[(GitHub repo)]
292
+
293
+ subgraph HFSpaceCI["HF Spaces (build pipeline)"]
294
+ SpaceUpload[HfApi.upload_folder]
295
+ DockerBuild[HF builds Dockerfile]
296
+ DockerRun[Container starts:<br/>uvicorn server.app:app --port 7860]
297
+ SpaceUpload --> DockerBuild --> DockerRun
298
+ end
299
+
300
+ GitHub -.->|judges browse| GitHub
301
+ Source -->|HfApi.upload_folder<br/>from laptop| SpaceUpload
302
+
303
+ DockerRun --> Live["Live env at<br/>pushpam14-api-contract-validator.hf.space"]
304
+
305
+ subgraph HFJob["HF Jobs (training, ephemeral)"]
306
+ JobStart[hf jobs uv run --flavor l4x1]
307
+ JobClone[run_in_hf_jobs.py:<br/>git clone repo from GitHub]
308
+ JobTrain[training/train.py<br/>connects to Live env<br/>via ValidatorEnv WebSocket]
309
+ JobStart --> JobClone --> JobTrain
310
+ end
311
+
312
+ JobTrain -->|/reset, /step| Live
313
+ JobTrain -->|push adapter| Hub[HF Hub adapter repo]
314
+ JobTrain -->|metrics| WandB[(WandB)]
315
+ ```
316
+
317
+ ### Why HF Jobs over Colab
318
+
319
+ | Factor | Colab Free | HF Jobs |
320
+ |---|---|---|
321
+ | Disconnects mid-run | After 3 hours / idle | No |
322
+ | GPU options | T4 only (16 GB) | t4 / l4 / a10g / a100 / h100 |
323
+ | Reproducibility for judges | Manual upload + auth | One CLI command, fully scripted |
324
+ | Cost on $30 hackathon credit | Free but unreliable | ~$2.40 for our main run |
325
+ | WandB / HF auth | Manual paste | `-s WANDB_API_KEY -s HF_TOKEN` flags |
326
+
327
+ For a 2-hour 7B+LoRA run, HF Jobs is strictly better. Colab is in our docs as a fallback.
328
+
329
+ ---
330
+
331
+ ## 7. Per-phase data flow diagrams
332
+
333
+ ### Phase 1 β€” Detection (find_type_mismatches example)
334
+
335
+ ```mermaid
336
+ sequenceDiagram
337
+ participant Agent as LLM
338
+ participant Env
339
+ participant Specgen as spec_generator
340
+ participant Rubric as rewards.py
341
+
342
+ Agent->>Env: reset(find_type_mismatches, seed=42)
343
+ Env->>Specgen: generate_easy_scenario(seed=42)
344
+ Specgen->>Specgen: sample 4 from pool of 12 violations
345
+ Specgen-->>Env: api_spec + payload + 4 PlantedViolations
346
+ Env-->>Agent: obs (api_spec + payload visible, violations hidden)
347
+
348
+ loop Up to 10 steps
349
+ Agent->>Env: step({field_path, violation_type})
350
+ Env->>Env: _find_matching_violation (path AND type)
351
+ alt full match (path + type)
352
+ Env->>Rubric: compute_step_reward(is_correct=True)
353
+ Rubric-->>Env: +1.0
354
+ else proximity (path only)
355
+ Env->>Rubric: compute_step_reward(is_path_match=True)
356
+ Rubric-->>Env: +0.3
357
+ else duplicate
358
+ Rubric-->>Env: -0.1
359
+ else false positive
360
+ Rubric-->>Env: -0.3
361
+ end
362
+ Env-->>Agent: obs (reward + violations_remaining update)
363
+ end
364
+
365
+ Agent->>Env: step({field_path: "DONE"})
366
+ Env-->>Agent: obs (done=True, score = correct/total)
367
+ ```
368
+
369
+ ### Phase 2 β€” Impact tracing (trace_downstream_blast_radius)
370
+
371
+ ```mermaid
372
+ sequenceDiagram
373
+ participant Agent as LLM
374
+ participant Env
375
+ participant Sg as service_graph
376
+ participant Tr as impact_tracer
377
+ participant Ru as rewards.py
378
+
379
+ Agent->>Env: reset(trace_downstream_blast_radius, seed=1)
380
+ Env->>Sg: get_cascade_scenario(seed=1)
381
+ Sg-->>Env: CascadeScenario (UserService email rename + 4 consumers)
382
+ Env-->>Agent: obs<br/>(public_observation = producer specs +<br/>consumer declarations; ground_truth_affected hidden)
383
+
384
+ Agent->>Env: step({action_type: trace_impact,<br/>affected_services: [Orders, Billing, Notifications]})
385
+ Env->>Tr: trace_impact(scenario, predicted)
386
+ Tr->>Tr: compute hits / missed / false_flags / unknown
387
+ Tr-->>Env: ImpactTraceResult
388
+ Env->>Ru: phase2_trace_rubric(result)
389
+ Ru-->>Env: Rubric (per-consumer signals)
390
+ Env-->>Agent: obs (reward = sum(rubric), done=true if perfect or steps exhausted)
391
+ ```
392
+
393
+ ### Phase 3 β€” Fix proposal (propose_backward_compat_fix)
394
+
395
+ ```mermaid
396
+ sequenceDiagram
397
+ participant Agent as LLM
398
+ participant Env
399
+ participant Sg as service_graph
400
+ participant Fv as fix_validator
401
+ participant Ru as rewards.py
402
+
403
+ Agent->>Env: reset(propose_backward_compat_fix, seed=1)
404
+ Env->>Sg: get_cascade_scenario(seed=1)
405
+ Sg-->>Env: CascadeScenario + acceptable_fix_strategies
406
+ Env-->>Agent: obs (detected_violation + consumer_specs visible)
407
+
408
+ Agent->>Env: step({action_type: propose_fix,<br/>fix_strategy: field_alias,<br/>spec_patch: {aliases: {email: email_address}}})
409
+ Env->>Fv: validate_fix(scenario, strategy, patch)
410
+ loop per consumer
411
+ Fv->>Fv: _STRATEGY_CHECKERS[strategy](consumer)
412
+ end
413
+ Fv-->>Env: FixValidationResult (passing / failing / reasons)
414
+ Env->>Ru: phase3_fix_rubric(result)
415
+ Ru-->>Env: Rubric (+2.0 if all_consumers_pass else -1.0 per failure)
416
+ Env-->>Agent: obs (reward, fix_validation_results, done if accepted)
417
+ ```
418
+
419
+ ---
420
+
421
+ ## 8. Why each tool? (decision log for interview Q&A)
422
+
423
+ ### Q: "Why OpenEnv and not roll your own RL framework?"
424
+
425
+ OpenEnv is the hackathon's mandate β€” but beyond compliance, it provides:
426
+ - A standard `Environment` base class with `reset` / `step` / `state` contract
427
+ - `EnvClient` with WebSocket session management out of the box
428
+ - FastAPI scaffolding via `create_app` so we get `/reset`, `/step`, `/state`, `/health`, `/docs`, `/ws` endpoints free
429
+ - Pydantic-typed Action/Observation/State models that auto-generate OpenAPI schema
430
+ - Compatibility with the hackathon's expected eval harness
431
+
432
+ Saved ~2 weeks of plumbing.
433
+
434
+ ### Q: "Why Unsloth?"
435
+
436
+ Three reasons:
437
+ 1. **2Γ— faster LoRA fine-tuning** vs vanilla transformers β€” critical for our 2-hour onsite training window
438
+ 2. **4-bit quantization** drops Qwen-7B from ~14 GB to ~5 GB VRAM, so it fits on a 24 GB L4 with room for activations and KV cache
439
+ 3. **Smart gradient offloading** β€” Unsloth swaps cold gradients to CPU, lets us train without OOM
440
+
441
+ Cost: an unsloth-specific bug (bf16 + LoRA dtype mismatch) cost us one re-run iteration. Documented in [`training/train.py`](training/train.py) comments.
442
+
443
+ ### Q: "Why TRL's GRPOTrainer specifically and not PPO?"
444
+
445
+ GRPO (Group Relative Policy Optimization) compares N completions per prompt and ranks them by reward β€” no value function needed. For our setup that's a perfect fit:
446
+ - We sample `num_generations=4` per prompt, env grades each, GRPO promotes the highest
447
+ - No reward-model bootstrap (the env IS the reward)
448
+ - Simpler than PPO; trains faster on small LoRA
449
+
450
+ PPO would also work but adds a value head we don't need.
451
+
452
+ ### Q: "Why GRPO instead of SFT on a labeled dataset?"
453
+
454
+ We don't have labeled (prompt, ideal_action) pairs. We have an *environment* with a verifiable grader. SFT would require us to hand-label correct violations / fixes β€” throwing away the env's role as the source of truth. GRPO uses the env's grader directly as the reward function, which:
455
+ - Lets the agent explore action variants
456
+ - Is grounded in actual env behavior, not human-labeled "right answers"
457
+ - Matches the hackathon's "training script connects to your environment" requirement
458
+
459
+ ### Q: "Why composable rubric instead of one monolithic reward?"
460
+
461
+ `final_docs/help_guide.md` Β§7 explicitly recommends composable rubrics. Practical reasons:
462
+ - **Hard to game**: an agent that maximizes one signal (e.g. "spam reports") burns another (the spam penalty)
463
+ - **Per-component logging**: we can see which signal drove training; if reward goes up but `consumer_correct` stays flat we'd know the model is gaming
464
+ - **14 signals across 3 phases**: rich gradient even when partial progress is made
465
+
466
+ ### Q: "Why HuggingFace Spaces for hosting?"
467
+
468
+ Hackathon mandate. Beyond that:
469
+ - Free CPU runtime for our env (we don't need GPU at serving time)
470
+ - Auto-builds Docker on push
471
+ - Public URL judges can hit directly: `pushpam14-api-contract-validator.hf.space`
472
+ - Repo browser at `huggingface.co/spaces/pushpam14/api-contract-validator` for file inspection
473
+
474
+ ### Q: "Why HF Jobs over Colab?"
475
+
476
+ Reliability. Colab disconnects mid-run; HF Jobs doesn't. Plus HF Jobs supports L4 / A10G / A100 / H100 (Colab Free is T4-only). For a 7B model + LoRA, L4 is the sweet spot β€” Qwen-7B with 4-bit quantization fits with room to spare, ~$2.40 for the full 300-step run.
477
+
478
+ ### Q: "Why log to WandB AND keep training_state.json AND keep training_full_log.txt?"
479
+
480
+ Three tiers of evidence in case any one fails or is questioned:
481
+ - **WandB** (canonical, immutable, public) β€” cannot be edited
482
+ - **training_state.json** (git-committed, parseable) β€” proves the data WandB has
483
+ - **training_full_log.txt** (git-committed, raw) β€” proves what the job actually printed
484
+
485
+ Different judges will trust different artifacts. We have all three.
486
+
487
+ ### Q: "Why a self-bootstrapping launcher (run_in_hf_jobs.py) instead of submitting train.py directly?"
488
+
489
+ `hf jobs uv run` uploads exactly one file. Our `train.py` imports from sibling modules (`inference.py`, `client.py`, `models.py`, `server/*`). A single-file submission would `ImportError` on first import. The launcher:
490
+ 1. Declares all heavy training deps via PEP-723 inline metadata so `uv` resolves them in one shot
491
+ 2. `git clone --depth 1` from GitHub
492
+ 3. Adds the package to `sys.path`
493
+ 4. Calls `training.train.main()`
494
+
495
+ 5 KB of glue, eliminates an entire class of "missing module" failures.
496
+
497
+ ---
498
+
499
+ ## 9. Engineering decisions worth highlighting
500
+
501
+ These are the non-obvious calls we made that paid off (or that we'd defend in code review).
502
+
503
+ ### Three-bar before/after comparison instead of two-bar
504
+
505
+ The "before" used to be Qwen-72B (10Γ— larger than the trained model β€” confounded by size). We re-baselined with untrained Qwen-7B (same base as the trained adapter). The 7B-vs-7B+LoRA comparison **isolates the GRPO training effect from model-size effects**. The headline `0.01 β†’ 0.67` only became defensible after this re-baselining.
506
+
507
+ ### Rewards table at the start, training at the end
508
+
509
+ We froze the reward function design before training. If we had iterated on rewards mid-training, the WandB curve wouldn't be apples-to-apples across runs.
510
+
511
+ ### `os._exit(0)` after `[INFO] done.`
512
+
513
+ The `websockets` library emits a non-zero exit code from its `__del__` finalizer when the event loop has been closed. HF Jobs sees that and marks the run ERROR. Calling `os._exit(0)` after our last log line bypasses interpreter shutdown finalizers entirely. The training itself was unchanged; only the badge in HF Jobs UI was misleading.
514
+
515
+ ### `TEMPERATURE=0.7` for sampling-fair comparison
516
+
517
+ Original `inference.py` used `temperature=0.2` (deterministic). The trained model would find 2-3 violations confidently, then loop on duplicates. We made TEMPERATURE env-configurable and re-ran all baselines + trained inference at 0.7. Same temperature for all three columns of the comparison; any difference is now purely model + training, not sampling.
518
+
519
+ ### Score recomputation from rewards (worked around `env.state()` bug)
520
+
521
+ `SUPPORTS_CONCURRENT_SESSIONS=True` means each request gets its own env instance; `await env.state()` after a sequence of `step()` calls hits a fresh instance and returns default `score=0.01`. We computed final scores from the per-step rewards trajectory (`details[*].rewards`) which is the ground truth.
522
+
523
+ ---
524
+
525
+ ## 10. Reproducibility checklist
526
+
527
+ Anyone can verify our claims with these commands.
528
+
529
+ ### Verify the Space is live
530
+
531
+ ```bash
532
+ curl https://pushpam14-api-contract-validator.hf.space/health
533
+ # expected: {"status":"healthy"}
534
+
535
+ curl -X POST https://pushpam14-api-contract-validator.hf.space/reset \
536
+ -H "Content-Type: application/json" \
537
+ -d '{"task_name":"trace_downstream_blast_radius","seed":1}'
538
+ # expected: 200 OK with phase=tracing observation
539
+ ```
540
+
541
+ ### Verify the trained adapter exists
542
+
543
+ ```bash
544
+ curl -sI https://huggingface.co/pushpam14/api-contract-validator-grpo-7b/resolve/main/adapter_model.safetensors | grep -i content-length
545
+ # expected: content-length: 162175520
546
+ ```
547
+
548
+ ### Verify the WandB run is real
549
+
550
+ Open https://wandb.ai/pushpamsubscriptions-inn/openenv-contract-guardian/runs/gch0eg3k β€” should show 300-step reward / loss / grad_norm / kl curves with timestamps from 2026-04-25 18:57.
551
+
552
+ ### Re-run inference
553
+
554
+ ```bash
555
+ git clone https://github.com/kumarpushpam17-personal/Hackathon
556
+ cd Hackathon/api_contract_validator
557
+ cp .env.example .env
558
+ # Edit .env with your own HF_TOKEN
559
+ pip install -e .
560
+ docker build -t api-contract-validator .
561
+ docker run -d -p 7860:7860 --name eg-env api-contract-validator
562
+ python inference.py
563
+ # Writes baseline scores at default Qwen-72B; or set MODEL_NAME=Qwen/Qwen2.5-7B-Instruct
564
+ ```
565
+
566
+ ### Re-run training
567
+
568
+ ```bash
569
+ hf jobs uv run \
570
+ --flavor l4x1 \
571
+ -s HF_TOKEN -s WANDB_API_KEY \
572
+ -e BASE_MODEL=unsloth/Qwen2.5-7B-Instruct-bnb-4bit \
573
+ -e ENV_URL=https://pushpam14-api-contract-validator.hf.space \
574
+ -e MAX_STEPS=300 \
575
+ -e PUSH_TO_HUB=YOUR_USERNAME/your-adapter-name \
576
+ api_contract_validator/training/run_in_hf_jobs.py
577
+ ```
578
+
579
+ ### Run tests
580
+
581
+ ```bash
582
+ PYTHONPATH=api_contract_validator python3 -m pytest api_contract_validator/tests/ -v
583
+ # expected: 28 passed
584
+ ```
585
+
586
+ ### Validate the env contract
587
+
588
+ ```bash
589
+ cd api_contract_validator
590
+ openenv validate
591
+ # expected: [OK] api_contract_validator: Ready for multi-mode deployment
592
+ ```
593
+
594
+ ---
595
+
596
+ ## See also
597
+
598
+ - [`README.md`](README.md) β€” judge-facing overview, quick links, results table
599
+ - [`BLOG.md`](BLOG.md) β€” public mini-blog writeup
600
+ - [`ENTERPRISE_CONTRACT_GUARDIAN_STORY.md`](ENTERPRISE_CONTRACT_GUARDIAN_STORY.md) β€” product narrative, two worked incident examples, episode lifecycle
601
+ - [`results/TRAINING_RUN_PROOF.md`](results/TRAINING_RUN_PROOF.md) β€” proof that the training run actually succeeded (the HF Jobs UI ERROR badge is a websockets-shutdown red herring)
602
+ - [`training/README.md`](training/README.md) β€” three ways to run the training pipeline (HF Jobs / Colab / local)