heavycoderhh commited on
Commit
47e723a
·
verified ·
1 Parent(s): 182b6e5

Promote Qwen3 8B QLoRA SFT run4b

Browse files
BENCHMARKS.md CHANGED
@@ -7,10 +7,10 @@ Held-out evaluation uses 30 deterministic seeds and four fixed policies. The goa
7
  | random | 30 | 0.000 | 0.000 | 0.000 | 0.000 | Vague questions and early evidence do not score. |
8
  | keyword_spam | 30 | 0.073 | 0.000 | 0.678 | 0.000 | Trigger words alone cannot earn primary reward. |
9
  | present_all | 30 | 0.000 | 0.000 | 0.000 | 0.000 | Blind evidence dumping fails because timing matters. |
10
- | trained_sft_grpo_run3 | 30 | 0.615 | 0.689 | 0.728 | 0.689 | Assistant-only SFT + GRPO improves evidence timing and reduces duplicate loops. |
11
  | scripted_oracle | 30 | 0.902 | 0.950 | 0.950 | 0.950 | The desired strategy is trigger first, evidence second. |
12
 
13
- The trained checkpoint is published at `heavycoderhh/counsel-env-qwen3-0.6b-grpo-run3`. Evaluation artifacts are in the model repo under `eval/`.
14
 
15
  ## Anti-Hacking Checks
16
 
 
7
  | random | 30 | 0.000 | 0.000 | 0.000 | 0.000 | Vague questions and early evidence do not score. |
8
  | keyword_spam | 30 | 0.073 | 0.000 | 0.678 | 0.000 | Trigger words alone cannot earn primary reward. |
9
  | present_all | 30 | 0.000 | 0.000 | 0.000 | 0.000 | Blind evidence dumping fails because timing matters. |
10
+ | trained_qwen3_8b_qlora_sft_run4b | 30 | 0.860 | 0.928 | 0.928 | 0.928 | Qwen3-8B QLoRA SFT learns the trigger-then-evidence loop reliably. |
11
  | scripted_oracle | 30 | 0.902 | 0.950 | 0.950 | 0.950 | The desired strategy is trigger first, evidence second. |
12
 
13
+ The trained checkpoint is published at `heavycoderhh/counsel-env-qwen3-8b-qlora-sft-run4b`. Evaluation artifacts are in the model repo under `eval/`, with a local mirror at `assets/trained_eval_run4b_8b_sft/eval/`.
14
 
15
  ## Anti-Hacking Checks
16
 
DEMO_SCRIPT.md CHANGED
@@ -18,7 +18,7 @@ Open `/demo`. Reset an easy case, ask the hinted trigger question, then present
18
 
19
  ## 75-90s: Why It Matters
20
 
21
- This is a compact theory-of-mind task for RL: the agent must reason over another actor's commitments under a budget. The published run-3 checkpoint is not oracle-level, but it beats the reward-hacking baselines by learning the trigger-then-evidence loop on held-out cases.
22
 
23
  ## Shot List
24
 
 
18
 
19
  ## 75-90s: Why It Matters
20
 
21
+ This is a compact theory-of-mind task: the agent must reason over another actor's commitments under a budget. The published Qwen3-8B QLoRA SFT checkpoint is close to the scripted oracle ceiling and beats the reward-hacking baselines by learning the trigger-then-evidence loop on held-out cases.
22
 
23
  ## Shot List
24
 
README.md CHANGED
@@ -122,12 +122,12 @@ The local evaluator compares four baselines:
122
  | random | 0.000 | 0.000 | 0.000 | 0.000 |
123
  | keyword_spam | 0.073 | 0.000 | 0.678 | 0.000 |
124
  | present_all | 0.000 | 0.000 | 0.000 | 0.000 |
125
- | trained_sft_grpo_run3 | 0.615 | 0.689 | 0.728 | 0.689 |
126
  | scripted_oracle | 0.902 | 0.950 | 0.950 | 0.950 |
127
 
128
  This shows the obvious hacks do not get primary reward: keyword spam can trigger claims, and present-all can burn exhibits, but neither surfaces contradictions.
129
 
130
- The trained run-3 checkpoint (`heavycoderhh/counsel-env-qwen3-0.6b-grpo-run3`) uses the run-2 checkpoint as a base, assistant-only oracle SFT, and GRPO refinement with stronger duplicate-loop penalties. It surfaces contradictions on held-out cases more reliably than run 2, while the first 200-step GRPO-only checkpoint learned mostly to ask a trigger question without presenting evidence.
131
 
132
  The same benchmark table is embedded in the live demo so judges can see the failure modes without cloning the repo.
133
 
@@ -165,7 +165,7 @@ python -m pytest -p no:cacheprovider -q
165
  Latest local result:
166
 
167
  ```text
168
- 20 passed
169
  ```
170
 
171
  The preflight also checks local FastAPI + WebSocket reset/step/state, Docker-style imports, notebook credit guards, rollout diagnostics, and held-out evaluation artifacts.
