File size: 22,521 Bytes
5e30653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62ce2ff
5e30653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3bf152
 
 
 
 
 
 
 
 
62ce2ff
 
d3bf152
 
 
 
 
 
 
 
 
62ce2ff
 
5e30653
 
 
 
 
 
 
 
39e03eb
 
 
 
 
 
 
5e30653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3bf152
5e30653
 
 
 
62ce2ff
5e30653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3bf152
62ce2ff
5e30653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62ce2ff
 
 
d3bf152
5e30653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""OPD/DPCA optimizer steps on one B200, tracked with TensorBoard instead of W&B.

Why this file exists
--------------------
`reproduction/dpca_2gpu_train.py` (upstream, commit 927a8264) refuses to run when
W&B comes up offline:

    if wb_run.offline:
        raise RuntimeError("W&B initialized offline; online logging is required")

The company node cannot satisfy that: the egress proxy resets `api.wandb.ai` and
`wandb.ai` (curl rc=56) while `huggingface.co` and `pypi.org` pass. `WANDB_MODE`
does not rescue it either — the same CLI reads `run_id` right after `wandb.init`,
and in `disabled` mode `Run.id` asserts `self._settings.run_id is not None`, so it
dies before writing any summary.

We do not edit that file: it is hash-pinned by its own source manifest. So this
runner is a second launcher, and it is NOT the qualified CLI. What it does reuse,
straight from the pinned module, is every piece that touches the science:

    from dpca_2gpu_train import (
        _response_logps, _strip_trailing_special_tokens,
        _project_advantage_for_metrics, _gpu_metrics, _mean, _sha256,
    )
    from verl.trainer.ppo.core_algos import compute_policy_loss_opd
    from verl.workers.reward_manager.opd import TeacherClient

Those helpers and the two verl functions are imported, never reimplemented, so
the gradient being applied is computed by the same code the canary used. The only
thing this file changes is the sink: TensorBoard event files plus `metrics.jsonl`,
with no network call anywhere in the run.

Evidence class: `implementation_validation`, same as the canary, and the run
records `not_the_upstream_cli: true` so it can never be mistaken for a run of the
hash-pinned CLI.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import random
import sys
import time
from pathlib import Path
from typing import Any

import numpy as np
import torch
from omegaconf import OmegaConf
from torch.utils.tensorboard import SummaryWriter
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    get_constant_schedule_with_warmup,
)

# The pinned upstream launcher and the verl code it calls. Nothing here re-implements
# the objective: these imports are the whole point of this file.
REPO_ROOT = Path(os.environ.get("DPCA_REPO_ROOT", "/opt/dpca"))
sys.path.insert(0, str(REPO_ROOT / "reproduction"))
sys.path.insert(0, str(REPO_ROOT))

import dpca_2gpu_train as pinned  # noqa: E402  (path must exist first)

from verl.trainer.ppo.core_algos import compute_policy_loss_opd  # noqa: E402
from verl.workers.reward_manager.opd import TeacherClient  # noqa: E402


def verify_pinned_sources(config: dict[str, Any]) -> dict[str, Any]:
    """Re-run the upstream hash guard verbatim, then check the commit matches."""
    manifest_path = REPO_ROOT / "reproduction/source_manifest.json"
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    expected = manifest.get("effective_sha256", manifest["sha256"])
    actual = {
        relative: pinned._sha256(REPO_ROOT / relative) for relative in expected
    }
    if actual != expected:
        differing = sorted(
            key
            for key in set(expected) | set(actual)
            if expected.get(key) != actual.get(key)
        )
        raise RuntimeError(f"Pinned effective source hash mismatch: {differing}")
    if manifest["commit"] != config["source_commit"]:
        raise RuntimeError(
            f"Source commit mismatch: {manifest['commit']} != {config['source_commit']}"
        )
    return {
        "git_commit": manifest["commit"],
        "source_manifest_sha256": pinned._sha256(manifest_path),
        "source_files_verified": len(actual),
    }


