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
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
"""Frozen training config and immutable planned-run manifest builders."""

from __future__ import annotations

import json
import math
from dataclasses import asdict, dataclass
from datetime import datetime
from pathlib import Path
from typing import Any, Literal

from ..atomic_io import atomic_write_json
from ..hashing import canonical_json, canonical_json_hash, is_git_revision, is_sha256
from .evi_po_contract import EVI_PO_ADAPTER_VERSION
from .papo_contract import (
    PAPO_ADAPTER_VERSION,
    PAPO_UPSTREAM_SOURCE_SHA256,
    PAPO_UPSTREAM_SOURCE_URL,
)
from .rewards import arm_trainer_kind, canonical_arm

TrainerKind = Literal["sft", "grpo", "papo", "evi_po"]
RunMode = Literal["sft", "smoke", "main"]
QWEN35_2B_REVISION = "15852e8c16360a2fea060d615a32b45270f8a8fc"
TRAINING_CONTRACT_VERSION = "evi_v2_constrained_answer_256_v1"
# Constrained decoding removes irrelevant formatting/runaway-generation noise
# while preserving every certified answer, including the public abstention
# token.  vLLM completes the regex and emits EOS; the 256-token cap remains a
# hard safety boundary rather than a routinely reached training event.
ANSWER_SCHEMA_REGEX = r"<answer>(<UNANSWERABLE>|[^<>\r\n]{1,128})</answer>"


class RunArtifactError(RuntimeError):
    """Raised when a frozen run identity or write-once artifact drifts."""