@@ -222,6 +222,22 @@ Tiny approved dry-run mode:
222
  RUN_TRAINING=1 COUNSEL_MODEL=Qwen/Qwen3-0.6B COUNSEL_MAX_STEPS=5 COUNSEL_DATASET_SIZE=12
223
  ```
224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  The current Space deployment does not start a paid GPU job. Before running remote training, approve the spend. Estimated costs:
226
 
227
  - A10G dry run: about `$0.50`
@@ -230,13 +246,13 @@ The current Space deployment does not start a paid GPU job. Before running remot
230
  Published training artifact:
231
 
232
  ```text
233
- https://huggingface.co/heavycoderhh/counsel-env-qwen3-0.6b-grpo-run3
234
  ```
235
 
236
  Held-out evaluation artifacts are in:
237
 
238
  ```text
239
- https://huggingface.co/heavycoderhh/counsel-env-qwen3-0.6b-grpo-run3/tree/main/eval
240
  ```
241
 
242
  The same trained eval files are mirrored locally for offline review:
@@ -250,6 +266,11 @@ assets/trained_eval_run3/trained_eval_rows.csv
250
  assets/trained_eval_run3/trained_eval_rows.jsonl
251
  assets/trained_eval_run3/trained_eval_summary.json
252
  assets/trained_eval_run3/trained_eval_transcripts.md
 
 
 
 
 
253
  ```
254
 
255
  ## Run Server Locally
@@ -281,4 +302,4 @@ Future work: self-play witness training, civil deposition templates, jurisdictio
281
 
282
  ## Status
283
 
284
- The Hugging Face Space is deployed on free `cpu-basic` hardware with the live demo and OpenEnv API. Local validation passes. A trained SFT+GRPO checkpoint and held-out evaluation are published on Hugging Face, and the final video/blog scripts are prepared under `assets/demo/`.
 
122
  | random | 0.000 | 0.000 | 0.000 | 0.000 |
123
  | keyword_spam | 0.073 | 0.000 | 0.678 | 0.000 |
124
  | present_all | 0.000 | 0.000 | 0.000 | 0.000 |
125
+ | trained_qwen3_8b_qlora_sft_run4b | 0.860 | 0.928 | 0.928 | 0.928 |
126
  | scripted_oracle | 0.902 | 0.950 | 0.950 | 0.950 |
127
 
128
  This shows the obvious hacks do not get primary reward: keyword spam can trigger claims, and present-all can burn exhibits, but neither surfaces contradictions.
129
 
130
+ The trained run4b checkpoint (`heavycoderhh/counsel-env-qwen3-8b-qlora-sft-run4b`) uses `Qwen/Qwen3-8B` with 4-bit QLoRA SFT and assistant-only oracle next-action labels. It surfaces contradictions on held-out cases much more reliably than run 3, while staying below the scripted oracle ceiling.
131
 
132
  The same benchmark table is embedded in the live demo so judges can see the failure modes without cloning the repo.
133
 
 
165
  Latest local result:
166
 
167
  ```text
168
+ 21 passed
169
  ```
170
 
171
  The preflight also checks local FastAPI + WebSocket reset/step/state, Docker-style imports, notebook credit guards, rollout diagnostics, and held-out evaluation artifacts.
 
222
  RUN_TRAINING=1 COUNSEL_MODEL=Qwen/Qwen3-0.6B COUNSEL_MAX_STEPS=5 COUNSEL_DATASET_SIZE=12
223
  ```
224
 
225
+ Fast 8B QLoRA SFT path used for the current best checkpoint:
226
+
227
+ ```bash
228
+ COUNSEL_MODEL=Qwen/Qwen3-8B \
229
+ COUNSEL_ARTIFACT_REPO=heavycoderhh/counsel-env-qwen3-8b-qlora-sft-run4b \
230
+ COUNSEL_SFT_DATASET_SIZE=480 \
231
+ COUNSEL_SFT_MAX_STEPS=220 \
232
+ COUNSEL_MAX_SFT_LENGTH=1536 \
233
+ COUNSEL_SFT_LEARNING_RATE=1e-4 \
234
+ COUNSEL_LORA_R=16 \
235
+ COUNSEL_LORA_ALPHA=32 \
236
+ COUNSEL_GRAD_ACCUM=4 \
237
+ COUNSEL_INCLUDE_REST_ROWS=0 \
238
+ python counsel_env/scripts/run_qlora_sft_training_job.py
239
+ ```
240
+
241
  The current Space deployment does not start a paid GPU job. Before running remote training, approve the spend. Estimated costs:
242
 
243
  - A10G dry run: about `$0.50`
 
246
  Published training artifact:
247
 
248
  ```text
249
+ https://huggingface.co/heavycoderhh/counsel-env-qwen3-8b-qlora-sft-run4b
250
  ```
251
 
252
  Held-out evaluation artifacts are in:
253
 
254
  ```text
