File size: 23,016 Bytes
498f80b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
"""CLI entry points for guac-coder."""

import argparse
import json
import logging
import os
import sys

from guac_coder.config import GRPOConfig, RewardConfig
from guac_coder.data import build_prompt
from guac_coder.rewards import compute_total_reward
from guac_coder.training import train_grpo


def _read_code_file(path: str) -> str:
    """Read a Python file, exiting with a clean message if it is missing."""
    if not os.path.isfile(path):
        raise SystemExit(f"error: no such file: {path}")
    with open(path, "r", encoding="utf-8") as fh:
        return fh.read()


RATER_CHOICES = ("static", "decision", "llm")


def _add_rater_args(parser: argparse.ArgumentParser) -> None:
    """Attach the shared rater-selection flags to a subparser."""
    parser.add_argument(
        "--rater",
        default="static",
        choices=list(RATER_CHOICES),
        help=(
            "Scoring backend: static (13 regex/AST rules), decision (Ollama "
            "System-One decision model, e.g. clef), or llm (generative judge)"
        ),
    )
    parser.add_argument(
        "--rater-model",
        default="clef",
        help="Decision model tag for --rater decision (e.g. clef, clef:cloud)",
    )
    parser.add_argument(
        "--rater-base-url",
        default="http://localhost:11434",
        help="Ollama base URL for the decision rater",
    )
    parser.add_argument(
        "--rater-threshold",
        type=float,
        default=0.5,
        help="Probability cutoff for multi-state decision rules",
    )
    parser.add_argument(
        "--rater-on-error",
        default="static",
        choices=["static", "zero", "raise"],
        help="Behaviour when the decision endpoint fails",
    )


def _reward_config_from_args(args: argparse.Namespace) -> RewardConfig:
    """Build a RewardConfig from the rater flags on ``args``."""
    kwargs = {}
    if getattr(args, "judge_model", None):
        kwargs["judge_model"] = args.judge_model
    if getattr(args, "rater", None):
        kwargs["rater"] = args.rater
    if getattr(args, "rater_model", None):
        kwargs["decision_model"] = args.rater_model
    if getattr(args, "rater_base_url", None):
        kwargs["decision_base_url"] = args.rater_base_url
    if getattr(args, "rater_threshold", None) is not None:
        kwargs["decision_threshold"] = args.rater_threshold
    if getattr(args, "rater_on_error", None):
        kwargs["decision_on_error"] = args.rater_on_error
    return RewardConfig(**kwargs)


def _resolve_llm_judge():
    """Return an LLM judge callable for the legacy rewards.py path.

    Uses npcpy.llm_funcs.get_llm_response when importable. Falls back to a
    judge that returns no scores, which makes the LLM component contribute
    zero rather than failing the run.
    """
    try:
        from npcpy.llm_funcs import get_llm_response

        return get_llm_response
    except Exception as exc:  # pragma: no cover - depends on environment
        logging.warning("LLM judge unavailable (%s); scoring static components only", exc)

        def _no_judge(**kwargs):
            return {}

        return _no_judge


def _setup_logging(level: int = logging.INFO) -> None:
    # force=True: npcpy and friends install root handlers at import time, and
    # plain basicConfig() would silently no-op, swallowing our INFO progress.
    logging.basicConfig(
        level=level,
        format="%(asctime)s [%(levelname)s] %(message)s",
        stream=sys.stdout,
        force=True,
    )
    logging.getLogger("guac_coder").setLevel(level)