@dataclass(frozen=True)
class RuntimeTrainingConfig:
    """Fully resolved values required before a GPU launcher may run."""

    run_id: str
    trainer_kind: TrainerKind
    arm: str
    seed: int
    model_path: str
    model_revision: str
    model_snapshot_sha256: str
    dataset_path: str
    dataset_asset_root: str
    output_dir: str
    initial_checkpoint_path: str
    environment_lock_path: str
    environment_lock_sha256: str
    evaluation_manifest_path: str
    evaluation_manifest_sha256: str
    system_prompt_sha256: str
    precision: str
    attention_implementation: str
    max_prompt_tokens: int
    max_completion_tokens: int
    total_context_tokens: int
    per_device_train_batch_size: int
    gradient_accumulation_steps: int
    world_size: int
    generations_per_prompt: int
    checkpoint_interval: int
    max_optimizer_steps: int
    max_completion_tokens_per_run: int
    learning_rate: float
    lora_rank: int
    lora_alpha: int
    lora_dropout: float
    lora_target_modules: tuple[str, ...]
    comparison_slot_manifest_sha256: str | None = None
    backend_entrypoint: str | None = None
    use_vllm: bool = True
    run_mode: RunMode = "main"
    compatibility_gate_path: str | None = None
    evi_direction_loss_weight: float = 0.0
    evi_evidence_loss_weight: float = 0.0
    evi_direction_margin: float = 0.0
    papo_mask_ratio: float = 0.6
    papo_perception_loss_weight: float = 0.02

    def __post_init__(self) -> None:
        if not isinstance(self.run_id, str) or not self.run_id:
            raise RunArtifactError("run_id must be non-empty")
        if self.trainer_kind not in {"sft", "grpo", "papo", "evi_po"}:
            raise RunArtifactError(f"unsupported trainer kind: {self.trainer_kind}")
        if self.run_mode not in {"sft", "smoke", "main"}:
            raise RunArtifactError(f"unsupported run mode: {self.run_mode}")
        if self.trainer_kind == "sft" and self.run_mode != "sft":
            raise RunArtifactError("SFT trainer requires run_mode=sft")
        if self.trainer_kind != "sft" and self.run_mode not in {"smoke", "main"}:
            raise RunArtifactError("RL trainer requires run_mode=smoke or main")
        if self.trainer_kind != "sft":
            try:
                canonical = canonical_arm(self.arm)
            except ValueError as exc:
                raise RunArtifactError(f"unsupported RL arm: {self.arm}") from exc
            if canonical != self.arm:
                object.__setattr__(self, "arm", canonical)
        if self.trainer_kind != "sft" and self.trainer_kind != arm_trainer_kind(self.arm):
            raise RunArtifactError(
                f"trainer kind {self.trainer_kind!r} does not match arm {self.arm!r}"
            )
        evi_values = (
            self.evi_direction_loss_weight,
            self.evi_evidence_loss_weight,
            self.evi_direction_margin,
        )
        if any(
            isinstance(value, bool)
            or not isinstance(value, int | float)
            or not math.isfinite(float(value))
            or value < 0
            for value in evi_values
        ):
            raise RunArtifactError("EVI-PO weights and margin must be finite and non-negative")
        if self.trainer_kind != "evi_po" and any(value != 0.0 for value in evi_values):
            raise RunArtifactError("non-EVI trainers may not carry EVI-PO objective values")
        if self.trainer_kind != "sft":
            if not self.comparison_slot_manifest_sha256:
                raise RunArtifactError(
                    "RL runs require comparison_slot_manifest_sha256 for schedule fairness"
                )
            if not is_sha256(self.comparison_slot_manifest_sha256):
                raise RunArtifactError("comparison_slot_manifest_sha256 must be a SHA-256")
        elif self.comparison_slot_manifest_sha256 is not None and not is_sha256(
            self.comparison_slot_manifest_sha256
        ):
            raise RunArtifactError("comparison_slot_manifest_sha256 must be a SHA-256")
        if isinstance(self.seed, bool) or not isinstance(self.seed, int) or self.seed < 0:
            raise RunArtifactError("seed must be a non-negative integer")
        if not isinstance(self.model_revision, str) or not is_git_revision(self.model_revision):
            raise RunArtifactError("model_revision must be an exact 40-hex revision")
        if self.model_revision != QWEN35_2B_REVISION:
            raise RunArtifactError("model_revision does not match pinned Qwen3.5-2B")
        for name in (
            "model_snapshot_sha256",
            "environment_lock_sha256",
            "evaluation_manifest_sha256",
            "system_prompt_sha256",
        ):
            if not is_sha256(str(getattr(self, name))):
                raise RunArtifactError(f"{name} must be a SHA-256")
        numeric_positive = (
            "max_prompt_tokens",
            "max_completion_tokens",
            "total_context_tokens",
            "per_device_train_batch_size",
            "gradient_accumulation_steps",
            "world_size",
            "generations_per_prompt",
            "checkpoint_interval",
            "max_completion_tokens_per_run",
            "lora_rank",
            "lora_alpha",
        )
        for name in numeric_positive:
            value = getattr(self, name)
            if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
                raise RunArtifactError(f"{name} must be a positive integer")
        if self.max_prompt_tokens + self.max_completion_tokens != self.total_context_tokens:
            raise RunArtifactError("prompt + completion tokens must equal total context")
        if (
            isinstance(self.learning_rate, bool)
            or not isinstance(self.learning_rate, int | float)
            or not math.isfinite(self.learning_rate)
            or self.learning_rate <= 0
        ):
            raise RunArtifactError("learning_rate must be finite and positive")
        if (
            isinstance(self.lora_dropout, bool)
            or not isinstance(self.lora_dropout, int | float)
            or not math.isfinite(self.lora_dropout)
            or not 0 <= self.lora_dropout < 1
        ):
            raise RunArtifactError("lora_dropout must be finite and in [0,1)")
        if self.lora_target_modules != ("all-linear",):
            raise RunArtifactError("controlled runs require lora_target_modules=all-linear")
        for name in (
            "model_path",
            "dataset_path",
            "dataset_asset_root",
            "output_dir",
            "initial_checkpoint_path",
            "environment_lock_path",
            "evaluation_manifest_path",
        ):
            value = getattr(self, name)
            if (
                not isinstance(value, str)
                or not value.strip()
                or value.strip()
                in {
                    "required",
                    "set_by_common_oom_smoke",
                    "set_to_match_global_batch",
                    "TODO",
                    "TBD",
                }
            ):
                raise RunArtifactError(f"{name} is unresolved")
        if self.trainer_kind == "sft":
            if self.max_optimizer_steps != -1:
                raise RunArtifactError("SFT requires max_optimizer_steps=-1 for one epoch")
            if Path(self.initial_checkpoint_path).resolve() != Path(self.model_path).resolve():
                raise RunArtifactError(
                    "SFT initial_checkpoint_path must equal model_path (base initialization)"
                )
        elif self.run_mode == "smoke" and self.max_optimizer_steps != 20:
            raise RunArtifactError("controlled RL smoke requires exactly 20 optimizer steps")
        elif self.run_mode == "main" and self.max_optimizer_steps != 5750:
            raise RunArtifactError("controlled main RL runs require exactly 5,750 optimizer steps")
        if self.run_mode == "main":
            if (
                not isinstance(self.compatibility_gate_path, str)
                or not self.compatibility_gate_path.strip()
            ):
                raise RunArtifactError("main RL runs require compatibility_gate_path")
        elif self.compatibility_gate_path is not None:
            raise RunArtifactError("SFT and smoke plans may not carry a compatibility gate")
        if self.precision != "bf16":
            raise RunArtifactError("Qwen3.5 controlled runs require bf16 precision")
        if self.attention_implementation != "flash_attention_2":
            raise RunArtifactError("Qwen3.5 controlled runs require flash_attention_2")
        if not isinstance(self.use_vllm, bool):
            raise RunArtifactError("use_vllm must be boolean")
        if self.backend_entrypoint != "explicit_learning.training.backend:run":
            raise RunArtifactError("controlled runs require explicit_learning.training.backend:run")
        if (self.lora_rank, self.lora_alpha, self.lora_dropout) != (64, 128, 0.0):
            raise RunArtifactError("controlled runs require LoRA r=64, alpha=128, dropout=0")
        if self.learning_rate != 1e-6:
            raise RunArtifactError("controlled runs require learning_rate=1e-6")
        if (self.max_prompt_tokens, self.max_completion_tokens, self.total_context_tokens) != (
            4096,
            256,
            4352,
        ):
            raise RunArtifactError("controlled runs require a 4096/256/4352 token envelope")
        expected_generations = 1 if self.trainer_kind == "sft" else 4
        if self.generations_per_prompt != expected_generations:
            raise RunArtifactError(
                f"{self.trainer_kind} requires generations_per_prompt={expected_generations}"
            )
        if (
            self.trainer_kind != "sft"
            and self.global_prompt_batch_size % self.generations_per_prompt != 0
        ):
            raise RunArtifactError(
                "global prompt batch size must be divisible by generations_per_prompt"
            )
        token_cap = 6_000_000 if self.trainer_kind == "sft" else 24_000_000
        if self.max_completion_tokens_per_run > token_cap:
            raise RunArtifactError(
                f"{self.trainer_kind} token budget exceeds protocol cap {token_cap}"
            )

    @property
    def global_prompt_batch_size(self) -> int:
        return self.per_device_train_batch_size * self.gradient_accumulation_steps * self.world_size

    def to_dict(self) -> dict[str, Any]:
        value = asdict(self)
        value["lora_target_modules"] = list(self.lora_target_modules)
        value["global_prompt_batch_size"] = self.global_prompt_batch_size
        value["effective_completion_batch_size"] = self.global_prompt_batch_size
        value["unique_prompt_groups_per_optimizer_step"] = (
            self.global_prompt_batch_size
            if self.trainer_kind == "sft"
            else self.global_prompt_batch_size // self.generations_per_prompt
        )
        value["train_full_weights"] = False
        value["base_model_resource"] = "qwen35_2b"
        value["base_model_repo_id"] = "Qwen/Qwen3.5-2B"
        value["training_contract_version"] = TRAINING_CONTRACT_VERSION
        value["completion_only_sft_loss"] = self.trainer_kind == "sft"
        value["assistant_only_sft_loss"] = False
        value["reject_overlength_samples"] = True
        # No-thinking protocol: the system prompt, SFT gold, structured rollout
        # regex, and reward all share the same concise answer contract.
        value["enable_thinking"] = False
        value["structured_output_regex"] = (
            None if self.trainer_kind == "sft" else ANSWER_SCHEMA_REGEX
        )
        value["optimizer"] = {
            "name": "adamw_torch",
            "learning_rate": self.learning_rate,
            "weight_decay": 0.0,
            "betas": [0.9, 0.999],
            "eps": 1.0e-8,
        }
        value["scheduler"] = {"name": "cosine", "warmup_ratio": 0.03}
        value["gradient_checkpointing"] = True
        value["max_grad_norm"] = 1.0
        value["num_train_epochs"] = 1
        value["max_optimizer_steps"] = self.max_optimizer_steps
        value["temperature"] = None if self.trainer_kind == "sft" else 1.0
        value["top_p"] = None if self.trainer_kind == "sft" else 1.0
        value["loss_type"] = (
            "assistant_only_cross_entropy"
            if self.trainer_kind == "sft"
            else ("grpo" if self.trainer_kind == "papo" else "dr_grpo")
        )
        value["beta"] = (
            None if self.trainer_kind == "sft" else (0.01 if self.trainer_kind == "papo" else 0.0)
        )
        value["freeze_vision_tower"] = False
        value["freeze_multimodal_projector"] = False
        value["lora_exclude_modules"] = ["embeddings", "lm_head"]
        value["papo_config"] = (
            {
                "variant": "PAPO-G",
                "mask_ratio": self.papo_mask_ratio,
                "mask_type": "random",
                "perception_loss_weight": self.papo_perception_loss_weight,
                "der_loss_weight1": 0.0,
                "der_loss_weight2": 0.0,
                "require_gpu_contract_probe": self.run_mode == "smoke",
                "adapter_version": PAPO_ADAPTER_VERSION,
                "upstream_source_url": PAPO_UPSTREAM_SOURCE_URL,
                "upstream_source_sha256": PAPO_UPSTREAM_SOURCE_SHA256,
            }
            if self.trainer_kind == "papo"
            else None
        )
        value["evi_po_config"] = (
            {
                "adapter_version": EVI_PO_ADAPTER_VERSION,
                "lambda_direction": self.evi_direction_loss_weight,
                "lambda_evidence": self.evi_evidence_loss_weight,
                "margin": self.evi_direction_margin,
                "required_relationships": ["FULL", "CONTROL", "MISSING"],
                "optional_relationships": ["SUBSTITUTE"],
                "candidate_support": "group_answers_plus_unanswerable",
                "evidence_supervision_relation": "FULL",
                "evidence_sources": [
                    "executor_dependency_nodes_projected_through_node_map",
                    "source_annotation_explicit_mask",
                    "source_annotation_bboxes",
                ],
                "attention_capture": "last_full_attention_layer_eager_forward_hook",
                "require_gpu_contract_probe": (
                    self.run_mode == "smoke"
                    and (
                        self.evi_direction_loss_weight > 0.0 or self.evi_evidence_loss_weight > 0.0
                    )
                ),
                "zero_weight_reduction": "exact_parent_grpo_path",
            }
            if self.trainer_kind == "evi_po"
            else None
        )
        value["vllm_config"] = (
            {
                "mode": "colocate",
                # Throughput-only knob: this is the fraction of GPU memory vLLM
                # reserves for its KV cache during the rollout (generation) phase.
                # Raising it lets more completions generate concurrently, which
                # speeds up RL rollout — the dominant runtime cost — WITHOUT
                # changing which tokens are sampled (seed + prompt + sampling
                # params are unchanged), so completions, gradients, and the
                # trained model are identical. The experimental batch sizes
                # (per_device_train_batch_size, gradient_accumulation_steps,
                # generations_per_prompt) are untouched. With enable_sleep_mode
                # vLLM frees its KV cache for the batch-1 LoRA training step, so
                # the rollout cap and the training step do not contend: a high
                # cap enlarges only the rollout KV cache. 0.85 on 80GB H100s
                # keeps ~67GB for vLLM weights+KV during rollout while the
                # sleep-mode training step reclaims the KV portion. Lower if a
                # colocate OOM appears (the smoke gate requires 0).
                "gpu_memory_utilization": 0.85,
                "max_model_length": self.total_context_tokens,
                "tensor_parallel_size": 1,
                "enable_sleep_mode": True,
                "structured_outputs_regex": ANSWER_SCHEMA_REGEX,
            }
            if self.use_vllm
            else None
        )
        value["token_budget_kind"] = (
            "assistant_tokens" if self.trainer_kind == "sft" else "sampled_completion_tokens"
        )
        value["sampled_completion_token_budget_role"] = (
            None if self.trainer_kind == "sft" else "hard_safety_ceiling_not_equality_target"
        )
        value["requires_forced_five_step_process_resume"] = self.run_mode == "smoke"
        return value