def weight_fingerprint(model: torch.nn.Module) -> tuple[str, int]:
    """Digest a slice of every named parameter, plus how many carry gradients.

    My first version hashed `next(model.parameters())`, which for Llama is
    `embed_tokens.weight`. That tensor receives no gradient here — the loss only
    covers response tokens — so it never moves and the check reported
    "weights unchanged" after ten real optimizer steps. The instrument was wrong,
    not the run. Hashing every named parameter in a stable order covers the
    transformer body, which does receive gradient.
    """
    digest = hashlib.sha256()
    params = sorted(model.named_parameters(), key=lambda item: item[0])
    with_grad = sum(1 for _, param in params if param.grad is not None)
    for name, param in params:
        with torch.no_grad():
            slice_ = param.detach().float().reshape(-1)[:512].cpu().numpy()
        digest.update(name.encode("utf-8"))
        digest.update(str(slice_.shape).encode("ascii"))
        digest.update(slice_.tobytes())
    return digest.hexdigest(), with_grad


def device_records() -> list[dict[str, Any]]:
    records = []
    for index in range(torch.cuda.device_count()):
        props = torch.cuda.get_device_properties(index)
        records.append(
            {
                "index": index,
                "name": props.name,
                # Same guard the pinned CLI uses, and it earns its keep: the
                # torch build in the installed venv has no `major_minor`, while
                # the image torch does. Without the hasattr the run dies before
                # loading a model, on an attribute difference alone.
                "capability": list(props.major_minor)
                if hasattr(props, "major_minor")
                else list(torch.cuda.get_device_capability(index)),
                "total_memory_bytes": props.total_memory,
                "uuid": str(props.uuid) if hasattr(props, "uuid") else None,
            }
        )
    return records