def main() -> None:
    parser = argparse.ArgumentParser(description="guac-coder: research code LLM")
    subparsers = parser.add_subparsers(dest="command")

    # train
    train_parser = subparsers.add_parser("train", help="Run GRPO training")
    train_parser.add_argument("--model", default="Qwen/Qwen2.5-Coder-7B")
    train_parser.add_argument("--output-dir", default="./grpo_output")
    train_parser.add_argument("--data", default=None, help="Path to JSONL training data")
    train_parser.add_argument("--iterations", type=int, default=100)
    train_parser.add_argument("--group-size", type=int, default=8)
    train_parser.add_argument("--lr", type=float, default=1e-5)
    train_parser.add_argument("--resume-from", default=None)
    train_parser.add_argument("--backend", default="auto", choices=["auto", "mlx", "torch"])
    train_parser.add_argument(
        "--legacy-rewards",
        action="store_true",
        help="Optimize the legacy rewards.py score instead of the 13-rule grpo_rewards",
    )
    _add_rater_args(train_parser)

    # eval
    eval_parser = subparsers.add_parser("eval", help="Evaluate code with reward function")
    eval_parser.add_argument("code", nargs="?", help="Python code string or '-' for stdin")
    eval_parser.add_argument("--file", default=None, help="Python file to evaluate")
    eval_parser.add_argument("--judge-model", default="gpt-4o")
    eval_parser.add_argument("--json", action="store_true", help="Output JSON")
    _add_rater_args(eval_parser)

    # reward
    reward_parser = subparsers.add_parser("reward", help="Compute reward for a code snippet")
    reward_parser.add_argument("--task", required=True, help="Task description")
    reward_parser.add_argument("--code", required=True, help="Code snippet or file path")
    reward_parser.add_argument("--llm-judge", action="store_true", help="Include LLM judge")
    reward_parser.add_argument(
        "--legacy",
        action="store_true",
        help="Use the legacy rewards.py path instead of the 13-rule grpo_rewards",
    )
    reward_parser.add_argument("--json", action="store_true", help="Output JSON")
    _add_rater_args(reward_parser)

    # trace
    trace_parser = subparsers.add_parser(
        "trace", help="Generate scored traces from local Ollama models"
    )
    trace_parser.add_argument("--models", required=True, help="Comma-separated model names")
    trace_parser.add_argument("--output-dir", default="./traces")
    trace_parser.add_argument("--tasks", default=None)
    trace_parser.add_argument("--limit", type=int, default=None)
    trace_parser.add_argument("--n-samples", type=int, default=1)
    trace_parser.add_argument("--num-predict", type=int, default=1024)
    trace_parser.add_argument("--temperature", type=float, default=0.8)
    trace_parser.add_argument("--seed", type=int, default=42)
    trace_parser.add_argument("--base-url", default="http://localhost:11434")
    trace_parser.add_argument("--timeout", type=float, default=600.0)
    trace_parser.add_argument("--no-think", action="store_true")
    trace_parser.add_argument("--no-resume", action="store_true")
    trace_parser.add_argument(
        "--model-opt",
        action="append",
        default=None,
        help="Per-model setting, repeatable: MODEL:key=value[,key=value]. "
        "Keys: num_predict, think, temperature, timeout",
    )
    trace_parser.add_argument("--json", action="store_true")
    _add_rater_args(trace_parser)

    # export
    export_parser = subparsers.add_parser(
        "export", help="Convert traces into SFT / preference / GRPO datasets"
    )
    export_parser.add_argument("--traces", required=True, help="Path to traces JSONL")
    export_parser.add_argument("--output-dir", default=None)
    export_parser.add_argument("--min-reward", type=float, default=None)
    export_parser.add_argument("--min-gap", type=float, default=0.15)
    export_parser.add_argument("--json", action="store_true")

    # audit
    audit_parser = subparsers.add_parser(
        "audit", help="Measure per-rule agreement between two raters"
    )
    audit_parser.add_argument("--corpus", required=True, help="Directory of .py cases")
    audit_parser.add_argument("--rater-a", default="static")
    audit_parser.add_argument("--rater-b", default="decision")
    audit_parser.add_argument("--rater-model", default=None)
    audit_parser.add_argument("--output", default=None, help="Write JSON report here")
    audit_parser.add_argument("--json", action="store_true")

    args = parser.parse_args()

    if args.command == "train":
        train_command(args)
    elif args.command == "eval":
        eval_command(args)
    elif args.command == "reward":
        reward_command(args)
    elif args.command == "trace":
        trace_command(args)
    elif args.command == "export":
        export_command(args)
    elif args.command == "audit":
        audit_command(args)
    else:
        parser.print_help()


def train_command(args: argparse.Namespace | None = None) -> None:
    """Run GRPO training."""
    if args is None:
        args = _parse_train_args()

    _setup_logging()

    cfg = GRPOConfig(
        model_name=args.model,
        output_dir=args.output_dir,
        num_iterations=args.iterations,
        group_size=args.group_size,
        learning_rate=args.lr,
        resume_from_checkpoint=args.resume_from,
        backend=getattr(args, "backend", "auto"),
    )
    reward_cfg = _reward_config_from_args(args)

    use_grpo_rewards = not getattr(args, "legacy_rewards", False)
    rater = getattr(args, "rater", "static")
    if getattr(args, "legacy_rewards", False):
        rater = "llm"
    # The LLM judge is only consulted on the legacy path; static and decision
    # raters never call it.
    get_llm_response_fn = _resolve_llm_judge() if rater == "llm" else (lambda **kwargs: {})

    train_grpo(
        cfg,
        reward_cfg,
        get_llm_response_fn,
        data_path=args.data,
        use_grpo_rewards=use_grpo_rewards,
        rater=rater,
    )