255
+ https://huggingface.co/heavycoderhh/counsel-env-qwen3-8b-qlora-sft-run4b/tree/main/eval
256
  ```
257
 
258
  The same trained eval files are mirrored locally for offline review:
 
266
  assets/trained_eval_run3/trained_eval_rows.jsonl
267
  assets/trained_eval_run3/trained_eval_summary.json
268
  assets/trained_eval_run3/trained_eval_transcripts.md
269
+ assets/trained_eval_run4b_8b_sft/eval/trained_eval_rows.csv
270
+ assets/trained_eval_run4b_8b_sft/eval/trained_eval_rows.jsonl
271
+ assets/trained_eval_run4b_8b_sft/eval/trained_eval_summary.json
272
+ assets/trained_eval_run4b_8b_sft/eval/trained_eval_transcripts.md
273
+ assets/trained_eval_run4b_8b_sft/training_summary.json
274
  ```
275
 
276
  ## Run Server Locally
 
302
 
303
  ## Status
304
 
305
+ The Hugging Face Space is deployed on free `cpu-basic` hardware with the live demo and OpenEnv API. Local validation passes. A trained Qwen3-8B QLoRA SFT checkpoint and held-out evaluation are published on Hugging Face, and the final video/blog scripts are prepared under `assets/demo/`.
RUN3_STATUS.md CHANGED
@@ -1,5 +1,7 @@
1
  # Run-3 Status
2
 
 
 
3
  Run-3 was launched as a Hugging Face Job after explicit approval. The first A100 job remained in `SCHEDULING` with no logs, so it was cancelled and relaunched on L40S. The first L40S attempt completed SFT, then failed before GRPO because `num_generations=6` was incompatible with TRL's default `generation_batch_size=4`; run-3 was patched to use `num_generations=4`.
4
 
5
  ```text
@@ -28,14 +30,7 @@ surface_rate=0.689
28
  avg_useless_ratio=0.550
29
  ```
30
 
31
- Expected next checks:
32
-
33
- ```bash
34
- hf jobs inspect 69ed848ed70108f37acdf694
35
- hf jobs logs 69ed848ed70108f37acdf694
36
- ```
37
-
38
- After the job succeeds, evaluate and upload run-3 artifacts:
39
 
40
  ```bash
41
  COUNSEL_EVAL_MODEL=heavycoderhh/counsel-env-qwen3-0.6b-grpo-run3 \
 
1
  # Run-3 Status
2
 
3
+ Run-3 is complete and has been superseded by run-4b (`heavycoderhh/counsel-env-qwen3-8b-qlora-sft-run4b`). Keep this file as historical proof for the SFT+GRPO attempt.
4
+
5
  Run-3 was launched as a Hugging Face Job after explicit approval. The first A100 job remained in `SCHEDULING` with no logs, so it was cancelled and relaunched on L40S. The first L40S attempt completed SFT, then failed before GRPO because `num_generations=6` was incompatible with TRL's default `generation_batch_size=4`; run-3 was patched to use `num_generations=4`.
6
 
7
  ```text
 
30
  avg_useless_ratio=0.550
31
  ```
32
 
33
+ Run-3 evaluation command:
 
 
 
 
 
 
 
34
 
35
  ```bash
36
  COUNSEL_EVAL_MODEL=heavycoderhh/counsel-env-qwen3-0.6b-grpo-run3 \
RUN3_TRAINING_PLAN.md CHANGED
@@ -1,5 +1,7 @@
1
  # Run-3 Training Plan
2
 
 
 
3
  Run 2 proves the environment works: the model beats reward-hacking baselines and surfaces contradictions on held-out cases. Run 3 targets the visible failure modes in the trained transcripts:
4
 
5
  - copying the case brief into `ask_question`
 
1
  # Run-3 Training Plan
2
 
3
+ Historical note: run 3 completed and was later superseded by run-4b, a Qwen3-8B QLoRA SFT run that reached `0.860` average reward and `0.928` primary/surface rate on the same held-out seeds.
4
+
5
  Run 2 proves the environment works: the model beats reward-hacking baselines and surfaces contradictions on held-out cases. Run 3 targets the visible failure modes in the trained transcripts:
6
 
7
  - copying the case brief into `ask_question`