def run(config: dict[str, Any], output_dir: Path) -> dict[str, Any]:
    execution = config.get("execution", {})
    expected_gpus = int(execution.get("gpu_count", 1))
    teacher_index = int(execution.get("teacher_device_index", 0))
    student_index = int(execution.get("student_device_index", 0))
    actual_gpus = torch.cuda.device_count()
    if actual_gpus != expected_gpus:
        raise RuntimeError(
            f"Expected exactly {expected_gpus} CUDA GPU(s); found {actual_gpus}"
        )
    if not (
        0 <= teacher_index < actual_gpus and 0 <= student_index < actual_gpus
    ):
        raise RuntimeError(
            f"Invalid placement: teacher={teacher_index} student={student_index} "
            f"cuda_device_count={actual_gpus}"
        )

    records = device_records()
    if not all("B200" in record["name"] for record in records):
        raise RuntimeError(f"Expected B200 device(s), got {records}")

    provenance = verify_pinned_sources(config)
    provenance.update(
        {
            "torch_version": torch.__version__,
            "cuda_runtime": torch.version.cuda,
            "cuda_device_count": actual_gpus,
            "python": sys.version.split()[0],
        }
    )

    seed = int(config["seed"])
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cuda.matmul.allow_tf32 = True

    output_dir.mkdir(parents=True, exist_ok=False)
    tb_dir = output_dir / "tensorboard"
    checkpoint_dir = output_dir / "checkpoint-final"
    metrics_path = output_dir / "metrics.jsonl"

    prompts = json.loads(
        Path(config["prompts_path"]).read_text(encoding="utf-8")
    )
    steps = int(config["optimizer"]["steps"])
    if len(prompts) < steps:
        raise RuntimeError(f"Need at least {steps} prompts; found {len(prompts)}")

    provenance["prompt_sha256"] = pinned._sha256(Path(config["prompts_path"]))
    provenance["prompt_count"] = len(prompts)
    effective_config_path = output_dir / "effective_config.json"
    effective_config_path.write_text(
        json.dumps({"config": config, "provenance": provenance}, indent=2, sort_keys=True),
        encoding="utf-8",
    )

    teacher_device = torch.device(f"cuda:{teacher_index}")
    student_device = torch.device(f"cuda:{student_index}")

    teacher_tokenizer = AutoTokenizer.from_pretrained(
        config["teacher"]["container_path"], local_files_only=True, use_fast=True
    )
    student_tokenizer = AutoTokenizer.from_pretrained(
        config["student"]["container_path"], local_files_only=True, use_fast=True
    )
    if student_tokenizer.pad_token_id is None:
        student_tokenizer.pad_token = student_tokenizer.eos_token

    teacher = AutoModelForCausalLM.from_pretrained(
        config["teacher"]["container_path"],
        local_files_only=True,
        dtype=torch.bfloat16,
        attn_implementation="sdpa",
    ).to(teacher_device)
    student = AutoModelForCausalLM.from_pretrained(
        config["student"]["container_path"],
        local_files_only=True,
        dtype=torch.bfloat16,
        attn_implementation="sdpa",
    ).to(student_device)
    teacher.eval()
    for parameter in teacher.parameters():
        parameter.requires_grad_(False)
    student.train()
    student.config.use_cache = False

    optimizer = torch.optim.AdamW(
        student.parameters(),
        lr=float(config["optimizer"]["learning_rate"]),
        weight_decay=float(config["optimizer"]["weight_decay"]),
    )
    scheduler = get_constant_schedule_with_warmup(
        optimizer, num_warmup_steps=int(config["optimizer"]["warmup_steps"])
    )
    loss_config = OmegaConf.create(
        {
            "clip_ratio": float(config["opd"]["clip_ratio_low"]),
            "clip_ratio_low": float(config["opd"]["clip_ratio_low"]),
            "clip_ratio_high": float(config["opd"]["clip_ratio_high"]),
            "clip_ratio_c": float(config["opd"]["clip_ratio_c"]),
            "policy_loss": {
                "opd_loss_max_clamp": float(config["opd"]["loss_max_clamp"])
            },
            "global_batch_info": {},
        }
    )

    writer = SummaryWriter(log_dir=str(tb_dir), flush_secs=5)
    fingerprint_before, _ = weight_fingerprint(student)
    writer.add_text("run/evidence_class", config["evidence_class"], 0)
    writer.add_text("run/source_commit", config["source_commit"], 0)
    writer.add_text("run/tracking_backend", "tensorboard", 0)
    writer.add_text("run/not_the_upstream_cli", "true", 0)
    writer.add_text("run/weight_fingerprint_before", fingerprint_before, 0)

    step_metrics: list[dict[str, Any]] = []
    run_start = time.perf_counter()
    for step_index in range(steps):
        optimizer_step = step_index + 1
        prompt = prompts[step_index]

        student_prompt_text = student_tokenizer.apply_chat_template(
            [{"role": "user", "content": prompt}],
            tokenize=False,
            add_generation_prompt=True,
        )
        teacher_prompt_text = teacher_tokenizer.apply_chat_template(
            [{"role": "user", "content": prompt}],
            tokenize=False,
            add_generation_prompt=True,
        )
        student_prompt_ids = student_tokenizer(
            student_prompt_text, add_special_tokens=False
        )["input_ids"]
        teacher_prompt_ids = teacher_tokenizer(
            teacher_prompt_text, add_special_tokens=False
        )["input_ids"]

        student.eval()
        generation_start = time.perf_counter()
        with torch.no_grad():
            prompt_tensor = torch.tensor(
                [student_prompt_ids], dtype=torch.long, device=student_device
            )
            generated = student.generate(
                input_ids=prompt_tensor,
                attention_mask=torch.ones_like(prompt_tensor),
                do_sample=True,
                temperature=float(config["rollout"]["temperature"]),
                top_p=float(config["rollout"]["top_p"]),
                top_k=int(config["rollout"]["top_k"]),
                min_new_tokens=int(config["rollout"]["min_new_tokens"]),
                max_new_tokens=int(config["rollout"]["max_new_tokens"]),
                pad_token_id=student_tokenizer.pad_token_id,
            )
        torch.cuda.synchronize(student_device)
        generation_seconds = time.perf_counter() - generation_start

        response_ids = pinned._strip_trailing_special_tokens(
            generated[0, len(student_prompt_ids) :].tolist(), student_tokenizer
        )
        if not response_ids:
            raise RuntimeError(f"Step {optimizer_step} produced no response tokens")
        response_text = student_tokenizer.decode(
            response_ids,
            skip_special_tokens=False,
            clean_up_tokenization_spaces=False,
        )
        teacher_response_ids = teacher_tokenizer(
            response_text, add_special_tokens=False
        )["input_ids"]
        if not teacher_response_ids:
            raise RuntimeError(
                f"Step {optimizer_step} produced no teacher response tokens"
            )

        score_start = time.perf_counter()
        old_logp = pinned._response_logps(
            student, student_prompt_ids, response_ids, student_device, grad=False
        ).detach()
        teacher_logp = pinned._response_logps(
            teacher, teacher_prompt_ids, teacher_response_ids, teacher_device, grad=False
        ).detach()
        torch.cuda.synchronize(teacher_device)
        torch.cuda.synchronize(student_device)
        score_seconds = time.perf_counter() - score_start

        aligned_cpu, chunk_ids_cpu, chunk_details, teacher_truncated = (
            TeacherClient._align_chunks(
                response_ids,
                teacher_response_ids,
                teacher_logp[0].float().cpu(),
                student_tokenizer,
                teacher_tokenizer,
                debug=True,
                large_chunk_threshold=int(config["opd"]["large_chunk_threshold"]),
            )
        )
        aligned = aligned_cpu.to(student_device).unsqueeze(0)
        chunk_ids = chunk_ids_cpu.to(student_device).unsqueeze(0)
        packed_teacher = torch.cat([aligned, chunk_ids], dim=-1)
        response_mask = torch.ones_like(old_logp, dtype=torch.float32)
        advantage = pinned._project_advantage_for_metrics(
            old_logp[0],
            aligned[0],
            chunk_ids[0],
            clamp=float(config["opd"]["loss_max_clamp"]),
        )

        student.train()
        optimizer.zero_grad(set_to_none=True)
        update_start = time.perf_counter()
        current_logp = pinned._response_logps(
            student, student_prompt_ids, response_ids, student_device, grad=True
        )
        lr_used = float(optimizer.param_groups[0]["lr"])
        loss, upstream_metrics = compute_policy_loss_opd(
            old_log_prob=old_logp,
            log_prob=current_logp,
            advantages=packed_teacher,
            response_mask=response_mask,
            loss_agg_mode=config["opd"]["loss_agg_mode"],
            config=loss_config,
        )
        if not torch.isfinite(loss):
            raise RuntimeError(f"Non-finite loss at step {optimizer_step}")
        loss.backward()
        grad_norm = torch.nn.utils.clip_grad_norm_(
            student.parameters(), float(config["optimizer"]["gradient_clip"])
        )
        if not torch.isfinite(grad_norm):
            raise RuntimeError(f"Non-finite grad norm at step {optimizer_step}")
        optimizer.step()
        scheduler.step()
        torch.cuda.synchronize(student_device)
        update_seconds = time.perf_counter() - update_start

        matched = [detail for detail in chunk_details if detail["type"] == "matched"]
        one_to_one = sum(
            1 for detail in matched if detail["n_stu"] == 1 and detail["n_tec"] == 1
        )
        inf_tokens = int(torch.isinf(aligned).sum().item())
        valid_tokens = len(response_ids) - inf_tokens
        total_seconds = generation_seconds + score_seconds + update_seconds

        metrics: dict[str, Any] = {
            "optimizer_step": optimizer_step,
            "loss/opd_policy": float(loss.detach().item()),
            "loss/ppo_kl": float(upstream_metrics["actor/ppo_kl"]),
            "loss/clip_fraction": float(upstream_metrics["actor/pg_clipfrac"]),
            "loss/clip_fraction_lower": float(
                upstream_metrics["actor/pg_clipfrac_lower"]
            ),
            "opd/inf_tokens": inf_tokens,
            "opd/inf_ratio": inf_tokens / max(len(response_ids), 1),
            "opd/valid_tokens": valid_tokens,
            "opd/chunks": len(matched),
            "opd/chunks_one_to_one": one_to_one,
            "opd/chunks_multi": len(matched) - one_to_one,
            "opd/teacher_truncated": int(teacher_truncated),
            "logp/student_mean": pinned._mean(old_logp),
            "logp/teacher_mean": pinned._mean(teacher_logp),
            "logp/student_sum": float(old_logp.detach().sum().item()),
            "logp/teacher_sum": float(teacher_logp.detach().sum().item()),
            "advantage/mean": pinned._mean(advantage),
            "advantage/min": float(advantage.detach().min().item()),
            "advantage/max": float(advantage.detach().max().item()),
            "advantage/std": float(
                advantage.detach().float().std(unbiased=False).item()
            ),
            "tokens/student_prompt": len(student_prompt_ids),
            "tokens/student_response": len(response_ids),
            "tokens/teacher_prompt": len(teacher_prompt_ids),
            "tokens/teacher_response": len(teacher_response_ids),
            "timing/generation_seconds": generation_seconds,
            "timing/scoring_seconds": score_seconds,
            "timing/update_seconds": update_seconds,
            "timing/step_seconds": total_seconds,
            "throughput/student_response_tokens_per_second": len(response_ids)
            / max(total_seconds, 1e-9),
            "optimizer/lr_used": lr_used,
            "optimizer/lr_next": float(scheduler.get_last_lr()[0]),
            "optimizer/grad_norm_before_clip": float(grad_norm.detach().item()),
            **pinned._gpu_metrics("teacher", teacher_index),
            **pinned._gpu_metrics("student", student_index),
        }
        metrics["opd/multi_chunk_ratio"] = metrics["opd/chunks_multi"] / max(
            metrics["opd/chunks"], 1
        )
        metrics["opd/max_student_tokens_per_chunk"] = max(
            (detail["n_stu"] for detail in matched), default=0
        )
        metrics["opd/max_teacher_tokens_per_chunk"] = max(
            (detail["n_tec"] for detail in matched), default=0
        )

        with metrics_path.open("a", encoding="utf-8") as handle:
            handle.write(json.dumps(metrics, sort_keys=True) + "\n")
        for name, value in metrics.items():
            if name != "optimizer_step" and isinstance(value, (int, float)):
                if np.isfinite(float(value)):
                    writer.add_scalar(name, float(value), optimizer_step)
        writer.flush()
        step_metrics.append(metrics)
        print("DPCA_TB_STEP_JSON=" + json.dumps(metrics, sort_keys=True), flush=True)

    checkpoint_dir.mkdir(parents=True, exist_ok=False)
    student.save_pretrained(checkpoint_dir, safe_serialization=True)
    student_tokenizer.save_pretrained(checkpoint_dir)
    torch.save(
        {
            "optimizer": optimizer.state_dict(),
            "scheduler": scheduler.state_dict(),
            "optimizer_steps": steps,
        },
        checkpoint_dir / "trainer_state.pt",
    )
    fingerprint_after, params_with_grad = weight_fingerprint(student)
    writer.add_text("run/weight_fingerprint_after", fingerprint_after, steps)

    summary = {
        "status": "completed",
        "evidence_class": config["evidence_class"],
        "run_id": config["run_id"],
        "optimizer_steps_completed": len(step_metrics),
        "not_the_upstream_cli": True,
        "tracking_backend": "tensorboard",
        "wandb_used": False,
        "network_used": False,
        "why_not_wandb": (
            "company node egress proxy resets api.wandb.ai/wandb.ai (curl rc=56); "
            "the pinned CLI raises on offline W&B and Run.id asserts run_id is not "
            "None under WANDB_MODE=disabled, so the objective is driven by this "
            "launcher with the pinned helpers and verl functions imported unchanged"
        ),
        "reused_pinned_symbols": [
            "dpca_2gpu_train._response_logps",
            "dpca_2gpu_train._strip_trailing_special_tokens",
            "dpca_2gpu_train._project_advantage_for_metrics",
            "dpca_2gpu_train._gpu_metrics",
            "dpca_2gpu_train._mean",
            "dpca_2gpu_train._sha256",
            "verl.trainer.ppo.core_algos.compute_policy_loss_opd",
            "verl.workers.reward_manager.opd.TeacherClient._align_chunks",
        ],
        "provenance": provenance,
        "b200_topology_verified": True,
        "gpu_count": expected_gpus,
        "device_placement": {
            "teacher_device_index": teacher_index,
            "student_device_index": student_index,
            "shared_device": teacher_index == student_index,
        },
        "devices": records,
        "tensorboard_dir": str(tb_dir),
        "checkpoint_dir": str(checkpoint_dir),
        "metrics_path": str(metrics_path),
        "student_weights_changed": fingerprint_after != fingerprint_before,
        "weight_fingerprint_before": fingerprint_before,
        "weight_fingerprint_after": fingerprint_after,
        "parameters_with_gradients": params_with_grad,
        "total_runtime_seconds": time.perf_counter() - run_start,
        "final_metrics": step_metrics[-1],
    }
    (output_dir / "summary.json").write_text(
        json.dumps(summary, indent=2, sort_keys=True), encoding="utf-8"
    )
    writer.close()
    print("DPCA_TB_SUMMARY_JSON=" + json.dumps(summary, sort_keys=True), flush=True)
    return summary


def main() -> None:
    os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", type=Path, required=True)
    parser.add_argument("--output-root", type=Path, default=Path("/runs"))
    args = parser.parse_args()
    config = json.loads(args.config.read_text(encoding="utf-8"))
    summary = run(config, args.output_root / config["run_id"])
    expected = int(config["optimizer"]["steps"])
    if summary["optimizer_steps_completed"] != expected:
        raise RuntimeError(
            f"Expected exactly {expected} optimizer steps, "
            f"got {summary['optimizer_steps_completed']}"
        )


if __name__ == "__main__":
    main()