def eval_command(args: argparse.Namespace | None = None) -> None:
    """Evaluate code with the legacy 12-rule reward function (static + LLM judge)."""
    if args is None:
        args = _parse_eval_args()

    _setup_logging()

    if args.file:
        code = _read_code_file(args.file)
    elif args.code and args.code != "-":
        code = args.code
    else:
        code = sys.stdin.read()

    reward_cfg = _reward_config_from_args(args)
    rater = getattr(args, "rater", "static")

    if rater == "llm":
        result = compute_total_reward(code, _resolve_llm_judge(), reward_cfg)
    else:
        from guac_coder.training import score_completion

        _total, details = score_completion(code, lambda **kwargs: {}, reward_cfg, rater=rater)
        rules = details.get("rules", {})
        result = {
            "total": _total,
            "rater": rater,
            "static": _total if rater == "static" else 0.0,
            "llm": 0.0,
            "static_components": rules if rater == "static" else {},
            "rules": rules,
            "llm_components": {},
        }

    if args.json:
        print(json.dumps(result, indent=2))
    else:
        print(f"Rater: {result.get('rater', 'llm')}")
        print(f"Total reward: {result['total']:.3f}")
        if result.get("rater") == "llm":
            print(f"  Static:     {result['static']:.3f}")
            print(f"  LLM judge:  {result['llm']:.3f}")
            print("\nStatic components:")
            for k, v in result.get("static_components", {}).items():
                print(f"  {k}: {v:+.3f}")
            print("\nLLM components:")
            for k, v in result.get("llm_components", {}).items():
                print(f"  {k}: {v:+.3f}")
        else:
            print("\nPer-rule rewards:")
            for k, v in result.get("rules", {}).items():
                print(f"  {k}: {v:+.3f}")


def reward_command(args: argparse.Namespace | None = None) -> None:
    """Compute reward for a task/code pair."""
    if args is None:
        args = _parse_reward_args()

    _setup_logging()

    code = args.code
    if code.endswith(".py") and "\n" not in code:
        code = _read_code_file(code)

    prompt = build_prompt(args.task)

    # --legacy / --llm-judge force the generative judge path; otherwise --rater
    # selects between the static rules and a decision model.
    use_legacy = getattr(args, "legacy", False) or getattr(args, "llm_judge", False)
    if getattr(args, "llm_judge", False) and not getattr(args, "legacy", False):
        logging.info("--llm-judge requires the legacy reward path; using --legacy")

    reward_cfg = _reward_config_from_args(args)
    rater = "llm" if use_legacy else getattr(args, "rater", "static")
    as_json = getattr(args, "json", False)

    if rater == "llm":
        judge = _resolve_llm_judge() if getattr(args, "llm_judge", False) else None
        get_llm_response_fn = judge or (lambda **kwargs: {})
        result = compute_total_reward(code, get_llm_response_fn, reward_cfg)
        total = result["total"]
        breakdown = result.get("static_components", {})
        extra = {"static": result["static"], "llm": result["llm"]}
    else:
        from guac_coder.training import score_completion

        total, details = score_completion(code, lambda **kwargs: {}, reward_cfg, rater=rater)
        breakdown = details.get("rules", {})
        extra = {}

    if as_json:
        print(
            json.dumps(
                {
                    "task": args.task,
                    "rater": rater,
                    "total": total,
                    **extra,
                    "rules": breakdown,
                },
                indent=2,
            )
        )
        return

    print(f"Task: {args.task}")
    print(f"Rater: {rater}")
    print(f"Prompt length: {len(prompt)} chars")
    print(f"Code length: {len(code)} chars")
    print(f"Total reward: {total:.3f}")
    for key, value in extra.items():
        print(f"  {key}: {value:+.3f}")
    print("\nPer-rule rewards:")
    for name, value in breakdown.items():
        print(f"  {name}: {value:+.3f}")