RUN4B_STATUS.md ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run-4b Status
2
+
3
+ Run-4b is the current official submission checkpoint.
4
+
5
+ ```text
6
+ Training job ID: 69edb014d2c8bd8662bcf5ba
7
+ Evaluation job ID: 69edb609d70108f37acdfc39
8
+ Base model: Qwen/Qwen3-8B
9
+ Training method: 4-bit QLoRA SFT
10
+ SFT rows: 1460
11
+ Training runtime: 1287.7 seconds
12
+ Target repo: heavycoderhh/counsel-env-qwen3-8b-qlora-sft-run4b
13
+ Checkpoint SHA: 4002e75edfd36e8fc7453dce4f8fe84eff628a76
14
+ Local eval mirror: assets/trained_eval_run4b_8b_sft/eval/
15
+ ```
16
+
17
+ Run-4b held-out result on the same 30 deterministic seeds:
18
+
19
+ ```text
20
+ avg_reward=0.860
21
+ primary_reward=0.928
22
+ trigger_rate=0.928
23
+ surface_rate=0.928
24
+ ```
25
+
26
+ The run uses assistant-only oracle next-action labels rendered through the Qwen chat template, trains only on the assistant tool-call span, excludes rest-only rows by default, and uploads a PEFT adapter. This fixed the first 8B SFT attempt, which learned poor tool-call formatting and scored zero.
27
+
28
+ Run-4b beats the previous official run-3 checkpoint:
29
+
30
+ | Metric | Run 3 | Run 4b |
31
+ | --- | ---: | ---: |
32
+ | Avg reward | 0.615 | 0.860 |
33
+ | Primary reward | 0.689 | 0.928 |
34
+ | Trigger rate | 0.728 | 0.928 |
35
+ | Surface rate | 0.689 | 0.928 |
36
+
37
+ Run-4b should remain the official checkpoint unless a later model beats it on the same held-out evaluation harness.
TRAINING_PROOF.md CHANGED
@@ -8,9 +8,10 @@ The deployed Space does not start paid training. Use this page to run the smalle
8
  - Training notebook: `notebooks/train_counsel.ipynb`.
9
  - Default safety: `RUN_TRAINING=0`, `push_to_hub=False`, `report_to="none"`.
10
  - Paid remote training has completed only after explicit approval.
11
- - Best checkpoint: `heavycoderhh/counsel-env-qwen3-0.6b-grpo-run3`.
12
- - Run-3 recipe: run-2 base checkpoint, 720 assistant-only oracle SFT next-action rows, then 500 GRPO steps with stronger evidence and duplicate-loop shaping.
13
- - Held-out result: average reward `0.615`, primary reward `0.689`, surface rate `0.689` across 30 deterministic seeds.
 
14
 
15
  ## Lowest-Cost Dry Run
16
 
@@ -31,11 +32,11 @@ Expected purpose:
31
 
32
  ## Submission Standard Run
33
 
34
- Run 3 completes the submission-standard path:
35
 
36
  1. Trained on generated curriculum cases.
37
  2. Evaluated on the same 30-seed harness used in `BENCHMARKS.md`.
38
  3. Published trained eval rows, summary, and transcripts under the checkpoint repo's `eval/` folder.
39
- 4. Mirrored the trained eval artifacts locally under `assets/trained_eval/`.
40
 
41
- Run 3 satisfies this path for a submission demo: it is not oracle-level, but it substantially improves learned evidence timing over run 2 while staying below the scripted oracle ceiling.
 
8
  - Training notebook: `notebooks/train_counsel.ipynb`.
9
  - Default safety: `RUN_TRAINING=0`, `push_to_hub=False`, `report_to="none"`.
10
  - Paid remote training has completed only after explicit approval.
11
+ - Best checkpoint: `heavycoderhh/counsel-env-qwen3-8b-qlora-sft-run4b`.
12
+ - Best recipe: `Qwen/Qwen3-8B` with 4-bit QLoRA, assistant-only oracle SFT next-action rows, no rest-only rows, and adapter upload.
13
+ - Held-out result: average reward `0.860`, primary reward `0.928`, trigger rate `0.928`, surface rate `0.928` across 30 deterministic seeds.
14
+ - Prior run-3 SFT+GRPO checkpoint: `heavycoderhh/counsel-env-qwen3-0.6b-grpo-run3`, average reward `0.615`.
15
 
16
  ## Lowest-Cost Dry Run
17
 
 
32
 
33
  ## Submission Standard Run
34
 
35
+ Run 4b is the current submission-standard path:
36
 
37
  1. Trained on generated curriculum cases.
38
  2. Evaluated on the same 30-seed harness used in `BENCHMARKS.md`.
39
  3. Published trained eval rows, summary, and transcripts under the checkpoint repo's `eval/` folder.
40
+ 4. Mirrored the trained eval artifacts locally under `assets/trained_eval_run4b_8b_sft/eval/`.
41
 
42
+ Run 4b satisfies this path for a submission demo: it is close to the scripted oracle ceiling and clearly above random, keyword spam, present-all, and the previous run-3 checkpoint.
scripts/evaluate_trained_checkpoint_job.py CHANGED
@@ -6,6 +6,7 @@
6
  # "numpy>=2.0.0",
7
  # "openenv-core>=0.2.1",
8
  # "pandas>=2.0.0",
 
9
  # "torch>=2.8.0",
10
  # "transformers>=5.2.0",
11
  # ]
@@ -27,6 +28,7 @@ from typing import Any, Dict, List, Optional
27
  import pandas as pd
28
  import torch
29
  from huggingface_hub import HfApi, snapshot_download
 
30
  from transformers import AutoModelForCausalLM, AutoTokenizer
31
 
32
 