def build_run_manifest(
    config: RuntimeTrainingConfig,
    *,
    source_config_sha256: str,
    dataset_manifest_sha256: str,
    initial_checkpoint_sha256: str,
    code_commit: str,
    created_at: str,
    launcher_command: tuple[str, ...],
) -> tuple[dict[str, Any], dict[str, Any]]:
    """Return frozen config and a manifest that says ``planned``, never trained."""

    for name, value in (
        ("source_config_sha256", source_config_sha256),
        ("dataset_manifest_sha256", dataset_manifest_sha256),
        ("initial_checkpoint_sha256", initial_checkpoint_sha256),
    ):
        if not isinstance(value, str) or not is_sha256(value):
            raise RunArtifactError(f"{name} must be a SHA-256")
    if not isinstance(code_commit, str) or not is_git_revision(code_commit):
        raise RunArtifactError("code_commit must be an exact 40-hex revision")
    if not isinstance(created_at, str) or not created_at:
        raise RunArtifactError("created_at must be supplied")
    try:
        parsed_created_at = datetime.fromisoformat(created_at.replace("Z", "+00:00"))
    except ValueError as exc:
        raise RunArtifactError("created_at must be ISO-8601") from exc
    if parsed_created_at.tzinfo is None:
        raise RunArtifactError("created_at must include a timezone")
    if not launcher_command or any(not str(part) for part in launcher_command):
        raise RunArtifactError("launcher_command must be explicit and non-empty")
    frozen = {
        "schema_version": 1,
        "source_config_sha256": source_config_sha256,
        "runtime": config.to_dict(),
    }
    frozen_sha = canonical_json_hash(frozen)
    manifest = {
        "schema_version": 1,
        "kind": "training_run_plan",
        "status": "planned",
        "trained": False,
        "run_id": config.run_id,
        "arm": config.arm,
        "seed": config.seed,
        "trainer_kind": config.trainer_kind,
        "run_mode": config.run_mode,
        "code_commit": code_commit,
        "created_at": created_at,
        "frozen_config_sha256": frozen_sha,
        "dataset_manifest_sha256": dataset_manifest_sha256,
        "initial_checkpoint_sha256": initial_checkpoint_sha256,
        "model_snapshot_sha256": config.model_snapshot_sha256,
        "environment_lock_sha256": config.environment_lock_sha256,
        "evaluation_manifest_sha256": config.evaluation_manifest_sha256,
        "system_prompt_sha256": config.system_prompt_sha256,
        "comparison_slot_manifest_sha256": config.comparison_slot_manifest_sha256,
        "launcher_command": list(launcher_command),
    }
    return frozen, manifest


def _write_once(path: Path, value: dict[str, Any]) -> None:
    if path.exists():
        try:
            existing = json.loads(path.read_text(encoding="utf-8"))
        except json.JSONDecodeError as exc:
            raise RunArtifactError(f"existing frozen artifact is invalid JSON: {path}") from exc
        if canonical_json(existing) != canonical_json(value):
            raise RunArtifactError(f"refusing to overwrite drifted frozen artifact: {path}")
        return
    atomic_write_json(path, value)


def write_frozen_run(
    run_dir: str | Path,
    *,
    frozen_config: dict[str, Any],
    run_manifest: dict[str, Any],
) -> tuple[Path, Path]:
    directory = Path(run_dir)
    directory.mkdir(parents=True, exist_ok=True)
    config_path = directory / "frozen-config.json"
    manifest_path = directory / "run-manifest.json"
    _write_once(config_path, frozen_config)
    _write_once(manifest_path, run_manifest)
    return config_path, manifest_path