def _parse_model_opts(specs) -> dict:
    """Parse --model-opt MODEL:key=value[,key=value] into per-model settings."""
    overrides = {}
    for spec in specs or []:
        # Model names contain colons (lfm3:latest), so split on the first
        # known key marker rather than on the first colon.
        marker = None
        for candidate in ("num_predict=", "think=", "temperature=", "timeout="):
            idx = spec.find(candidate)
            if idx != -1 and (marker is None or idx < marker):
                marker = idx
        if marker is None:
            raise SystemExit("error: malformed --model-opt '%s' (want MODEL:key=value)" % spec)
        head = spec[:marker].rstrip()
        if not head.endswith(":"):
            raise SystemExit("error: malformed --model-opt '%s' (want MODEL:key=value)" % spec)
        model = head[:-1].strip()
        rest = spec[marker:]
        settings = overrides.setdefault(model, {})
        for pair in rest.split(","):
            key, _, value = pair.partition("=")
            key, value = key.strip(), value.strip()
            if not key or not value:
                raise SystemExit("error: malformed --model-opt pair '%s'" % pair)
            if key == "num_predict" or key == "timeout":
                try:
                    value = int(float(value)) if key == "num_predict" else float(value)
                except ValueError:
                    raise SystemExit(
                        "error: --model-opt %s needs a number, got '%s'" % (key, value)
                    )
            elif key == "temperature":
                try:
                    value = float(value)
                except ValueError:
                    raise SystemExit("error: --model-opt temperature needs a number")
            elif key == "think":
                value = value.lower() in ("1", "true", "yes", "on")
            else:
                raise SystemExit("error: unknown --model-opt key '%s'" % key)
            settings[key] = value
    return overrides


def trace_command(args: argparse.Namespace | None = None) -> None:
    """Generate scored traces from local Ollama models."""
    if args is None:
        args = _parse_trace_args()

    _setup_logging()

    from guac_coder.data import load_research_tasks
    from guac_coder.trace import run_experiment

    models = [m.strip() for m in args.models.split(",") if m.strip()]
    tasks = load_research_tasks(args.tasks) if args.tasks else load_research_tasks()
    if args.limit:
        tasks = tasks[: args.limit]

    summary = run_experiment(
        models=models,
        output_dir=args.output_dir,
        tasks=tasks,
        n_samples=args.n_samples,
        base_url=args.base_url,
        num_predict=args.num_predict,
        temperature=args.temperature,
        seed=args.seed,
        think=not args.no_think,
        timeout=args.timeout,
        resume=not args.no_resume,
        model_overrides=_parse_model_opts(getattr(args, "model_opt", None)),
        rater=getattr(args, "rater", "static"),
        reward_cfg=_reward_config_from_args(args),
    )

    if args.json:
        print(json.dumps(summary, indent=2))
        return

    print("\nTraces: %s" % summary["traces_path"])
    print("New this run: %d" % summary["new_traces_this_run"])
    for model, stats in summary["models"].items():
        print("\n== %s ==" % model)
        print(
            "  n=%d scored=%d sources=%s" % (stats["n"], stats["n_scored"], stats["code_sources"])
        )
        if stats.get("empty_reasons"):
            print("  empty: %s" % stats["empty_reasons"])
        print(
            "  mean_reward=%s std=%s min=%s max=%s"
            % (
                stats["mean_reward"],
                stats["std_reward"],
                stats["min_reward"],
                stats["max_reward"],
            )
        )
        print("  mean_code_chars=%s" % stats["mean_code_chars"])
        if stats["rules"]:
            print("  per-rule means (fired fraction):")
            for rule, rs in stats["rules"].items():
                print("    %-34s %+.3f  (%.0f%%)" % (rule, rs["mean"], rs["fired_frac"] * 100))


def audit_command(args: argparse.Namespace | None = None) -> None:
    """Measure per-rule agreement between two raters over a labeled corpus."""
    if args is None:
        args = _parse_audit_args()

    _setup_logging()

    from guac_coder.rater_audit import format_report, run_audit

    report = run_audit(
        corpus_dir=args.corpus,
        rater_a=args.rater_a,
        rater_b=args.rater_b,
        rater_model=args.rater_model,
    )

    if args.output:
        with open(args.output, "w", encoding="utf-8") as fh:
            json.dump(report, fh, indent=2)
        logging.info("Wrote audit report to %s", args.output)

    if args.json:
        print(json.dumps(report, indent=2))
        return

    print(format_report(report))