@@ -198,13 +200,23 @@ def execute_tool(env: CounselEnvironment, name: Optional[str], args: Dict[str, A
198
 
199
  def evaluate_model(repo_id: str, episodes: int, label: str) -> tuple[List[dict], List[str]]:
200
  dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
201
- tokenizer = AutoTokenizer.from_pretrained(repo_id, trust_remote_code=True)
 
 
 
 
 
 
 
 
202
  model = AutoModelForCausalLM.from_pretrained(
203
- repo_id,
204
  torch_dtype=dtype,
205
  device_map="auto",
206
  trust_remote_code=True,
207
  )
 
 
208
  model.eval()
209
 
210
  rows: List[dict] = []
 
6
  # "numpy>=2.0.0",
7
  # "openenv-core>=0.2.1",
8
  # "pandas>=2.0.0",
9
+ # "peft>=0.18.0",
10
  # "torch>=2.8.0",
11
  # "transformers>=5.2.0",
12
  # ]
 
28
  import pandas as pd
29
  import torch
30
  from huggingface_hub import HfApi, snapshot_download
31
+ from peft import PeftConfig, PeftModel
32
  from transformers import AutoModelForCausalLM, AutoTokenizer
33
 
34
 
 
200
 
201
  def evaluate_model(repo_id: str, episodes: int, label: str) -> tuple[List[dict], List[str]]:
202
  dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
203
+ try:
204
+ peft_config = PeftConfig.from_pretrained(repo_id)
205
+ except Exception:
206
+ peft_config = None
207
+ load_repo = peft_config.base_model_name_or_path if peft_config is not None else repo_id
208
+ tokenizer_repo = repo_id if peft_config is not None else load_repo
209
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_repo, trust_remote_code=True)
210
+ if tokenizer.pad_token is None:
211
+ tokenizer.pad_token = tokenizer.eos_token
212
  model = AutoModelForCausalLM.from_pretrained(
213
+ load_repo,
214
  torch_dtype=dtype,
215
  device_map="auto",
216
  trust_remote_code=True,
217
  )
218
+ if peft_config is not None:
219
+ model = PeftModel.from_pretrained(model, repo_id)
220
  model.eval()
221
 
222
  rows: List[dict] = []
scripts/run_qlora_sft_training_job.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "accelerate>=1.12.0",
5
+ # "bitsandbytes>=0.48.0",
6
+ # "datasets>=4.0.0",
7
+ # "huggingface_hub>=1.0.0",
8
+ # "openenv-core>=0.2.1",
9
+ # "peft>=0.18.0",
10
+ # "torch>=2.8.0",
11
+ # "transformers>=5.2.0",
12
+ # ]
13
+ # ///
14
+ """Fast QLoRA oracle-SFT run for larger Counsel-Env models.
15
+
16
+ This job is intended for quick 4B/8B ablations. It trains only LoRA adapter
17
+ weights on generated oracle next-action rows, uploads the adapter, and leaves
18
+ GRPO as an optional follow-up only if SFT evaluation beats the current best.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import importlib.util
24
+ import json
25
+ import os
26
+ import sys
27
+ from pathlib import Path
28
+ from typing import Any, Dict, List
29
+
30
+ import torch
31
+ from datasets import Dataset
32
+ from huggingface_hub import HfApi, snapshot_download
33
+ from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
34
+ from transformers import (
35
+ AutoModelForCausalLM,
36
+ AutoTokenizer,
37
+ BitsAndBytesConfig,
38
+ DataCollatorForSeq2Seq,
39
+ Trainer,
40
+ TrainingArguments,
41
+ )
42
+
43
+
44
+ SPACE_REPO = os.getenv("COUNSEL_SPACE_REPO", "heavycoderhh/counsel-env")
45
+ MODEL = os.getenv("COUNSEL_MODEL", "Qwen/Qwen3-8B")
46
+ OUTPUT_DIR = Path(os.getenv("COUNSEL_OUTPUT_DIR", "/tmp/counsel-qwen3-8b-qlora-sft"))
47
+ ARTIFACT_REPO = os.getenv("COUNSEL_ARTIFACT_REPO", "heavycoderhh/counsel-env-qwen3-8b-qlora-sft-run4")
48
+ SFT_DATASET_SIZE = int(os.getenv("COUNSEL_SFT_DATASET_SIZE", "480"))
49
+ SFT_EPOCHS = float(os.getenv("COUNSEL_SFT_EPOCHS", "1"))
50
+ SFT_MAX_STEPS = int(os.getenv("COUNSEL_SFT_MAX_STEPS", "320"))
51
+ SFT_LEARNING_RATE = float(os.getenv("COUNSEL_SFT_LEARNING_RATE", "2e-4"))
52
+ MAX_SFT_LENGTH = int(os.getenv("COUNSEL_MAX_SFT_LENGTH", "2048"))
53
+ LORA_R = int(os.getenv("COUNSEL_LORA_R", "16"))
54
+ LORA_ALPHA = int(os.getenv("COUNSEL_LORA_ALPHA", "32"))
55
+ LORA_DROPOUT = float(os.getenv("COUNSEL_LORA_DROPOUT", "0.05"))
56
+ GRADIENT_ACCUMULATION_STEPS = int(os.getenv("COUNSEL_GRAD_ACCUM", "4"))
57
+ INCLUDE_REST_ROWS = os.getenv("COUNSEL_INCLUDE_REST_ROWS", "0") == "1"
58
+
59
+
60
+ def prepare_imports() -> None:
61
+ """Make the Space package importable inside HF Jobs."""
62
+ try:
63
+ import counsel_env # noqa: F401
64
+
65
+ return
66
+ except Exception:
67
+ pass
68
+
69
+ source_dir = snapshot_download(repo_id=SPACE_REPO, repo_type="space")
70
+ init_path = Path(source_dir) / "__init__.py"
71
+ spec = importlib.util.spec_from_file_location(
72
+ "counsel_env",
73
+ init_path,
74
+ submodule_search_locations=[source_dir],
75
+ )
76
+ if spec is None or spec.loader is None:
77
+ raise RuntimeError(f"Could not load Counsel-Env package from {source_dir}")
78
+ module = importlib.util.module_from_spec(spec)
79
+ sys.modules["counsel_env"] = module
80
+ spec.loader.exec_module(module)
81
+ print(f"Loaded Counsel-Env source from {source_dir}")
82
+
83
+
84
+ prepare_imports()
85
+
86
+ from counsel_env.models import CounselAction # noqa: E402
87
+ from counsel_env.server.counsel_env_environment import CounselEnvironment # noqa: E402
88
+
89
+
90
+ def ask_question(question: str) -> str:
91
+ """Ask the witness a question.
92
+
93
+ Args:
94
+ question: The cross-examination question to ask the witness.
95
+ """
96
+ raise RuntimeError("Tool schema only")
97
+
98
+
99
+ def present_evidence(exhibit_id: str) -> str:
100
+ """Present an exhibit to the witness.
101
+
102
+ Args:
103
+ exhibit_id: The ID of the exhibit to present.
104
+ """
105
+ raise RuntimeError("Tool schema only")
106
+
107
+
108
+ def rest_case() -> str:
109
+ """End the cross-examination."""
110
+ raise RuntimeError("Tool schema only")
111
+
112
+
113
+ TOOLS = [ask_question, present_evidence, rest_case]
114
+
115
+ BASE_PROMPT = (
116
+ "You are a sharp prosecuting attorney cross-examining a deterministic witness. "
117
+ "Your goal is to surface contradictions by first making the witness commit to a claim, "
118
+ "then presenting the exact exhibit that disproves it. Use the limited question budget efficiently. "
119
+ "Return exactly one tool call and no prose. Never invent exhibit IDs. "
120
+ "Do not rest the case until after at least one contradiction has been surfaced."
121
+ )
122
+
123
+
124
+ def sample_stage_schedule(total: int) -> List[str]:
125
+ schedule = []
126
+ for index in range(total):
127
+ frac = index / max(1, total - 1)
128
+ if frac < 0.45:
129
+ schedule.append("easy")
130
+ elif frac < 0.85:
131
+ schedule.append("medium")
132
+ else:
133
+ schedule.append("hard")
134
+ return schedule
135
+
136
+
137
+ def format_evidence(evidence_descriptions: Dict[str, str]) -> str:
138
+ return "\n".join(f"- {exhibit_id}: {description}" for exhibit_id, description in evidence_descriptions.items())
139
+
140
+
141
+ def reset_text(obs: Any) -> str:
142
+ return (
143
+ f"CASE BRIEF:\n{obs.case_brief}\n\n"
144
+ f"You have {obs.questions_remaining} questions. "
145
+ "Available exhibits with descriptions:\n"
146
+ f"{format_evidence(obs.evidence_descriptions)}\n\n"
147
+ "Use ask_question first. After the witness commits, present the exact matching exhibit ID."
148
+ )
149
+
150
+
151
+ def tool_feedback(obs: Any) -> str:
152
+ components = obs.reward_components or {}
153
+ evidence = ", ".join(obs.available_evidence)
154
+ return (
155
+ f"WITNESS: {obs.witness_response}\n"
156
+ f"STATE: triggered={int(components.get('contradictions_triggered', 0))}/"
157
+ f"{int(components.get('contradictions_total', 0))}, "
158
+ f"surfaced={int(components.get('contradictions_surfaced', 0))}/"
159
+ f"{int(components.get('contradictions_total', 0))}, "
160
+ f"questions_remaining={obs.questions_remaining}, done={obs.done}\n"
161
+ f"VALID_EXHIBITS: {evidence}"
162
+ )
163
+
164
+
165
+ def tool_call(name: str, arguments: Dict[str, Any]) -> str:
166
+ return "<tool_call>\n" + json.dumps({"name": name, "arguments": arguments}, sort_keys=True) + "\n</tool_call>"
167
+
168
+
169
+ def tokenize_assistant_action(
170
+ tokenizer: Any,
171
+ prompt_messages: List[Dict[str, str]],
172
+ assistant_message: Dict[str, str],
173
+ ) -> Dict[str, List[int]]:
174
+ """Create one row with loss on the rendered assistant generation span."""
175
+ prompt_text = tokenizer.apply_chat_template(
176
+ prompt_messages,
177
+ tools=TOOLS,
178
+ tokenize=False,
179
+ add_generation_prompt=True,
180
+ chat_template_kwargs={"enable_thinking": False},
181
+ )
182
+ full_text = tokenizer.apply_chat_template(
183
+ prompt_messages + [assistant_message],
184
+ tools=TOOLS,
185
+ tokenize=False,
186
+ add_generation_prompt=False,
187
+ chat_template_kwargs={"enable_thinking": False},
188
+ )
189
+ encoded = tokenizer(full_text, add_special_tokens=False, max_length=MAX_SFT_LENGTH, truncation=True)
190
+ prompt_ids = tokenizer(prompt_text, add_special_tokens=False, max_length=MAX_SFT_LENGTH, truncation=True)[
191
+ "input_ids"
192
+ ]
193
+ input_ids = encoded["input_ids"]
194
+ labels = list(input_ids)
195
+ labels[: min(len(prompt_ids), len(labels))] = [-100] * min(len(prompt_ids), len(labels))
196
+ encoded["labels"] = labels
197
+ return encoded
198
+
199
+
200
+ def create_oracle_sft_dataset(tokenizer: Any, num_samples: int) -> Dataset:
201
+ rows: List[Dict[str, List[int]]] = []
202
+ stages = sample_stage_schedule(num_samples)
203
+ for seed, stage in enumerate(stages, start=514159):
204
+ env = CounselEnvironment()
205
+ obs = env.reset(seed=seed, curriculum_stage=stage, episode_id=f"qwen8b_sft_{seed}")
206
+ messages = [{"role": "user", "content": f"{BASE_PROMPT}\n\n{reset_text(obs)}"}]
207
+
208
+ for contradiction in env.witness.contradictions:
209
+ question = f"{contradiction.trigger_keywords[0]}?"
210
+ assistant_message = {"role": "assistant", "content": tool_call("ask_question", {"question": question})}
211
+ rows.append(tokenize_assistant_action(tokenizer, messages, assistant_message))
212
+ messages.append(assistant_message)
213
+ obs = env.step(CounselAction(tool="ask_question", text=question))
214
+ messages.append({"role": "user", "content": f"<tool_response>\n{tool_feedback(obs)}\n</tool_response>"})
215
+
216
+ exhibit_id = contradiction.disprover_evidence_id
217
+ assistant_message = {
218
+ "role": "assistant",
219
+ "content": tool_call("present_evidence", {"exhibit_id": exhibit_id}),
220
+ }
221
+ rows.append(tokenize_assistant_action(tokenizer, messages, assistant_message))
222
+ messages.append(assistant_message)
223
+ obs = env.step(CounselAction(tool="present_evidence", exhibit_id=exhibit_id))
224
+ messages.append({"role": "user", "content": f"<tool_response>\n{tool_feedback(obs)}\n</tool_response>"})
225
+
226
+ if INCLUDE_REST_ROWS:
227
+ assistant_message = {"role": "assistant", "content": tool_call("rest_case", {})}
228
+ rows.append(tokenize_assistant_action(tokenizer, messages, assistant_message))
229
+
230
+ return Dataset.from_list(rows)
231
+
232
+
233
+ def write_summary(path: Path, train_result: Any, row_count: int) -> None:
234
+ summary = {
235
+ "recipe": "qwen3_8b_qlora_oracle_sft",
236
+ "base_model": MODEL,
237
+ "artifact_repo": ARTIFACT_REPO,
238
+ "space_repo": SPACE_REPO,
239
+ "sft_case_count": SFT_DATASET_SIZE,
240
+ "sft_row_count": row_count,
241
+ "sft_epochs": SFT_EPOCHS,
242
+ "sft_max_steps": SFT_MAX_STEPS,
243
+ "sft_learning_rate": SFT_LEARNING_RATE,
244
+ "max_sft_length": MAX_SFT_LENGTH,
245
+ "lora_r": LORA_R,
246
+ "lora_alpha": LORA_ALPHA,
247
+ "lora_dropout": LORA_DROPOUT,
248
+ "gradient_accumulation_steps": GRADIENT_ACCUMULATION_STEPS,
249
+ "include_rest_rows": INCLUDE_REST_ROWS,
250
+ "metrics": getattr(train_result, "metrics", {}) or {},
251
+ }
252
+ path.write_text(json.dumps(summary, indent=2, sort_keys=True), encoding="utf-8")
253
+ print(json.dumps(summary, indent=2, sort_keys=True))
254
+
255
+
256
+ def upload_artifacts() -> None:
257
+ token = os.getenv("HF_TOKEN")
258
+ if not token:
259
+ print("HF_TOKEN not set; skipping artifact upload.")
260
+ return
261
+ api = HfApi(token=token)
262
+ api.create_repo(repo_id=ARTIFACT_REPO, repo_type="model", exist_ok=True)
263
+ api.upload_folder(
264
+ repo_id=ARTIFACT_REPO,
265
+ repo_type="model",
266
+ folder_path=str(OUTPUT_DIR),
267
+ commit_message=f"Upload Counsel-Env QLoRA SFT adapter ({SFT_MAX_STEPS} max steps)",
268
+ )
269
+ print(f"Uploaded QLoRA SFT adapter to https://huggingface.co/{ARTIFACT_REPO}")
270
+
271
+
272
+ def main() -> None:
273
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
274
+ tokenizer = AutoTokenizer.from_pretrained(MODEL, trust_remote_code=True)
275
+ if tokenizer.pad_token is None:
276
+ tokenizer.pad_token = tokenizer.eos_token
277
+ dataset = create_oracle_sft_dataset(tokenizer, SFT_DATASET_SIZE)
278
+
279
+ quantization = BitsAndBytesConfig(
280
+ load_in_4bit=True,
281
+ bnb_4bit_quant_type="nf4",
282
+ bnb_4bit_compute_dtype=torch.bfloat16,
283
+ bnb_4bit_use_double_quant=True,
284
+ )
285
+ model = AutoModelForCausalLM.from_pretrained(
286
+ MODEL,
287
+ quantization_config=quantization,
288
+ device_map="auto",
289
+ trust_remote_code=True,
290
+ )
291
+ model.config.use_cache = False
292
+ model = prepare_model_for_kbit_training(model)
293
+ lora_config = LoraConfig(
294
+ r=LORA_R,
295
+ lora_alpha=LORA_ALPHA,
296
+ lora_dropout=LORA_DROPOUT,
297
+ bias="none",
298
+ task_type="CAUSAL_LM",
299
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
300
+ )
301
+ model = get_peft_model(model, lora_config)
302
+ model.print_trainable_parameters()
303
+
304
+ args = TrainingArguments(
305
+ output_dir=str(OUTPUT_DIR),
306
+ per_device_train_batch_size=1,
307
+ gradient_accumulation_steps=GRADIENT_ACCUMULATION_STEPS,
308
+ num_train_epochs=SFT_EPOCHS,
309
+ max_steps=SFT_MAX_STEPS if SFT_MAX_STEPS > 0 else -1,
310
+ learning_rate=SFT_LEARNING_RATE,
311
+ optim="paged_adamw_8bit",
312
+ logging_steps=10,
313
+ save_strategy="no",
314
+ report_to="none",
315
+ bf16=torch.cuda.is_available(),
316
+ gradient_checkpointing=True,
317
+ remove_unused_columns=False,
318
+ )
319
+ trainer = Trainer(
320
+ model=model,
321
+ args=args,
322
+ train_dataset=dataset,
323
+ data_collator=DataCollatorForSeq2Seq(tokenizer=tokenizer, padding=True, label_pad_token_id=-100),
324
+ )
325
+ train_result = trainer.train()
326
+ trainer.save_model(str(OUTPUT_DIR))
327
+ tokenizer.save_pretrained(str(OUTPUT_DIR))
328
+ write_summary(OUTPUT_DIR / "training_summary.json", train_result, len(dataset))
329
+ upload_artifacts()
330
+
331
+
332
+ if __name__ == "__main__":
333
+ main()
server/demo.py CHANGED
@@ -46,13 +46,13 @@ BENCHMARK_ROWS = [
46
  "takeaway": "Blindly dumping exhibits fails because timing matters.",
47
  },
48
  {
49
- "agent": "trained_sft_grpo_run3",
50
  "episodes": 30,
51
- "avg_reward": 0.615,
52
- "primary_reward": 0.689,
53
- "trigger_rate": 0.728,
54
- "surface_rate": 0.689,
55
- "takeaway": "Assistant-only SFT plus GRPO improves evidence timing and reduces loops.",
56
  },
57
  {
58
  "agent": "scripted_oracle",
@@ -265,7 +265,7 @@ def _demo_html() -> str:
265
  <body>
266
  <header>
267
  <h1>Counsel-Env Live Demo</h1>
268
- <p>Make the witness commit, then present the exhibit that exposes the contradiction. This is the target behavior for GRPO training.</p>
269
  </header>
270
  <main>
271
  <div class="stack">
 
46
  "takeaway": "Blindly dumping exhibits fails because timing matters.",
47
  },
48
  {
49
+ "agent": "trained_qwen3_8b_qlora_sft_run4b",
50
  "episodes": 30,
51
+ "avg_reward": 0.860,
52
+ "primary_reward": 0.928,
53
+ "trigger_rate": 0.928,
54
+ "surface_rate": 0.928,
55
+ "takeaway": "Qwen3-8B QLoRA SFT learns the trigger-then-evidence loop reliably.",
56
  },
57
  {
58
  "agent": "scripted_oracle",
 
265
  <body>
266
  <header>
267
  <h1>Counsel-Env Live Demo</h1>
268
+ <p>Make the witness commit, then present the exhibit that exposes the contradiction. This is the target behavior for post-training.</p>
269
  </header>
270
  <main>
271
  <div class="stack">