def export_command(args: argparse.Namespace | None = None) -> None:
    """Convert a traces JSONL into training datasets."""
    if args is None:
        args = _parse_export_args()

    _setup_logging()

    from guac_coder.trace_export import export_all

    output_dir = args.output_dir or os.path.join(os.path.dirname(args.traces) or ".", "datasets")
    manifest = export_all(
        traces_path=args.traces,
        output_dir=output_dir,
        min_reward=args.min_reward,
        min_gap=args.min_gap,
    )

    if args.json:
        print(json.dumps(manifest, indent=2))
        return

    print(
        "Traces:      %s (%d rows, %d scored)"
        % (manifest["traces_path"], manifest["n_traces"], manifest["n_scored"])
    )
    print("SFT:         %d -> %s" % (manifest["sft"]["n"], manifest["sft"]["path"]))
    print("Preference:  %d -> %s" % (manifest["preference"]["n"], manifest["preference"]["path"]))
    print("GRPO:        %d -> %s" % (manifest["grpo"]["n"], manifest["grpo"]["path"]))


def _parse_export_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description="Export traces to training datasets")
    p.add_argument("--traces", required=True)
    p.add_argument("--output-dir", default=None)
    p.add_argument("--min-reward", type=float, default=None)
    p.add_argument("--min-gap", type=float, default=0.15)
    p.add_argument("--json", action="store_true")
    return p.parse_args()


def _parse_trace_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description="Collect scored traces from local models")
    p.add_argument("--models", required=True, help="Comma-separated Ollama model names")
    p.add_argument("--output-dir", default="./traces")
    p.add_argument("--tasks", default=None, help="Task list file (.txt or .jsonl)")
    p.add_argument("--limit", type=int, default=None, help="Use only the first N tasks")
    p.add_argument("--n-samples", type=int, default=1)
    p.add_argument("--num-predict", type=int, default=1024)
    p.add_argument("--temperature", type=float, default=0.8)
    p.add_argument("--seed", type=int, default=42)
    p.add_argument("--base-url", default="http://localhost:11434")
    p.add_argument("--timeout", type=float, default=600.0)
    p.add_argument("--no-think", action="store_true", help="Disable model thinking traces")
    p.add_argument("--no-resume", action="store_true", help="Ignore existing traces")
    p.add_argument("--model-opt", action="append", default=None)
    p.add_argument("--json", action="store_true")
    _add_rater_args(p)
    return p.parse_args()


def _parse_audit_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description="Rater agreement audit")
    p.add_argument("--corpus", required=True)
    p.add_argument("--rater-a", default="static")
    p.add_argument("--rater-b", default="decision")
    p.add_argument("--rater-model", default=None)
    p.add_argument("--output", default=None)
    p.add_argument("--json", action="store_true")
    return p.parse_args()


def _parse_train_args() -> argparse.Namespace:
    p = argparse.ArgumentParser()
    p.add_argument("--model", default="Qwen/Qwen2.5-Coder-7B")
    p.add_argument("--output-dir", default="./grpo_output")
    p.add_argument("--data", default=None)
    p.add_argument("--iterations", type=int, default=100)
    p.add_argument("--group-size", type=int, default=8)
    p.add_argument("--lr", type=float, default=1e-5)
    p.add_argument("--resume-from", default=None)
    p.add_argument("--backend", default="auto", choices=["auto", "mlx", "torch"])
    p.add_argument("--legacy-rewards", action="store_true")
    _add_rater_args(p)
    return p.parse_args()


def _parse_eval_args() -> argparse.Namespace:
    p = argparse.ArgumentParser()
    p.add_argument("code", nargs="?", default="-")
    p.add_argument("--file", default=None)
    p.add_argument("--judge-model", default="gpt-4o")
    p.add_argument("--json", action="store_true")
    _add_rater_args(p)
    return p.parse_args()


def _parse_reward_args() -> argparse.Namespace:
    p = argparse.ArgumentParser()
    p.add_argument("--task", required=True)
    p.add_argument("--code", required=True)
    p.add_argument("--legacy", action="store_true")
    p.add_argument("--json", action="store_true")
    _add_rater_args(p)
    return p.parse_args()


if __name__ == "__main__":
    main()