tenseleyflow/documentlanguagemodel / b6deabb

Browse files

style: ruff format pass + embed_warmup ARG002 ignore for HF callback protocol

Authored by espadonne
SHA
b6deabb764cf7506bb56284fad6d257aa76ce586
Parents
19f5a6c
Tree
557a338

98 changed files

StatusFile+-
M pyproject.toml 4 0
M src/dlm/base_models/probes.py 1 3
M src/dlm/cli/commands.py 15 41
M src/dlm/cli/scaffold.py 7 22
M src/dlm/data/formatter.py 5 1
M src/dlm/directives/cache.py 5 9
M src/dlm/directives/cache_key.py 1 3
M src/dlm/directives/discovery.py 2 8
M src/dlm/directives/expand.py 5 17
M src/dlm/directives/merge.py 1 5
M src/dlm/directives/safety.py 1 3
M src/dlm/doc/parser.py 3 8
M src/dlm/doc/schema.py 2 8
M src/dlm/doc/serializer.py 4 2
M src/dlm/export/runner.py 2 5
M src/dlm/export/weighted_merge.py 10 26
M src/dlm/hardware/capabilities.py 1 3
M src/dlm/hardware/plan.py 1 3
M src/dlm/hardware/refusals.py 4 11
M src/dlm/inference/backends/mlx_backend.py 1 2
M src/dlm/inference/loader.py 1 3
M src/dlm/metrics/queries.py 1 3
M src/dlm/metrics/sinks/wandb.py 1 2
M src/dlm/share/hf_sink.py 1 3
M src/dlm/share/peer.py 2 7
M src/dlm/share/pull.py 2 6
M src/dlm/share/push.py 7 7
M src/dlm/share/signing.py 3 6
M src/dlm/share/sinks.py 3 9
M src/dlm/share/url_sink.py 9 12
M src/dlm/store/inspect.py 1 1
M src/dlm/store/paths.py 2 5
M src/dlm/templates/init.py 1 2
M src/dlm/train/checkpoint_commit.py 5 14
M src/dlm/train/cpt/embed_warmup.py 15 3
M src/dlm/train/cpt/schedule.py 2 6
M src/dlm/train/cpt/vocab_gap.py 7 14
M src/dlm/train/distributed/rank_env.py 2 6
M src/dlm/train/multi_adapter/router.py 1 2
M src/dlm/train/preference/dpo_phase.py 2 6
M src/dlm/train/preference/dpo_trainer.py 1 3
M src/dlm/train/preference/errors.py 1 3
M src/dlm/train/preference/orpo_phase.py 2 7
M src/dlm/train/preference/phase_orchestrator.py 2 6
M src/dlm/train/trainer.py 1 3
M tests/integration/directives/test_auto_scaffold_cycle.py 2 6
M tests/integration/directives/test_dlm_dir_descent.py 25 27
M tests/integration/directives/test_full_cycle.py 1 2
M tests/integration/metrics/test_full_cycle.py 1 3
M tests/integration/train/multi_adapter/test_two_adapters.py 4 4
M tests/integration/train/multi_adapter/test_weighted_merge.py 3 9
M tests/integration/train/preference/test_dpo_tinymodel.py 10 2
M tests/integration/train/preference/test_orpo_tinymodel.py 10 2
M tests/unit/cli/test_prompt_adapter_flag.py 1 3
M tests/unit/cli/test_serve_guard.py 5 8
M tests/unit/cli/test_train_scaffold_cli.py 42 35
M tests/unit/directives/test_cache.py 1 3
M tests/unit/directives/test_defaults.py 1 3
M tests/unit/directives/test_discovery.py 2 6
M tests/unit/directives/test_expand.py 4 18
M tests/unit/directives/test_merge.py 56 38
M tests/unit/directives/test_safety.py 1 5
M tests/unit/doc/test_fence_adapter_suffix.py 2 6
M tests/unit/doc/test_migration_v1_to_v2.py 1 3
M tests/unit/doc/test_round_trip_v4_adapters.py 1 3
M tests/unit/doc/test_schema.py 5 15
M tests/unit/eval/test_summary.py 2 6
M tests/unit/export/test_vendoring.py 1 3
M tests/unit/export/test_weighted_merge.py 1 3
M tests/unit/hardware/test_capabilities.py 1 3
M tests/unit/hardware/test_f28_multi_adapter_qlora.py 5 15
M tests/unit/hardware/test_plan.py 6 18
M tests/unit/inference/test_resolve_adapter_path.py 2 6
M tests/unit/lock/test_mismatch_policy.py 3 3
M tests/unit/metrics/test_db_schema.py 3 10
M tests/unit/metrics/test_queries.py 1 3
M tests/unit/replay/test_store.py 7 21
M tests/unit/share/test_peer_tokens.py 1 3
M tests/unit/store/test_inspect_named_adapters.py 1 3
M tests/unit/store/test_paths_named_adapters.py 2 8
M tests/unit/templates/test_registry.py 3 8
M tests/unit/test_templates_parse.py 1 2
M tests/unit/train/cpt/test_embed_warmup.py 4 6
M tests/unit/train/cpt/test_schedule.py 8 25
M tests/unit/train/cpt/test_vocab_gap.py 2 6
M tests/unit/train/distributed/test_rank_env.py 1 3
M tests/unit/train/multi_adapter/test_orchestrator.py 3 9
M tests/unit/train/multi_adapter/test_router.py 9 32
M tests/unit/train/preference/test_determinism_plumbing.py 4 12
M tests/unit/train/preference/test_dpo_dataset.py 1 3
M tests/unit/train/preference/test_dpo_phase.py 3 9
M tests/unit/train/preference/test_dpo_trainer.py 2 6
M tests/unit/train/preference/test_method_registry.py 1 0
M tests/unit/train/preference/test_orpo_phase.py 3 9
M tests/unit/train/preference/test_orpo_trainer.py 1 3
M tests/unit/train/preference/test_phase_orchestrator.py 2 7
M tests/unit/train/test_resolve_adapter_hparams.py 6 18
M tests/unit/watch/test_status.py 3 9
pyproject.tomlmodified
@@ -137,6 +137,10 @@ ignore = [
137137
 # will take so `--help` reflects the shipping surface — even though the
138138
 # stub body discards them.
139139
 "src/dlm/cli/commands.py" = ["ARG001"]
140
+# HuggingFace Trainer callbacks MUST accept `args`/`state`/`control`
141
+# positionally even when the implementation only reads some of them —
142
+# HF dispatches them by position. ARG002 for these wrappers is noise.
143
+"src/dlm/train/cpt/embed_warmup.py" = ["ARG002"]
140144
 
141145
 [tool.ruff.format]
142146
 quote-style = "double"
src/dlm/base_models/probes.pymodified
@@ -378,9 +378,7 @@ def probe_pretokenizer_hash(
378378
 # --- aggregate ---------------------------------------------------------------
379379
 
380380
 
381
-def run_all(
382
-    spec: BaseModelSpec, *, skip_export_probes: bool = False
383
-) -> ProbeReport:
381
+def run_all(spec: BaseModelSpec, *, skip_export_probes: bool = False) -> ProbeReport:
384382
     """Run every probe; aggregate into a `ProbeReport`.
385383
 
386384
     `GatedModelError` from an individual probe propagates immediately —
src/dlm/cli/commands.pymodified
@@ -139,9 +139,7 @@ def init_cmd(
139139
         from dlm.templates import TemplateError, apply_template
140140
 
141141
         try:
142
-            applied_result = apply_template(
143
-                template, path, force=force, accept_license=True
144
-            )
142
+            applied_result = apply_template(template, path, force=force, accept_license=True)
145143
         except TemplateError as exc:
146144
             console.print(f"[red]init:[/red] {exc}")
147145
             raise typer.Exit(code=1) from exc
@@ -1494,9 +1492,7 @@ def metrics_cmd(
14941492
     parsed = parse_file(path)
14951493
     store = for_dlm(parsed.frontmatter.dlm_id)
14961494
 
1497
-    runs = recent_runs(
1498
-        store.root, limit=limit, phase=phase, since=since_delta, run_id=run_id
1499
-    )
1495
+    runs = recent_runs(store.root, limit=limit, phase=phase, since=since_delta, run_id=run_id)
15001496
 
15011497
     if run_id is not None:
15021498
         # Drill-down: show this run's steps + evals.
@@ -1520,9 +1516,7 @@ def metrics_cmd(
15201516
             writer.writerow(["step", "loss", "lr", "grad_norm", "val_loss"])
15211517
             eval_by_step = {e.step: e.val_loss for e in evals}
15221518
             for s in steps:
1523
-                writer.writerow(
1524
-                    [s.step, s.loss, s.lr, s.grad_norm, eval_by_step.get(s.step)]
1525
-                )
1519
+                writer.writerow([s.step, s.loss, s.lr, s.grad_norm, eval_by_step.get(s.step)])
15261520
             return
15271521
         console.print(
15281522
             f"[green]run_id={run.run_id}[/green]  phase={run.phase}  "
@@ -1545,9 +1539,7 @@ def metrics_cmd(
15451539
         writer = csv.writer(sys.stdout)
15461540
         writer.writerow(["run_id", "phase", "seed", "status", "started_at", "ended_at"])
15471541
         for r in runs:
1548
-            writer.writerow(
1549
-                [r.run_id, r.phase, r.seed, r.status, r.started_at, r.ended_at]
1550
-            )
1542
+            writer.writerow([r.run_id, r.phase, r.seed, r.status, r.started_at, r.ended_at])
15511543
         return
15521544
 
15531545
     if not runs:
@@ -1690,8 +1682,8 @@ def show_cmd(
16901682
         raise typer.Exit(code=1) from exc
16911683
 
16921684
     store = for_dlm(parsed.frontmatter.dlm_id)
1693
-    training_sources, discovered_configs = (
1694
-        _summarize_training_sources_and_discovered(parsed, path.resolve().parent)
1685
+    training_sources, discovered_configs = _summarize_training_sources_and_discovered(
1686
+        parsed, path.resolve().parent
16951687
     )
16961688
     # Store may not exist yet (no `dlm train` run). Treat that as an
16971689
     # informational state rather than an error — useful after `dlm init`.
@@ -1830,9 +1822,7 @@ def _human_size(n: int) -> str:
18301822
     return f"{n} PB"
18311823
 
18321824
 
1833
-def _summarize_training_sources(
1834
-    parsed: object, base_path: Path
1835
-) -> list[dict[str, object]] | None:
1825
+def _summarize_training_sources(parsed: object, base_path: Path) -> list[dict[str, object]] | None:
18361826
     """Best-effort resolution of `training.sources` for `dlm show`.
18371827
 
18381828
     Returns None when the frontmatter declares no directives; returns
@@ -1905,9 +1895,7 @@ def _summarize_training_sources_and_discovered(
19051895
                 "has_ignore": bool(dc.ignore_rules),
19061896
                 "include": list(dc.config.include) if dc.config else [],
19071897
                 "exclude": list(dc.config.exclude) if dc.config else [],
1908
-                "exclude_defaults": (
1909
-                    dc.config.exclude_defaults if dc.config else True
1910
-                ),
1898
+                "exclude_defaults": (dc.config.exclude_defaults if dc.config else True),
19111899
                 "metadata": dict(dc.config.metadata) if dc.config else {},
19121900
                 "ignore_rules": len(dc.ignore_rules),
19131901
             }
@@ -1915,9 +1903,7 @@ def _summarize_training_sources_and_discovered(
19151903
     return records, discovered_records
19161904
 
19171905
 
1918
-def _summarize_training_cache(
1919
-    cache_dir: Path, store_root: Path
1920
-) -> dict[str, object] | None:
1906
+def _summarize_training_cache(cache_dir: Path, store_root: Path) -> dict[str, object] | None:
19211907
     """Return a JSON-friendly snapshot of the tokenized-section cache.
19221908
 
19231909
     None when the cache dir doesn't exist (store never trained with
@@ -1956,9 +1942,7 @@ def _render_training_cache_text(console: object, snap: dict[str, object]) -> Non
19561942
         console.print(f"    last hit rate:  {float(rate):.1%}")
19571943
 
19581944
 
1959
-def _render_training_sources_text(
1960
-    console: object, records: list[dict[str, object]]
1961
-) -> None:
1945
+def _render_training_sources_text(console: object, records: list[dict[str, object]]) -> None:
19621946
     from rich.console import Console
19631947
 
19641948
     assert isinstance(console, Console)
@@ -2110,9 +2094,7 @@ def push_cmd(
21102094
         bool,
21112095
         typer.Option("--sign", help="Sign the pack with minisign before upload."),
21122096
     ] = False,
2113
-    include_exports: Annotated[
2114
-        bool, typer.Option("--include-exports")
2115
-    ] = False,
2097
+    include_exports: Annotated[bool, typer.Option("--include-exports")] = False,
21162098
     include_base: Annotated[bool, typer.Option("--include-base")] = False,
21172099
     include_logs: Annotated[bool, typer.Option("--include-logs")] = False,
21182100
     licensee: Annotated[
@@ -2149,10 +2131,7 @@ def push_cmd(
21492131
         raise typer.Exit(code=1) from exc
21502132
 
21512133
     size_mb = result.bytes_sent / (1024 * 1024)
2152
-    console.print(
2153
-        f"[green]pushed:[/green] {result.destination} "
2154
-        f"({size_mb:.2f} MB)"
2155
-    )
2134
+    console.print(f"[green]pushed:[/green] {result.destination} ({size_mb:.2f} MB)")
21562135
     if result.sink_kind.value == "hf":
21572136
         console.print(f"[dim]install:[/dim] dlm pull {result.destination}")
21582137
     if result.detail:
@@ -2197,10 +2176,7 @@ def pull_cmd(
21972176
         raise typer.Exit(code=1) from exc
21982177
 
21992178
     size_mb = result.bytes_received / (1024 * 1024)
2200
-    console.print(
2201
-        f"[green]pulled:[/green] {result.source} → {result.dlm_path} "
2202
-        f"({size_mb:.2f} MB)"
2203
-    )
2179
+    console.print(f"[green]pulled:[/green] {result.source} → {result.dlm_path} ({size_mb:.2f} MB)")
22042180
 
22052181
     status = result.verification.status
22062182
     if status == VerifyStatus.VERIFIED:
@@ -2265,8 +2241,7 @@ def serve_cmd(
22652241
     store = for_dlm(dlm_id)
22662242
     if not store.manifest.exists():
22672243
         console.print(
2268
-            f"[red]serve:[/red] no training state for {dlm_id} — run "
2269
-            "[bold]dlm train[/bold] first."
2244
+            f"[red]serve:[/red] no training state for {dlm_id} — run [bold]dlm train[/bold] first."
22702245
         )
22712246
         raise typer.Exit(code=1)
22722247
 
@@ -2387,8 +2362,7 @@ def cache_prune_cmd(
23872362
     seconds = _parse_duration(older_than)
23882363
     if seconds is None:
23892364
         console.print(
2390
-            f"[red]cache:[/red] invalid --older-than {older_than!r} "
2391
-            "(expected e.g. 30d, 12h, 45m)"
2365
+            f"[red]cache:[/red] invalid --older-than {older_than!r} (expected e.g. 30d, 12h, 45m)"
23922366
         )
23932367
         raise typer.Exit(code=2)
23942368
 
src/dlm/cli/scaffold.pymodified
@@ -83,9 +83,7 @@ def scaffold_train_target(
8383
     if not target.exists():
8484
         raise ScaffoldError(f"target does not exist: {target}", path=target)
8585
     if not target.is_dir():
86
-        raise ScaffoldError(
87
-            f"scaffold expects a directory, got file: {target}", path=target
88
-        )
86
+        raise ScaffoldError(f"scaffold expects a directory, got file: {target}", path=target)
8987
 
9088
     dlm_dir = target / _SCAFFOLD_DIR
9189
     existing = sorted(dlm_dir.glob("*.dlm")) if dlm_dir.is_dir() else []
@@ -105,13 +103,9 @@ def scaffold_train_target(
105103
             return ScaffoldResult(dlm_path=named_match, scaffolded=False, dlm_id=dlm_id)
106104
         if name_is_default and len(existing) == 1:
107105
             dlm_id = _dlm_id_from_file(existing[0])
108
-            return ScaffoldResult(
109
-                dlm_path=existing[0], scaffolded=False, dlm_id=dlm_id
110
-            )
106
+            return ScaffoldResult(dlm_path=existing[0], scaffolded=False, dlm_id=dlm_id)
111107
         if name_is_default and len(existing) > 1:
112
-            listing = "\n".join(
113
-                f"  dlm train {target} --name {c.stem}" for c in existing
114
-            )
108
+            listing = "\n".join(f"  dlm train {target} --name {c.stem}" for c in existing)
115109
             raise ScaffoldError(
116110
                 f"multiple .dlm files found under {target / _SCAFFOLD_DIR}; "
117111
                 f"pass --name to pick one:\n{listing}",
@@ -128,11 +122,7 @@ def scaffold_train_target(
128122
         )
129123
 
130124
     dlm_path = dlm_dir / f"{name}.dlm"
131
-    existing_id = (
132
-        _dlm_id_from_file(dlm_path)
133
-        if rescaffold and dlm_path.is_file()
134
-        else None
135
-    )
125
+    existing_id = _dlm_id_from_file(dlm_path) if rescaffold and dlm_path.is_file() else None
136126
 
137127
     dlm_id = existing_id or mint_ulid()
138128
     dlm_dir.mkdir(parents=True, exist_ok=True)
@@ -146,9 +136,7 @@ def scaffold_train_target(
146136
         policy=policy,
147137
         target=target,
148138
     )
149
-    _LOG.info(
150
-        "scaffold: wrote %s (dlm_id=%s, base=%s)", dlm_path, dlm_id, base
151
-    )
139
+    _LOG.info("scaffold: wrote %s (dlm_id=%s, base=%s)", dlm_path, dlm_id, base)
152140
     return ScaffoldResult(dlm_path=dlm_path, scaffolded=True, dlm_id=dlm_id)
153141
 
154142
 
@@ -205,17 +193,14 @@ def _write_scaffold(
205193
         [
206194
             "---",
207195
             "",
208
-            "# Auto-scaffolded by `dlm train`. Edit the frontmatter above "
209
-            "to refine training.",
196
+            "# Auto-scaffolded by `dlm train`. Edit the frontmatter above to refine training.",
210197
             "",
211198
         ]
212199
     )
213200
     atomic_write_text(dlm_path, "\n".join(lines))
214201
 
215202
 
216
-def _build_include_globs(
217
-    include: tuple[str, ...], *, recursive: bool
218
-) -> tuple[str, ...]:
203
+def _build_include_globs(include: tuple[str, ...], *, recursive: bool) -> tuple[str, ...]:
219204
     """Map `--include` flags + `--recursive` to frontmatter globs.
220205
 
221206
     Empty `--include` + `--recursive` → `["**/*"]`: train on every
src/dlm/data/formatter.pymodified
@@ -57,7 +57,11 @@ def make_formatting_func(tokenizer: PreTrainedTokenizerBase) -> FormattingFunc:
5757
             if not isinstance(text, str):
5858
                 raise DataFormatError(f"`text` field must be str, got {type(text).__name__}")
5959
             return text
60
-        if row.get("prompt") is not None and row.get("chosen") is not None and row.get("rejected") is not None:
60
+        if (
61
+            row.get("prompt") is not None
62
+            and row.get("chosen") is not None
63
+            and row.get("rejected") is not None
64
+        ):
6165
             raise DataFormatError(
6266
                 "preference rows (prompt/chosen/rejected) must be routed to DPOTrainer, "
6367
                 "not SFTTrainer's formatting_func"
src/dlm/directives/cache.pymodified
@@ -132,9 +132,7 @@ class TokenizedCache:
132132
     # ---- Open / construct --------------------------------------------
133133
 
134134
     @classmethod
135
-    def open(
136
-        cls, root: Path, *, max_bytes: int = _DEFAULT_MAX_BYTES
137
-    ) -> TokenizedCache:
135
+    def open(cls, root: Path, *, max_bytes: int = _DEFAULT_MAX_BYTES) -> TokenizedCache:
138136
         """Open (or create) a cache at `root`.
139137
 
140138
         Creates the directory layout idempotently. Missing manifest →
@@ -343,17 +341,15 @@ class TokenizedCache:
343341
         mid-put fallback.
344342
         """
345343
         cutoff = time.time() - older_than_seconds
346
-        stale_keys = [
347
-            e.key_str
348
-            for e in self._manifest.values()
349
-            if e.last_access_ts < cutoff
350
-        ]
344
+        stale_keys = [e.key_str for e in self._manifest.values() if e.last_access_ts < cutoff]
351345
         for key_str in stale_keys:
352346
             entry = self._manifest[key_str]
353347
             self._entry_path(entry).unlink(missing_ok=True)
354348
             del self._manifest[key_str]
355349
         if stale_keys:
356
-            _LOG.info("cache: pruned %d entries older than %ds", len(stale_keys), older_than_seconds)
350
+            _LOG.info(
351
+                "cache: pruned %d entries older than %ds", len(stale_keys), older_than_seconds
352
+            )
357353
         return len(stale_keys)
358354
 
359355
     def clear(self) -> int:
src/dlm/directives/cache_key.pymodified
@@ -50,9 +50,7 @@ class CacheKey:
5050
         birthday threshold. The full sha is persisted in the manifest
5151
         for verification if a collision ever occurs in practice.
5252
         """
53
-        return (
54
-            f"{self.section_id}.{self.tokenizer_sha[:12]}.seq{self.sequence_len}.npz"
55
-        )
53
+        return f"{self.section_id}.{self.tokenizer_sha[:12]}.seq{self.sequence_len}.npz"
5654
 
5755
     def shard(self) -> str:
5856
         """First 2 hex chars of section_id — the directory shard."""
src/dlm/directives/discovery.pymodified
@@ -76,11 +76,7 @@ def discover_configs(root: Path) -> tuple[DiscoveredConfig, ...]:
7676
         anchor = dlm_dir.parent
7777
         config = _load_training_yaml(dlm_dir / _CONFIG_FILENAME)
7878
         ignore_rules = _load_ignore(dlm_dir / _IGNORE_FILENAME)
79
-        discovered.append(
80
-            DiscoveredConfig(
81
-                anchor=anchor, config=config, ignore_rules=ignore_rules
82
-            )
83
-        )
79
+        discovered.append(DiscoveredConfig(anchor=anchor, config=config, ignore_rules=ignore_rules))
8480
 
8581
     discovered.sort(key=lambda d: len(d.anchor.as_posix()))
8682
     return tuple(discovered)
@@ -121,9 +117,7 @@ def _load_training_yaml(path: Path) -> DlmTrainingConfig | None:
121117
     try:
122118
         return DlmTrainingConfig.model_validate(raw)
123119
     except ValidationError as exc:
124
-        _LOG.warning(
125
-            "discovery: %s: schema violation (%s); skipping config", path, exc
126
-        )
120
+        _LOG.warning("discovery: %s: schema violation (%s); skipping config", path, exc)
127121
         return None
128122
 
129123
 
src/dlm/directives/expand.pymodified
@@ -100,9 +100,7 @@ def expand_sources(parsed: ParsedDlm, *, base_path: Path) -> ExpandResult:
100100
     if not directives:
101101
         return ExpandResult(sections=(), provenance=(), discovered=())
102102
 
103
-    effective_base = (
104
-        base_path.parent if base_path.name == ".dlm" else base_path
105
-    )
103
+    effective_base = base_path.parent if base_path.name == ".dlm" else base_path
106104
     strict = training.sources_policy == "strict"
107105
     sections: list[Section] = []
108106
     provenance: list[SourceProvenance] = []
@@ -159,10 +157,7 @@ def _expand_one(
159157
     header_root = resolved_root if resolved_root.is_dir() else resolved_root.parent
160158
 
161159
     for file_path in _iter_candidates(resolved_root):
162
-        if (
163
-            directive.max_files is not None
164
-            and len(sections) >= directive.max_files
165
-        ):
160
+        if directive.max_files is not None and len(sections) >= directive.max_files:
166161
             _LOG.info(
167162
                 "directive: hit max_files=%d for %s; truncating deterministically",
168163
                 directive.max_files,
@@ -190,10 +185,7 @@ def _expand_one(
190185
             _LOG.warning("directive: stat failed for %s: %s; skipping", file_path, exc)
191186
             continue
192187
 
193
-        if (
194
-            directive.max_bytes_per_file is not None
195
-            and size > directive.max_bytes_per_file
196
-        ):
188
+        if directive.max_bytes_per_file is not None and size > directive.max_bytes_per_file:
197189
             _LOG.info(
198190
                 "directive: %s (%d bytes) exceeds max_bytes_per_file=%d; skipping",
199191
                 file_path,
@@ -210,9 +202,7 @@ def _expand_one(
210202
             continue
211203
 
212204
         if is_probably_binary(raw):
213
-            _LOG.info(
214
-                "directive: %s looks binary (NUL in first KiB); skipping", file_path
215
-            )
205
+            _LOG.info("directive: %s looks binary (NUL in first KiB); skipping", file_path)
216206
             skipped_binary += 1
217207
             continue
218208
 
@@ -225,9 +215,7 @@ def _expand_one(
225215
 
226216
         relpath = file_path.relative_to(header_root).as_posix()
227217
         content = f"# source: {relpath}\n\n{text}"
228
-        sections.append(
229
-            Section(type=SectionType.PROSE, content=content, tags=effective.tags)
230
-        )
218
+        sections.append(Section(type=SectionType.PROSE, content=content, tags=effective.tags))
231219
         total_bytes += len(raw)
232220
 
233221
     return sections, SourceProvenance(
src/dlm/directives/merge.pymodified
@@ -52,11 +52,7 @@ def ancestors_of(
5252
     """Return DiscoveredConfigs whose anchor is an ancestor of file_path,
5353
     sorted shallowest → deepest. Includes the direct-parent anchor."""
5454
     abs_file = file_path.resolve()
55
-    result = [
56
-        d
57
-        for d in discovered
58
-        if _is_ancestor(d.anchor.resolve(), abs_file)
59
-    ]
55
+    result = [d for d in discovered if _is_ancestor(d.anchor.resolve(), abs_file)]
6056
     result.sort(key=lambda d: len(d.anchor.as_posix()))
6157
     return tuple(result)
6258
 
src/dlm/directives/safety.pymodified
@@ -158,9 +158,7 @@ def enumerate_matching_files(
158158
             yield candidate
159159
 
160160
 
161
-def _matches_filters(
162
-    rel_path: str, include: Iterable[str], exclude: Iterable[str]
163
-) -> bool:
161
+def _matches_filters(rel_path: str, include: Iterable[str], exclude: Iterable[str]) -> bool:
164162
     """Match rel_path against include (any) and exclude (none)."""
165163
     if any(_compile_glob(pat).fullmatch(rel_path) for pat in exclude):
166164
         return False
src/dlm/doc/parser.pymodified
@@ -210,9 +210,7 @@ def _tokenize_body(body: str, *, body_start_line: int, path: Path | None) -> lis
210210
             match = _FENCE_RE.match(line)
211211
             if match:
212212
                 fence_name = match.group(1)
213
-                fence_type, fence_adapter = _resolve_fence_type(
214
-                    fence_name, source_line, path
215
-                )
213
+                fence_type, fence_adapter = _resolve_fence_type(fence_name, source_line, path)
216214
                 flush()
217215
                 current_type = fence_type
218216
                 current_adapter = fence_adapter
@@ -233,9 +231,7 @@ def _tokenize_body(body: str, *, body_start_line: int, path: Path | None) -> lis
233231
     return sections
234232
 
235233
 
236
-def _resolve_fence_type(
237
-    name: str, line: int, path: Path | None
238
-) -> tuple[SectionType, str | None]:
234
+def _resolve_fence_type(name: str, line: int, path: Path | None) -> tuple[SectionType, str | None]:
239235
     """Map a fence name to `(SectionType, adapter_name|None)` or raise.
240236
 
241237
     Multi-adapter fences carry a `#<adapter>` suffix; the adapter part is
@@ -267,8 +263,7 @@ def _resolve_fence_type(
267263
         section_type = SectionType(base)
268264
     except ValueError as exc:
269265
         raise FenceError(
270
-            f"unknown section fence '::{name}::'; valid types are "
271
-            f"{[t.value for t in SectionType]}",
266
+            f"unknown section fence '::{name}::'; valid types are {[t.value for t in SectionType]}",
272267
             path=path,
273268
             line=line,
274269
             col=1,
src/dlm/doc/schema.pymodified
@@ -69,9 +69,7 @@ class PreferenceConfig(BaseModel):
6969
 
7070
     enabled: bool = False
7171
     method: Literal["dpo", "orpo"] = "dpo"
72
-    hyperparams: PreferenceHyperparams = Field(
73
-        default_factory=lambda: PreferenceHyperparams()
74
-    )
72
+    hyperparams: PreferenceHyperparams = Field(default_factory=lambda: PreferenceHyperparams())
7573
     # DPO-only fields — ignored for ORPO but kept on the config so a
7674
     # user switching methods doesn't have to delete them.
7775
     loss_type: Literal["sigmoid", "hinge", "ipo"] = "sigmoid"
@@ -247,11 +245,7 @@ class TrainingConfig(BaseModel):
247245
             "target_modules": "auto",
248246
             "learning_rate": 2e-4,
249247
         }
250
-        drift = [
251
-            key
252
-            for key, default in flat_defaults.items()
253
-            if getattr(self, key) != default
254
-        ]
248
+        drift = [key for key, default in flat_defaults.items() if getattr(self, key) != default]
255249
         if drift:
256250
             raise ValueError(
257251
                 "training.adapters is declared; flat per-adapter fields "
src/dlm/doc/serializer.pymodified
@@ -104,8 +104,10 @@ def _emit_nested_mapping(model: BaseModel, *, indent: int) -> list[str]:
104104
             lines.append(f"{pad}{field_name}:")
105105
             lines.extend(nested)
106106
             continue
107
-        if isinstance(value, dict) and value and all(
108
-            isinstance(v, BaseModel) for v in value.values()
107
+        if (
108
+            isinstance(value, dict)
109
+            and value
110
+            and all(isinstance(v, BaseModel) for v in value.values())
109111
         ):
110112
             # `dict[str, BaseModel]` (e.g. training.adapters) — emit
111113
             # each entry as a nested mapping. The key is the dict
src/dlm/export/runner.pymodified
@@ -186,9 +186,7 @@ def run_export(
186186
         if not adapter_path.exists():
187187
             from dlm.export.errors import ExportError
188188
 
189
-            raise ExportError(
190
-                f"adapter_path_override {adapter_path} does not exist"
191
-            )
189
+            raise ExportError(f"adapter_path_override {adapter_path} does not exist")
192190
     elif adapter_name is None:
193191
         resolved = store.resolve_current_adapter()
194192
         pointer = store.adapter_current_pointer
@@ -196,8 +194,7 @@ def run_export(
196194
             from dlm.export.errors import ExportError
197195
 
198196
             raise ExportError(
199
-                f"no current adapter under {pointer}; "
200
-                "run `dlm train` before exporting."
197
+                f"no current adapter under {pointer}; run `dlm train` before exporting."
201198
             )
202199
         adapter_path = resolved
203200
     else:
src/dlm/export/weighted_merge.pymodified
@@ -77,47 +77,37 @@ def parse_mix_spec(spec_str: str) -> list[MixEntry]:
7777
     for piece in raw.split(","):
7878
         token = piece.strip()
7979
         if not token:
80
-            raise InvalidMixSpecError(
81
-                f"--adapter-mix: empty entry in spec {spec_str!r}"
82
-            )
80
+            raise InvalidMixSpecError(f"--adapter-mix: empty entry in spec {spec_str!r}")
8381
         if ":" not in token:
8482
             raise InvalidMixSpecError(
85
-                f"--adapter-mix: entry {token!r} is missing a weight "
86
-                "(shape: `name:weight`)"
83
+                f"--adapter-mix: entry {token!r} is missing a weight (shape: `name:weight`)"
8784
             )
8885
         name, _, weight_str = token.rpartition(":")
8986
         name = name.strip()
9087
         weight_str = weight_str.strip()
9188
         if not _NAME_RE.fullmatch(name):
9289
             raise InvalidMixSpecError(
93
-                f"--adapter-mix: adapter name {name!r} is not valid "
94
-                f"(must match {_NAME_RE.pattern})"
90
+                f"--adapter-mix: adapter name {name!r} is not valid (must match {_NAME_RE.pattern})"
9591
             )
9692
         if name in seen:
97
-            raise InvalidMixSpecError(
98
-                f"--adapter-mix: adapter {name!r} appears twice"
99
-            )
93
+            raise InvalidMixSpecError(f"--adapter-mix: adapter {name!r} appears twice")
10094
         seen.add(name)
10195
         try:
10296
             weight = float(weight_str)
10397
         except ValueError as exc:
10498
             raise InvalidMixSpecError(
105
-                f"--adapter-mix: weight {weight_str!r} for adapter "
106
-                f"{name!r} is not a number"
99
+                f"--adapter-mix: weight {weight_str!r} for adapter {name!r} is not a number"
107100
             ) from exc
108101
         if weight < 0:
109102
             raise InvalidMixSpecError(
110
-                f"--adapter-mix: weight {weight} for adapter {name!r} "
111
-                "is negative (must be >= 0)"
103
+                f"--adapter-mix: weight {weight} for adapter {name!r} is negative (must be >= 0)"
112104
             )
113105
         entries.append(MixEntry(name=name, weight=weight))
114106
 
115107
     return entries
116108
 
117109
 
118
-def validate_mix_against_declared(
119
-    entries: list[MixEntry], declared: set[str]
120
-) -> None:
110
+def validate_mix_against_declared(entries: list[MixEntry], declared: set[str]) -> None:
121111
     """Refuse mix entries that reference adapters not in `training.adapters`.
122112
 
123113
     Single source of error messaging so the CLI and the runner both
@@ -170,9 +160,7 @@ def build_weighted_merged( # pragma: no cover - heavy path
170160
 
171161
     first = entries[0]
172162
     first_path = _resolve_or_raise(store, first.name)
173
-    model = PeftModel.from_pretrained(
174
-        base_model, str(first_path), adapter_name=first.name
175
-    )
163
+    model = PeftModel.from_pretrained(base_model, str(first_path), adapter_name=first.name)
176164
     for extra in entries[1:]:
177165
         path = _resolve_or_raise(store, extra.name)
178166
         model.load_adapter(str(path), adapter_name=extra.name)
@@ -208,9 +196,7 @@ def resolve_first_source_path(store: StorePath, entries: list[MixEntry]) -> Path
208196
     single-valued), so any source is interchangeable — we pick the first.
209197
     """
210198
     if not entries:
211
-        raise InvalidMixSpecError(
212
-            "resolve_first_source_path: empty mix"
213
-        )
199
+        raise InvalidMixSpecError("resolve_first_source_path: empty mix")
214200
     return _resolve_or_raise(store, entries[0].name)
215201
 
216202
 
@@ -257,9 +243,7 @@ def save_merged_to_tmp( # pragma: no cover - heavy path
257243
     import shutil
258244
 
259245
     tmp_dir.mkdir(parents=True, exist_ok=True)
260
-    merged_model.save_pretrained(
261
-        str(tmp_dir), selected_adapters=[_MERGED_ADAPTER_NAME]
262
-    )
246
+    merged_model.save_pretrained(str(tmp_dir), selected_adapters=[_MERGED_ADAPTER_NAME])
263247
 
264248
     # PEFT nests under the adapter name; that's where run_export
265249
     # expects to find adapter_config.json + safetensors.
src/dlm/hardware/capabilities.pymodified
@@ -156,9 +156,7 @@ def _get_unified_memory_gb(backend: Backend) -> float | None:
156156
     return psutil.virtual_memory().total / (1024**3)
157157
 
158158
 
159
-def _supports_bf16(
160
-    backend: Backend, sm: tuple[int, int] | None, rocm_arch: str | None
161
-) -> bool:
159
+def _supports_bf16(backend: Backend, sm: tuple[int, int] | None, rocm_arch: str | None) -> bool:
162160
     if backend == Backend.CUDA:
163161
         return sm is not None and sm >= (8, 0)
164162
     if backend == Backend.ROCM:
src/dlm/hardware/plan.pymodified
@@ -104,9 +104,7 @@ def resolve(
104104
         raise ValueError(f"world_size must be >= 1, got {world_size}")
105105
     if world_size > 1:
106106
         check_multi_gpu_refusals(caps, world_size)
107
-    check_refusals(
108
-        training, caps, base_params, force=force, num_adapters=num_adapters
109
-    )
107
+    check_refusals(training, caps, base_params, force=force, num_adapters=num_adapters)
110108
 
111109
     use_qlora = _should_qlora(training, caps)
112110
     precision = _pick_precision(caps, override=training.precision)
src/dlm/hardware/refusals.pymodified
@@ -83,15 +83,11 @@ def check_refusals(
8383
         per_adapter_gb = max(0.1, base_params * avg_lora_r / (1e9 * 64))
8484
         activations_gb = base_params * 2.0 / 1e9 * 0.25
8585
         qlora_adapter_count = _qlora_adapter_count(training, num_adapters)
86
-        est_peak = (
87
-            base_gb + per_adapter_gb * qlora_adapter_count + activations_gb
88
-        )
86
+        est_peak = base_gb + per_adapter_gb * qlora_adapter_count + activations_gb
8987
         budget = caps.vram_gb * 0.85
9088
         if est_peak > budget:
9189
             offenders = _qlora_adapter_names(training)
92
-            offender_note = (
93
-                f" (offending adapters: {sorted(offenders)})" if offenders else ""
94
-            )
90
+            offender_note = f" (offending adapters: {sorted(offenders)})" if offenders else ""
9591
             raise ResolutionError(
9692
                 "Multi-adapter QLoRA would exceed VRAM "
9793
                 f"(~{est_peak:.1f} GB estimated vs {budget:.1f} GB budget "
@@ -130,8 +126,7 @@ def check_multi_gpu_refusals(caps: Capabilities, world_size: int) -> None:
130126
         )
131127
     if caps.backend == Backend.CPU:
132128
         raise ResolutionError(
133
-            "Multi-GPU training on CPU is not supported. "
134
-            "Drop `--gpus` or run single-process.",
129
+            "Multi-GPU training on CPU is not supported. Drop `--gpus` or run single-process.",
135130
         )
136131
     if caps.backend == Backend.ROCM:
137132
         raise ResolutionError(
@@ -181,9 +176,7 @@ def _avg_lora_r(training: TrainingConfig) -> float:
181176
     """Average LoRA rank across declared adapters (fallback: flat lora_r)."""
182177
     if training.adapters is None or not training.adapters:
183178
         return float(training.lora_r)
184
-    return sum(a.lora_r for a in training.adapters.values()) / len(
185
-        training.adapters
186
-    )
179
+    return sum(a.lora_r for a in training.adapters.values()) / len(training.adapters)
187180
 
188181
 
189182
 def _qlora_adapter_count(training: TrainingConfig, fallback: int) -> int:
src/dlm/inference/backends/mlx_backend.pymodified
@@ -54,8 +54,7 @@ def stage_mlx_adapter_dir(peft_adapter_dir: Path, dst_dir: Path) -> Path:
5454
     src_config = peft_adapter_dir / _ADAPTER_CONFIG_FILENAME
5555
     if not src_config.exists():
5656
         raise MlxConversionError(
57
-            f"{peft_adapter_dir} is not a PEFT adapter dir "
58
-            f"({_ADAPTER_CONFIG_FILENAME} is missing)"
57
+            f"{peft_adapter_dir} is not a PEFT adapter dir ({_ADAPTER_CONFIG_FILENAME} is missing)"
5958
         )
6059
     if not (peft_adapter_dir / "adapter_model.safetensors").exists():
6160
         raise MlxConversionError(
src/dlm/inference/loader.pymodified
@@ -105,9 +105,7 @@ def _torch_dtype_for(precision: str) -> Any:
105105
     return lookup.get(precision, torch.float16)
106106
 
107107
 
108
-def resolve_adapter_path(
109
-    store: StorePath, *, adapter_name: str | None
110
-) -> Path:
108
+def resolve_adapter_path(store: StorePath, *, adapter_name: str | None) -> Path:
111109
     """Return the on-disk adapter version dir for inference.
112110
 
113111
     Single entry point for both the flat (unnamed) and named-adapter
src/dlm/metrics/queries.pymodified
@@ -132,9 +132,7 @@ def evals_for_run(store_root: Path, run_id: int, *, since_step: int = 0) -> list
132132
     return [EvalRow(*row) for row in rows]
133133
 
134134
 
135
-def tokenization_for_run(
136
-    store_root: Path, run_id: int
137
-) -> TokenizationRow | None:
135
+def tokenization_for_run(store_root: Path, run_id: int) -> TokenizationRow | None:
138136
     """The tokenization row for `run_id`, or None when absent.
139137
 
140138
     Returns None when the table is empty for this run (i.e. the run
src/dlm/metrics/sinks/wandb.pymodified
@@ -45,8 +45,7 @@ class WandbSink:
4545
             import wandb  # type: ignore[import-not-found]
4646
         except ImportError as exc:  # pragma: no cover - depends on install
4747
             raise RuntimeError(
48
-                "W&B sink requires `wandb`; "
49
-                "run `uv sync --extra observability` to install it."
48
+                "W&B sink requires `wandb`; run `uv sync --extra observability` to install it."
5049
             ) from exc
5150
 
5251
         wandb_dir = store_root / "wandb"
src/dlm/share/hf_sink.pymodified
@@ -75,9 +75,7 @@ def push_hf(
7575
             exist_ok=True,
7676
         )
7777
     except HfHubHTTPError as exc:
78
-        raise SinkError(
79
-            f"hf push: failed to ensure repo {repo_id!r}: {exc}"
80
-        ) from exc
78
+        raise SinkError(f"hf push: failed to ensure repo {repo_id!r}: {exc}") from exc
8179
 
8280
     # Upload the pack.
8381
     if progress is not None:
src/dlm/share/peer.pymodified
@@ -74,10 +74,7 @@ class PeerSession:
7474
         signature = self._sign(self.dlm_id, expiry_iso, nonce)
7575
         # Wire format: nonce || len(expiry_iso) || expiry_iso || sig
7676
         payload = (
77
-            nonce
78
-            + len(expiry_iso).to_bytes(2, "big")
79
-            + expiry_iso.encode("ascii")
80
-            + signature
77
+            nonce + len(expiry_iso).to_bytes(2, "big") + expiry_iso.encode("ascii") + signature
8178
         )
8279
         return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=")
8380
 
@@ -162,9 +159,7 @@ class RateLimiter:
162159
             while self.requests and self.requests[0] < window_start:
163160
                 self.requests.popleft()
164161
             if len(self.requests) >= self.rate_limit_per_min:
165
-                raise RateLimitError(
166
-                    f"rate limit: {self.rate_limit_per_min} req/min exceeded"
167
-                )
162
+                raise RateLimitError(f"rate limit: {self.rate_limit_per_min} req/min exceeded")
168163
             if self.active >= self.max_concurrency:
169164
                 raise RateLimitError(
170165
                     f"rate limit: max concurrent connections ({self.max_concurrency}) exceeded"
src/dlm/share/pull.pymodified
@@ -64,9 +64,7 @@ def pull(
6464
         pack_path = staging / "incoming.dlm.pack"
6565
         sig_path = pack_path.with_suffix(pack_path.suffix + ".minisig")
6666
 
67
-        bytes_received = _dispatch_pull(
68
-            spec, pack_path, sig_path, progress=progress
69
-        )
67
+        bytes_received = _dispatch_pull(spec, pack_path, sig_path, progress=progress)
7068
 
7169
         # Verify signature BEFORE unpack so users learn the trust
7270
         # status even if unpack then fails for an unrelated reason.
@@ -181,9 +179,7 @@ def _try_peer_sidecar(target: str, sig_path: Path) -> None:
181179
 
182180
 def _log_verification(source: str, result: VerifyResult) -> None:
183181
     if result.status == VerifyStatus.VERIFIED:
184
-        _LOG.info(
185
-            "pull: verified signature from %s using %s", source, result.key_path
186
-        )
182
+        _LOG.info("pull: verified signature from %s using %s", source, result.key_path)
187183
     elif result.status == VerifyStatus.UNVERIFIED:
188184
         _LOG.warning(
189185
             "pull: signature present but could not verify (%s). "
src/dlm/share/push.pymodified
@@ -140,9 +140,7 @@ def _sign_pack(pack_path: Path) -> None:
140140
     _LOG.info("push: signed %s → %s", pack_path, sig_path)
141141
 
142142
 
143
-def _dispatch_push(
144
-    pack_path: Path, spec: SinkSpec, *, progress: ProgressCallback
145
-) -> PushResult:
143
+def _dispatch_push(pack_path: Path, spec: SinkSpec, *, progress: ProgressCallback) -> PushResult:
146144
     if spec.kind == SinkKind.HF:
147145
         from dlm.share.hf_sink import push_hf
148146
 
@@ -198,7 +196,11 @@ def _collect_readme_fields(pack_path: Path) -> dict[str, str]:
198196
         import zstandard as zstd
199197
 
200198
         fields: dict[str, str] = {}
201
-        with pack_path.open("rb") as f, zstd.ZstdDecompressor().stream_reader(f) as r, tarfile.open(fileobj=r, mode="r|") as tar:
199
+        with (
200
+            pack_path.open("rb") as f,
201
+            zstd.ZstdDecompressor().stream_reader(f) as r,
202
+            tarfile.open(fileobj=r, mode="r|") as tar,
203
+        ):
202204
             for member in tar:
203205
                 if member.name.endswith("header.json"):
204206
                     import json
@@ -208,9 +210,7 @@ def _collect_readme_fields(pack_path: Path) -> dict[str, str]:
208210
                         header = json.loads(data.read().decode("utf-8"))
209211
                         fields["dlm_id"] = str(header.get("dlm_id", ""))
210212
                         fields["base_model"] = str(header.get("base_model", ""))
211
-                        fields["adapter_version"] = str(
212
-                            header.get("adapter_version", "")
213
-                        )
213
+                        fields["adapter_version"] = str(header.get("adapter_version", ""))
214214
                     break
215215
         return fields
216216
     except (OSError, ValueError, ImportError) as exc:
src/dlm/share/signing.pymodified
@@ -119,8 +119,7 @@ def sign_file(
119119
     sig_path = target.with_suffix(target.suffix + ".minisig")
120120
     if not sig_path.is_file():
121121
         raise ShareError(
122
-            f"minisign succeeded but {sig_path} is missing; "
123
-            "signing integration is out of sync"
122
+            f"minisign succeeded but {sig_path} is missing; signing integration is out of sync"
124123
         )
125124
     return sig_path
126125
 
@@ -142,8 +141,7 @@ def verify_signature(
142141
 
143142
     if not minisign_available():
144143
         _LOG.warning(
145
-            "verify: signature present (%s) but `minisign` is not installed; "
146
-            "cannot verify",
144
+            "verify: signature present (%s) but `minisign` is not installed; cannot verify",
147145
             signature,
148146
         )
149147
         return VerifyResult(
@@ -154,8 +152,7 @@ def verify_signature(
154152
     keys_dir = trusted_keys_dir or _DEFAULT_TRUSTED_KEYS_DIR
155153
     if not keys_dir.is_dir():
156154
         _LOG.warning(
157
-            "verify: signature present but no trusted keys at %s; "
158
-            "pack is unverifiable",
155
+            "verify: signature present but no trusted keys at %s; pack is unverifiable",
159156
             keys_dir,
160157
         )
161158
         return VerifyResult(
src/dlm/share/sinks.pymodified
@@ -58,9 +58,7 @@ def parse_source(source: str) -> SinkSpec:
5858
     if source.startswith("hf:"):
5959
         rest = source[len("hf:") :]
6060
         if not rest or "/" not in rest:
61
-            raise UnknownSinkError(
62
-                f"hf: source must be 'hf:<org>/<repo>', got {source!r}"
63
-            )
61
+            raise UnknownSinkError(f"hf: source must be 'hf:<org>/<repo>', got {source!r}")
6462
         return SinkSpec(kind=SinkKind.HF, target=rest)
6563
 
6664
     if source.startswith(("http://", "https://")):
@@ -69,9 +67,7 @@ def parse_source(source: str) -> SinkSpec:
6967
     if source.startswith("peer://"):
7068
         rest = source[len("peer://") :]
7169
         if not rest:
72
-            raise UnknownSinkError(
73
-                f"peer:// source needs host:port/path, got {source!r}"
74
-            )
70
+            raise UnknownSinkError(f"peer:// source needs host:port/path, got {source!r}")
7571
         return SinkSpec(kind=SinkKind.PEER, target=rest)
7672
 
7773
     # Fall through to local path. Accept absolute, relative, and `~`.
@@ -80,6 +76,4 @@ def parse_source(source: str) -> SinkSpec:
8076
     if path_looking:
8177
         return SinkSpec(kind=SinkKind.LOCAL, target=source)
8278
 
83
-    raise UnknownSinkError(
84
-        f"unrecognized source {source!r}: expected hf:/https:/peer:/ or a path"
85
-    )
79
+    raise UnknownSinkError(f"unrecognized source {source!r}: expected hf:/https:/peer:/ or a path")
src/dlm/share/url_sink.pymodified
@@ -55,9 +55,12 @@ def push_url(pack_path: Path, url: str, *, progress: ProgressCallback = None) ->
5555
         headers=_build_headers(total, content_type="application/octet-stream"),
5656
     )
5757
     try:
58
-        with pack_path.open("rb") as src, urllib.request.urlopen(  # noqa: S310
59
-            req, data=_iter_read(src, total, progress), timeout=60
60
-        ) as resp:
58
+        with (
59
+            pack_path.open("rb") as src,
60
+            urllib.request.urlopen(  # noqa: S310
61
+                req, data=_iter_read(src, total, progress), timeout=60
62
+            ) as resp,
63
+        ):
6164
             status = resp.status
6265
             if status < 200 or status >= 300:
6366
                 raise SinkError(f"url push: HTTP {status} from {url}")
@@ -105,9 +108,7 @@ def pull_url(url: str, out_path: Path, *, progress: ProgressCallback = None) ->
105108
         raise SinkError(f"url pull: I/O error writing {out_path}: {exc}") from exc
106109
 
107110
 
108
-def _build_headers(
109
-    content_length: int | None, *, content_type: str | None
110
-) -> dict[str, str]:
111
+def _build_headers(content_length: int | None, *, content_type: str | None) -> dict[str, str]:
111112
     headers = {"User-Agent": _USER_AGENT}
112113
     if content_type is not None:
113114
         headers["Content-Type"] = content_type
@@ -119,9 +120,7 @@ def _build_headers(
119120
     return headers
120121
 
121122
 
122
-def _iter_read(
123
-    src: IO[bytes], total: int, progress: ProgressCallback
124
-) -> bytes:
123
+def _iter_read(src: IO[bytes], total: int, progress: ProgressCallback) -> bytes:
125124
     """Streaming read adapter for urllib's `data=` parameter.
126125
 
127126
     urllib accepts a bytes-or-bytes-iterable. We return the full bytes
@@ -138,9 +137,7 @@ def _iter_read(
138137
     return data
139138
 
140139
 
141
-def _stream_to_file(
142
-    resp: IO[bytes], out_path: Path, total: int, progress: ProgressCallback
143
-) -> int:
140
+def _stream_to_file(resp: IO[bytes], out_path: Path, total: int, progress: ProgressCallback) -> int:
144141
     written = 0
145142
     with out_path.open("wb") as dst:
146143
         while True:
src/dlm/store/inspect.pymodified
@@ -202,7 +202,7 @@ def _max_version(versions_dir: Path) -> int:
202202
         if not name.startswith(_VERSION_DIR_PREFIX):
203203
             continue
204204
         try:
205
-            n = int(name[len(_VERSION_DIR_PREFIX):])
205
+            n = int(name[len(_VERSION_DIR_PREFIX) :])
206206
         except ValueError:
207207
             continue
208208
         highest = max(highest, n)
src/dlm/store/paths.pymodified
@@ -52,8 +52,7 @@ _ADAPTER_NAME_RE: Final[re.Pattern[str]] = re.compile(r"^[a-z][a-z0-9_]{0,31}$")
5252
 def _validate_adapter_name(name: str) -> None:
5353
     if not _ADAPTER_NAME_RE.fullmatch(name):
5454
         raise ValueError(
55
-            f"adapter name {name!r} is not valid "
56
-            f"(must match {_ADAPTER_NAME_RE.pattern})"
55
+            f"adapter name {name!r} is not valid (must match {_ADAPTER_NAME_RE.pattern})"
5756
         )
5857
 
5958
 
@@ -235,9 +234,7 @@ class StorePath:
235234
             ) from exc
236235
         from dlm.io.atomic import write_text as _atomic_write_text
237236
 
238
-        _atomic_write_text(
239
-            self.adapter_current_pointer_for(name), f"{relative}\n"
240
-        )
237
+        _atomic_write_text(self.adapter_current_pointer_for(name), f"{relative}\n")
241238
 
242239
     def export_quant_dir(self, quant: str) -> Path:
243240
         """Return `exports/<quant>/` (does NOT create it)."""
src/dlm/templates/init.pymodified
@@ -95,8 +95,7 @@ def apply_template(
9595
         ) from exc
9696
     if is_gated(spec) and not accept_license:
9797
         raise TemplateApplyError(
98
-            f"template {name!r} uses gated base {spec.key!r}; "
99
-            "pass accept_license=True"
98
+            f"template {name!r} uses gated base {spec.key!r}; pass accept_license=True"
10099
         )
101100
 
102101
     parsed = parse_text(template.dlm_text)
src/dlm/train/checkpoint_commit.pymodified
@@ -43,9 +43,7 @@ _LOG = logging.getLogger(__name__)
4343
 _VERSION_PREFIX = "v"
4444
 
4545
 
46
-def allocate_next_version(
47
-    store: StorePath, *, adapter_name: str | None = None
48
-) -> Path:
46
+def allocate_next_version(store: StorePath, *, adapter_name: str | None = None) -> Path:
4947
     """Return the next empty `adapter/[<name>/]versions/vNNNN/` path.
5048
 
5149
     Creates the directory (and any missing parents). When `adapter_name`
@@ -99,8 +97,7 @@ def commit_version(
9997
             )
10098
         except OSError:
10199
             _LOG.exception(
102
-                "non-finite adapter weights + rejected-dir rename failed; "
103
-                "leaving %s in place",
100
+                "non-finite adapter weights + rejected-dir rename failed; leaving %s in place",
104101
                 pending,
105102
             )
106103
         raise
@@ -156,9 +153,7 @@ def fsync_dir(path: Path) -> None:
156153
         os.close(fd)
157154
 
158155
 
159
-def list_pending_versions(
160
-    store: StorePath, *, adapter_name: str | None = None
161
-) -> list[Path]:
156
+def list_pending_versions(store: StorePath, *, adapter_name: str | None = None) -> list[Path]:
162157
     """Return version dirs that exist on disk but aren't the current pointer.
163158
 
164159
     Used by the trainer's startup routine to detect crash-before-flip
@@ -182,13 +177,9 @@ def list_pending_versions(
182177
     return [version_for(n) for n in sorted(existing) if n != current_n]
183178
 
184179
 
185
-def _existing_versions(
186
-    store: StorePath, *, adapter_name: str | None = None
187
-) -> list[int]:
180
+def _existing_versions(store: StorePath, *, adapter_name: str | None = None) -> list[int]:
188181
     base = (
189
-        store.adapter_versions
190
-        if adapter_name is None
191
-        else store.adapter_versions_for(adapter_name)
182
+        store.adapter_versions if adapter_name is None else store.adapter_versions_for(adapter_name)
192183
     )
193184
     if not base.is_dir():
194185
         return []
src/dlm/train/cpt/embed_warmup.pymodified
@@ -127,7 +127,11 @@ class EmbedWarmupCallback: # pragma: no cover - exercised by slow integration
127127
         self._active: bool = False
128128
 
129129
     def on_train_begin(
130
-        self, args: Any, state: Any, control: Any, **kwargs: Any  # noqa: ARG002
130
+        self,
131
+        args: Any,
132
+        state: Any,
133
+        control: Any,
134
+        **kwargs: Any,  # noqa: ARG002
131135
     ) -> None:
132136
         if self.n_steps <= 0:
133137
             return
@@ -145,12 +149,20 @@ class EmbedWarmupCallback: # pragma: no cover - exercised by slow integration
145149
         self._active = False
146150
 
147151
     def on_step_end(
148
-        self, args: Any, state: Any, control: Any, **kwargs: Any  # noqa: ARG002
152
+        self,
153
+        args: Any,
154
+        state: Any,
155
+        control: Any,
156
+        **kwargs: Any,  # noqa: ARG002
149157
     ) -> None:
150158
         if self._active and state.global_step >= self.n_steps:
151159
             self._restore()
152160
 
153161
     def on_train_end(
154
-        self, args: Any, state: Any, control: Any, **kwargs: Any  # noqa: ARG002
162
+        self,
163
+        args: Any,
164
+        state: Any,
165
+        control: Any,
166
+        **kwargs: Any,  # noqa: ARG002
155167
     ) -> None:
156168
         self._restore()
src/dlm/train/cpt/schedule.pymodified
@@ -50,13 +50,9 @@ def cosine_with_floor_lr(
5050
     if warmup_steps < 0:
5151
         raise ValueError(f"warmup_steps must be non-negative, got {warmup_steps}")
5252
     if warmup_steps >= total_steps:
53
-        raise ValueError(
54
-            f"warmup_steps ({warmup_steps}) must be < total_steps ({total_steps})"
55
-        )
53
+        raise ValueError(f"warmup_steps ({warmup_steps}) must be < total_steps ({total_steps})")
5654
     if not 0.0 <= floor_ratio <= 1.0:
57
-        raise ValueError(
58
-            f"floor_ratio must be in [0.0, 1.0], got {floor_ratio}"
59
-        )
55
+        raise ValueError(f"floor_ratio must be in [0.0, 1.0], got {floor_ratio}")
6056
     if step < 0:
6157
         raise ValueError(f"step must be non-negative, got {step}")
6258
 
src/dlm/train/cpt/vocab_gap.pymodified
@@ -85,8 +85,7 @@ def compute_vocab_gap(
8585
     """
8686
     if len(token_ids) != len(decoded_tokens):
8787
         raise ValueError(
88
-            f"token_ids/decoded_tokens length mismatch: "
89
-            f"{len(token_ids)} vs {len(decoded_tokens)}"
88
+            f"token_ids/decoded_tokens length mismatch: {len(token_ids)} vs {len(decoded_tokens)}"
9089
         )
9190
     if top_n < 0:
9291
         raise ValueError(f"top_n must be non-negative, got {top_n}")
@@ -95,11 +94,7 @@ def compute_vocab_gap(
9594
     total_words = _count_words(text)
9695
     tpw = total_tokens / total_words if total_words else 0.0
9796
 
98
-    unk_hits = (
99
-        sum(1 for tid in token_ids if tid == unk_token_id)
100
-        if unk_token_id is not None
101
-        else 0
102
-    )
97
+    unk_hits = sum(1 for tid in token_ids if tid == unk_token_id) if unk_token_id is not None else 0
10398
 
10499
     counts: Counter[str] = Counter(decoded_tokens)
105100
     top_tokens = counts.most_common(top_n)
@@ -113,7 +108,9 @@ def compute_vocab_gap(
113108
     )
114109
 
115110
 
116
-def report(text: str, tokenizer: Any, *, top_n: int = 10) -> VocabGapReport:  # pragma: no cover - network/heavy
111
+def report(
112
+    text: str, tokenizer: Any, *, top_n: int = 10
113
+) -> VocabGapReport:  # pragma: no cover - network/heavy
117114
     """Run the base tokenizer over `text` and compute the fit report.
118115
 
119116
     Heavy-import shell around `compute_vocab_gap` — covered by the slow
@@ -147,12 +144,8 @@ def render_report(r: VocabGapReport) -> str:
147144
         f"  <unk> hits      : {r.unk_hits}",
148145
     ]
149146
     if r.has_unk:
150
-        lines.append(
151
-            "  WARNING: non-zero <unk> count — tokenizer has rare-character"
152
-        )
153
-        lines.append(
154
-            "  holes for this domain. Consider a different base model."
155
-        )
147
+        lines.append("  WARNING: non-zero <unk> count — tokenizer has rare-character")
148
+        lines.append("  holes for this domain. Consider a different base model.")
156149
     if r.top_tokens:
157150
         lines.append("  top tokens:")
158151
         width = max(len(t) for t, _ in r.top_tokens)
src/dlm/train/distributed/rank_env.pymodified
@@ -31,9 +31,7 @@ def detect_world_size() -> int:
3131
     try:
3232
         value = int(raw)
3333
     except ValueError as exc:
34
-        raise ValueError(
35
-            f"WORLD_SIZE env var is not an integer: {raw!r}"
36
-        ) from exc
34
+        raise ValueError(f"WORLD_SIZE env var is not an integer: {raw!r}") from exc
3735
     if value < 1:
3836
         return 1
3937
     return value
@@ -53,9 +51,7 @@ def detect_rank() -> int:
5351
         try:
5452
             value = int(raw)
5553
         except ValueError as exc:
56
-            raise ValueError(
57
-                f"{key} env var is not an integer: {raw!r}"
58
-            ) from exc
54
+            raise ValueError(f"{key} env var is not an integer: {raw!r}") from exc
5955
         if value < 0:
6056
             return 0
6157
         return value
src/dlm/train/multi_adapter/router.pymodified
@@ -107,7 +107,6 @@ def sections_for(parsed: ParsedDlm, adapter_name: str) -> list[Section]:
107107
     plan = build_plan(parsed)
108108
     if adapter_name not in plan.by_adapter:
109109
         raise UnknownAdapterError(
110
-            f"adapter {adapter_name!r} not declared "
111
-            f"(declared: {sorted(plan.by_adapter)})"
110
+            f"adapter {adapter_name!r} not declared (declared: {sorted(plan.by_adapter)})"
112111
         )
113112
     return plan.by_adapter[adapter_name]
src/dlm/train/preference/dpo_phase.pymodified
@@ -351,9 +351,7 @@ def _build_real_dpo_trainer( # pragma: no cover
351351
     # Policy: base + the SFT-trained adapter as trainable.
352352
     base_model = load_base_model(spec, plan)
353353
     adapter_dir = store.adapter_version(reference_adapter_version)
354
-    policy_model = PeftModel.from_pretrained(
355
-        base_model, str(adapter_dir), is_trainable=True
356
-    )
354
+    policy_model = PeftModel.from_pretrained(base_model, str(adapter_dir), is_trainable=True)
357355
 
358356
     # Reference: frozen per preference.reference mode. We reload a
359357
     # clean base for the reference rather than sharing `base_model` so
@@ -376,9 +374,7 @@ def _build_real_dpo_trainer( # pragma: no cover
376374
     doc_ds = build_dpo_dataset(list(parsed.sections))
377375
     rng = _random.Random(seed + reference_adapter_version)
378376
     now = datetime.now(UTC).replace(tzinfo=None, microsecond=0)
379
-    replay_rows = replay.sample_preference_rows(
380
-        k=max(8, 2 * len(doc_ds)), now=now, rng=rng
381
-    )
377
+    replay_rows = replay.sample_preference_rows(k=max(8, 2 * len(doc_ds)), now=now, rng=rng)
382378
     if replay_rows:
383379
         replay_ds = Dataset.from_list(replay_rows)
384380
         train_ds = concatenate_datasets([doc_ds, replay_ds])
src/dlm/train/preference/dpo_trainer.pymodified
@@ -119,9 +119,7 @@ def load_reference_model( # pragma: no cover
119119
         try:
120120
             ref = PeftModel.from_pretrained(model, str(adapter_path), is_trainable=False)
121121
         except Exception as exc:
122
-            raise DpoReferenceLoadError(
123
-                adapter_path=str(adapter_path), cause=str(exc)
124
-            ) from exc
122
+            raise DpoReferenceLoadError(adapter_path=str(adapter_path), cause=str(exc)) from exc
125123
         _freeze(ref)
126124
         return ref
127125
 
src/dlm/train/preference/errors.pymodified
@@ -36,8 +36,6 @@ class DpoReferenceLoadError(DpoPhaseError):
3636
     adapter-version path that couldn't be opened."""
3737
 
3838
     def __init__(self, *, adapter_path: str, cause: str) -> None:
39
-        super().__init__(
40
-            f"could not load DPO reference model from {adapter_path}: {cause}"
41
-        )
39
+        super().__init__(f"could not load DPO reference model from {adapter_path}: {cause}")
4240
         self.adapter_path = adapter_path
4341
         self.cause = cause
src/dlm/train/preference/orpo_phase.pymodified
@@ -42,7 +42,6 @@ from dlm.train.trainer import (
4242
 )
4343
 
4444
 if TYPE_CHECKING:
45
-
4645
     from dlm.base_models import BaseModelSpec
4746
     from dlm.doc.parser import ParsedDlm
4847
     from dlm.hardware.capabilities import Capabilities
@@ -294,9 +293,7 @@ def _build_real_orpo_trainer( # pragma: no cover
294293
 
295294
     base_model = load_base_model(spec, plan)
296295
     adapter_dir = store.adapter_version(reference_adapter_version)
297
-    policy_model = PeftModel.from_pretrained(
298
-        base_model, str(adapter_dir), is_trainable=True
299
-    )
296
+    policy_model = PeftModel.from_pretrained(base_model, str(adapter_dir), is_trainable=True)
300297
 
301298
     tok_bringup = prepare_tokenizer(spec.hf_id, spec.revision)
302299
 
@@ -305,9 +302,7 @@ def _build_real_orpo_trainer( # pragma: no cover
305302
     doc_ds = build_dpo_dataset(list(parsed.sections))
306303
     rng = _random.Random(seed + reference_adapter_version)
307304
     now = datetime.now(UTC).replace(tzinfo=None, microsecond=0)
308
-    replay_rows = replay.sample_preference_rows(
309
-        k=max(8, 2 * len(doc_ds)), now=now, rng=rng
310
-    )
305
+    replay_rows = replay.sample_preference_rows(k=max(8, 2 * len(doc_ds)), now=now, rng=rng)
311306
     if replay_rows:
312307
         replay_ds = Dataset.from_list(replay_rows)
313308
         train_ds = concatenate_datasets([doc_ds, replay_ds])
src/dlm/train/preference/phase_orchestrator.pymodified
@@ -116,9 +116,7 @@ def run_phases(
116116
       explicitly request DPO, skip with a warning instead of raising.
117117
     """
118118
     sections = list(parsed.sections)
119
-    pref_cfg = resolve_preference_enabled(
120
-        parsed.frontmatter.training.preference, sections
121
-    )
119
+    pref_cfg = resolve_preference_enabled(parsed.frontmatter.training.preference, sections)
122120
     results: list[PhaseResult] = []
123121
 
124122
     sft_fn = sft_runner or _real_sft_runner()
@@ -137,9 +135,7 @@ def run_phases(
137135
         sft_result = sft_fn(store, parsed, spec, plan, **sft_kwargs)
138136
         results.append(PhaseResult(phase="sft", result=sft_result))
139137
 
140
-    should_run_pref = phase == "preference" or (
141
-        phase == "all" and pref_cfg.enabled
142
-    )
138
+    should_run_pref = phase == "preference" or (phase == "all" and pref_cfg.enabled)
143139
     if should_run_pref:
144140
         if not has_preference_content(sections):
145141
             if phase == "preference":
src/dlm/train/trainer.pymodified
@@ -1257,9 +1257,7 @@ def _expand_directives(
12571257
     if parsed.frontmatter.training.sources is None:
12581258
         return parsed, ()
12591259
 
1260
-    base_path = (
1261
-        parsed.source_path.parent if parsed.source_path is not None else Path.cwd()
1262
-    )
1260
+    base_path = parsed.source_path.parent if parsed.source_path is not None else Path.cwd()
12631261
     result = expand_sources(parsed, base_path=base_path)
12641262
     if not result.sections:
12651263
         return parsed, result.provenance
tests/integration/directives/test_auto_scaffold_cycle.pymodified
@@ -96,9 +96,7 @@ def test_auto_scaffold_train_resume_cycle(
9696
             ),
9797
         )
9898
 
99
-        run1 = run_training(
100
-            store, parsed, spec, plan, mode="fresh", seed=42, max_steps=6
101
-        )
99
+        run1 = run_training(store, parsed, spec, plan, mode="fresh", seed=42, max_steps=6)
102100
         assert run1.adapter_version == 1
103101
 
104102
         # --- Second invocation: reuse scaffolded .dlm ---------------------
@@ -118,9 +116,7 @@ def test_auto_scaffold_train_resume_cycle(
118116
 
119117
         # Train again — should produce adapter v0002 in the same store.
120118
         parsed2 = parse_file(result2.dlm_path)
121
-        run2 = run_training(
122
-            store, parsed2, spec, plan, mode="fresh", seed=42, max_steps=6
123
-        )
119
+        run2 = run_training(store, parsed2, spec, plan, mode="fresh", seed=42, max_steps=6)
124120
         assert run2.adapter_version == 2
125121
 
126122
         manifest = load_manifest(store.manifest)
tests/integration/directives/test_dlm_dir_descent.pymodified
@@ -23,31 +23,31 @@ _VALID_ULID = "01HZ4X7TGZM3J1A2B3C4D5E6F7"
2323
 def _build_tree(root: Path) -> None:
2424
     """Build a repo fixture:
2525
 
26
-        root/
26
+    root/
27
+      .dlm/
28
+        training.yaml   include: ['src/**/*.py', 'docs/**/*.md']
29
+                        exclude: ['**/test_*.py']
30
+                        metadata: {language: python}
31
+        ignore          *.log
32
+      src/
33
+        main.py
34
+        test_main.py
35
+        vendor/
2736
           .dlm/
28
-            training.yaml   include: ['src/**/*.py', 'docs/**/*.md']
29
-                            exclude: ['**/test_*.py']
30
-                            metadata: {language: python}
31
-            ignore          *.log
32
-          src/
33
-            main.py
34
-            test_main.py
35
-            vendor/
36
-              .dlm/
37
-                training.yaml  exclude_defaults: false
38
-                               metadata: {vendor: true_yes}
39
-              .git_shim/       (bare dir w/ file to prove defaults off)
40
-                HEAD
41
-              dep.py
42
-          docs/
43
-            guide.md
44
-            .dlm/
45
-              ignore  !draft.md     (re-include what parent excluded? N/A)
46
-            draft.md
47
-          debug.log
48
-          .env.local
49
-          build/
50
-            output.py
37
+            training.yaml  exclude_defaults: false
38
+                           metadata: {vendor: true_yes}
39
+          .git_shim/       (bare dir w/ file to prove defaults off)
40
+            HEAD
41
+          dep.py
42
+      docs/
43
+        guide.md
44
+        .dlm/
45
+          ignore  !draft.md     (re-include what parent excluded? N/A)
46
+        draft.md
47
+      debug.log
48
+      .env.local
49
+      build/
50
+        output.py
5151
     """
5252
     (root / ".dlm").mkdir()
5353
     (root / ".dlm" / "training.yaml").write_text(
@@ -66,9 +66,7 @@ def _build_tree(root: Path) -> None:
6666
     (root / "src" / "vendor").mkdir()
6767
     (root / "src" / "vendor" / ".dlm").mkdir()
6868
     (root / "src" / "vendor" / ".dlm" / "training.yaml").write_text(
69
-        "dlm_training_version: 1\n"
70
-        "exclude_defaults: false\n"
71
-        "metadata:\n  vendor: true_yes\n",
69
+        "dlm_training_version: 1\nexclude_defaults: false\nmetadata:\n  vendor: true_yes\n",
7270
         encoding="utf-8",
7371
     )
7472
     (root / "src" / "vendor" / "dep.py").write_text("def dep(): pass\n")
tests/integration/directives/test_full_cycle.pymodified
@@ -60,8 +60,7 @@ def test_directive_tree_trains_and_summarizes(
6060
         tree = home / "src"
6161
         tree.mkdir()
6262
         (tree / "a.py").write_text(
63
-            "def add(x, y):\n    return x + y\n\n"
64
-            "def sub(x, y):\n    return x - y\n",
63
+            "def add(x, y):\n    return x + y\n\ndef sub(x, y):\n    return x - y\n",
6564
             encoding="utf-8",
6665
         )
6766
         (tree / "b.py").write_text(
tests/integration/metrics/test_full_cycle.pymodified
@@ -33,9 +33,7 @@ def test_trained_store_has_metrics_rows( # pragma: no cover - slow path
3333
     runs = recent_runs(trained_store.store.root, limit=10)
3434
     assert runs, "trainer.run() did not record any runs"
3535
     latest = runs[0]
36
-    assert latest.status in ("ok", "running"), (
37
-        f"expected 'ok' or 'running', got {latest.status!r}"
38
-    )
36
+    assert latest.status in ("ok", "running"), f"expected 'ok' or 'running', got {latest.status!r}"
3937
 
4038
     steps = steps_for_run(trained_store.store.root, latest.run_id)
4139
     # The tiny-model fixture runs at least one step.
tests/integration/train/multi_adapter/test_two_adapters.pymodified
@@ -148,12 +148,12 @@ def test_two_adapters_each_get_their_own_version_history(
148148
     import json
149149
 
150150
     k_cfg = json.loads(
151
-        (store.adapter_version_for("knowledge", 1) / "adapter_config.json")
152
-        .read_text(encoding="utf-8")
151
+        (store.adapter_version_for("knowledge", 1) / "adapter_config.json").read_text(
152
+            encoding="utf-8"
153
+        )
153154
     )
154155
     t_cfg = json.loads(
155
-        (store.adapter_version_for("tone", 1) / "adapter_config.json")
156
-        .read_text(encoding="utf-8")
156
+        (store.adapter_version_for("tone", 1) / "adapter_config.json").read_text(encoding="utf-8")
157157
     )
158158
     assert k_cfg["r"] == 8, f"knowledge lora_r: {k_cfg['r']}"
159159
     assert t_cfg["r"] == 4, f"tone lora_r: {t_cfg['r']}"
tests/integration/train/multi_adapter/test_weighted_merge.pymodified
@@ -79,9 +79,7 @@ def _train_two_adapters(
7979
         make_dlm(
8080
             sections=[prose(_PROSE)],
8181
             base_model="smollm2-135m",
82
-            training_overrides={
83
-                "adapters": {"knowledge": {}, "tone": {}}
84
-            },
82
+            training_overrides={"adapters": {"knowledge": {}, "tone": {}}},
8583
         ),
8684
         encoding="utf-8",
8785
     )
@@ -134,9 +132,7 @@ def test_weighted_merge_saves_tokenizer_files(
134132
 
135133
     spec = resolve_base_model(parsed.frontmatter.base_model, accept_license=True)
136134
     cached = download_spec(spec, local_files_only=True)
137
-    base_model = AutoModelForCausalLM.from_pretrained(
138
-        str(cached.path), revision=spec.revision
139
-    )
135
+    base_model = AutoModelForCausalLM.from_pretrained(str(cached.path), revision=spec.revision)
140136
 
141137
     entries = [
142138
         MixEntry(name="knowledge", weight=1.0),
@@ -194,9 +190,7 @@ def test_weighted_merge_passes_preflight_tokenizer_vocab(
194190
 
195191
     spec = resolve_base_model(parsed.frontmatter.base_model, accept_license=True)
196192
     cached = download_spec(spec, local_files_only=True)
197
-    base_model = AutoModelForCausalLM.from_pretrained(
198
-        str(cached.path), revision=spec.revision
199
-    )
193
+    base_model = AutoModelForCausalLM.from_pretrained(str(cached.path), revision=spec.revision)
200194
 
201195
     entries = [
202196
         MixEntry(name="knowledge", weight=0.7),
tests/integration/train/preference/test_dpo_tinymodel.pymodified
@@ -67,9 +67,17 @@ def _five_terse_preference_triples() -> str:
6767
     the rejected one — the direction DPO should push completions."""
6868
     pairs = [
6969
         ("What is 2 + 2?", "4.", "The sum of two and two is four, a basic arithmetic fact."),
70
-        ("What color is grass?", "Green.", "Grass is typically a vibrant shade of green most of the year."),
70
+        (
71
+            "What color is grass?",
72
+            "Green.",
73
+            "Grass is typically a vibrant shade of green most of the year.",
74
+        ),
7175
         ("Is water wet?", "Yes.", "Water is generally considered wet in most everyday contexts."),
72
-        ("Do birds fly?", "Most do.", "The majority of bird species can indeed fly, though a few cannot."),
76
+        (
77
+            "Do birds fly?",
78
+            "Most do.",
79
+            "The majority of bird species can indeed fly, though a few cannot.",
80
+        ),
7381
         ("What's 10 - 3?", "7.", "Ten minus three equals seven in standard arithmetic."),
7482
     ]
7583
     parts: list[str] = []
tests/integration/train/preference/test_orpo_tinymodel.pymodified
@@ -77,9 +77,17 @@ def test_orpo_phase_writes_second_adapter_version(trained_store) -> None: # typ
7777
 def _five_terse_preference_triples() -> str:
7878
     pairs = [
7979
         ("What is 2 + 2?", "4.", "The sum of two and two is four, a basic arithmetic fact."),
80
-        ("What color is grass?", "Green.", "Grass is typically a vibrant shade of green most of the year."),
80
+        (
81
+            "What color is grass?",
82
+            "Green.",
83
+            "Grass is typically a vibrant shade of green most of the year.",
84
+        ),
8185
         ("Is water wet?", "Yes.", "Water is generally considered wet in most everyday contexts."),
82
-        ("Do birds fly?", "Most do.", "The majority of bird species can indeed fly, though a few cannot."),
86
+        (
87
+            "Do birds fly?",
88
+            "Most do.",
89
+            "The majority of bird species can indeed fly, though a few cannot.",
90
+        ),
8391
         ("What's 10 - 3?", "7.", "Ten minus three equals seven in standard arithmetic."),
8492
     ]
8593
     parts: list[str] = []
tests/unit/cli/test_prompt_adapter_flag.pymodified
@@ -48,9 +48,7 @@ def _scaffold_multi_doc(tmp_path: Path) -> Path:
4848
 
4949
 
5050
 class TestFlatDocRejectsAdapter:
51
-    def test_single_adapter_doc_with_adapter_flag_exits_2(
52
-        self, tmp_path: Path
53
-    ) -> None:
51
+    def test_single_adapter_doc_with_adapter_flag_exits_2(self, tmp_path: Path) -> None:
5452
         doc = _scaffold_flat_doc(tmp_path)
5553
         runner = CliRunner()
5654
         result = runner.invoke(
tests/unit/cli/test_serve_guard.pymodified
@@ -18,12 +18,7 @@ from dlm.cli.app import app
1818
 
1919
 def _write_minimal_dlm(path: Path, dlm_id: str = "01KPQ9M3" + "0" * 18) -> None:
2020
     path.write_text(
21
-        "---\n"
22
-        f"dlm_id: {dlm_id}\n"
23
-        "dlm_version: 6\n"
24
-        "base_model: smollm2-135m\n"
25
-        "---\n"
26
-        "body\n",
21
+        f"---\ndlm_id: {dlm_id}\ndlm_version: 6\nbase_model: smollm2-135m\n---\nbody\n",
2722
         encoding="utf-8",
2823
     )
2924
 
@@ -40,8 +35,10 @@ class TestServeUntrainedGuard:
4035
         result = runner.invoke(
4136
             app,
4237
             [
43
-                "--home", str(tmp_path / "home"),
44
-                "serve", str(doc),
38
+                "--home",
39
+                str(tmp_path / "home"),
40
+                "serve",
41
+                str(doc),
4542
             ],
4643
         )
4744
         assert result.exit_code == 1, result.output
tests/unit/cli/test_train_scaffold_cli.pymodified
@@ -32,9 +32,7 @@ def _captured() -> dict[str, Any]:
3232
     return {}
3333
 
3434
 
35
-def _install_capturing_fake(
36
-    monkeypatch: pytest.MonkeyPatch, captured: dict[str, Any]
37
-) -> None:
35
+def _install_capturing_fake(monkeypatch: pytest.MonkeyPatch, captured: dict[str, Any]) -> None:
3836
     """Replace `run_phases` with a stub that records call args and
3937
     returns `[]` (triggering the CLI's "no-op: nothing to train" path
4038
     with exit code 0). The scaffold + manifest + expand_sources pipeline
@@ -80,10 +78,14 @@ class TestDlmTrainDirScaffold:
8078
             result = runner.invoke(
8179
                 app,
8280
                 [
83
-                    "--home", str(tmp_path / "home"),
84
-                    "train", str(corpus),
85
-                    "--base", "smollm2-135m",
86
-                    "--include", "**/*.md",
81
+                    "--home",
82
+                    str(tmp_path / "home"),
83
+                    "train",
84
+                    str(corpus),
85
+                    "--base",
86
+                    "smollm2-135m",
87
+                    "--include",
88
+                    "**/*.md",
8789
                 ],
8890
             )
8991
 
@@ -105,12 +107,8 @@ class TestDlmTrainDirScaffold:
105107
         always 0."""
106108
         corpus = tmp_path / "corpus"
107109
         corpus.mkdir()
108
-        (corpus / "alpha.md").write_text(
109
-            "# Alpha\nalpha-unique-token\n", encoding="utf-8"
110
-        )
111
-        (corpus / "beta.md").write_text(
112
-            "# Beta\nbeta-unique-token\n", encoding="utf-8"
113
-        )
110
+        (corpus / "alpha.md").write_text("# Alpha\nalpha-unique-token\n", encoding="utf-8")
111
+        (corpus / "beta.md").write_text("# Beta\nbeta-unique-token\n", encoding="utf-8")
114112
 
115113
         captured = _captured()
116114
         _install_capturing_fake(monkeypatch, captured)
@@ -120,10 +118,14 @@ class TestDlmTrainDirScaffold:
120118
             result = runner.invoke(
121119
                 app,
122120
                 [
123
-                    "--home", str(tmp_path / "home"),
124
-                    "train", str(corpus),
125
-                    "--base", "smollm2-135m",
126
-                    "--include", "**/*.md",
121
+                    "--home",
122
+                    str(tmp_path / "home"),
123
+                    "train",
124
+                    str(corpus),
125
+                    "--base",
126
+                    "smollm2-135m",
127
+                    "--include",
128
+                    "**/*.md",
127129
                 ],
128130
             )
129131
 
@@ -146,12 +148,8 @@ class TestDlmTrainDirScaffold:
146148
         )
147149
         combined = _section_texts(expanded.sections)
148150
         rendered = "\n".join(f"  {s.content[:80]!r}" for s in expanded.sections)
149
-        assert "alpha-unique-token" in combined, (
150
-            "B2: alpha.md not ingested. got:\n" + rendered
151
-        )
152
-        assert "beta-unique-token" in combined, (
153
-            "B2: beta.md not ingested. got:\n" + rendered
154
-        )
151
+        assert "alpha-unique-token" in combined, "B2: alpha.md not ingested. got:\n" + rendered
152
+        assert "beta-unique-token" in combined, "B2: beta.md not ingested. got:\n" + rendered
155153
         assert expanded.provenance[0].file_count == 2
156154
         assert expanded.provenance[0].total_bytes > 0
157155
 
@@ -173,10 +171,14 @@ class TestDlmTrainDirScaffold:
173171
             result = runner.invoke(
174172
                 app,
175173
                 [
176
-                    "--home", str(tmp_path / "home"),
177
-                    "train", str(corpus),
178
-                    "--base", "smollm2-135m",
179
-                    "--include", "**/*.md",
174
+                    "--home",
175
+                    str(tmp_path / "home"),
176
+                    "train",
177
+                    str(corpus),
178
+                    "--base",
179
+                    "smollm2-135m",
180
+                    "--include",
181
+                    "**/*.md",
180182
                 ],
181183
             )
182184
 
@@ -217,10 +219,14 @@ class TestDlmTrainDirScaffold:
217219
             r1 = runner.invoke(
218220
                 app,
219221
                 [
220
-                    "--home", str(tmp_path / "home"),
221
-                    "train", str(corpus),
222
-                    "--base", "smollm2-135m",
223
-                    "--include", "**/*.md",
222
+                    "--home",
223
+                    str(tmp_path / "home"),
224
+                    "train",
225
+                    str(corpus),
226
+                    "--base",
227
+                    "smollm2-135m",
228
+                    "--include",
229
+                    "**/*.md",
224230
                 ],
225231
             )
226232
             assert r1.exit_code == 0, r1.output
@@ -235,13 +241,14 @@ class TestDlmTrainDirScaffold:
235241
             r2 = runner.invoke(
236242
                 app,
237243
                 [
238
-                    "--home", str(tmp_path / "home"),
239
-                    "train", str(corpus),
244
+                    "--home",
245
+                    str(tmp_path / "home"),
246
+                    "train",
247
+                    str(corpus),
240248
                 ],
241249
             )
242250
 
243251
         assert r2.exit_code == 0, r2.output
244252
         assert manifest_path.stat().st_mtime_ns == first_mtime, (
245
-            "manifest was rewritten on the resume path; "
246
-            "training history could be lost"
253
+            "manifest was rewritten on the resume path; training history could be lost"
247254
         )
tests/unit/directives/test_cache.pymodified
@@ -98,9 +98,7 @@ class TestInvalidation:
9898
         cache.put(key_a, _tokens(4))
9999
         assert cache.get(key_b) is None
100100
 
101
-    def test_missing_file_recovers(
102
-        self, tmp_path: Path, caplog: pytest.LogCaptureFixture
103
-    ) -> None:
101
+    def test_missing_file_recovers(self, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
104102
         """If the on-disk entry vanishes under us, get() should treat
105103
         it as a miss and clean up the stale manifest row."""
106104
         import logging
tests/unit/directives/test_defaults.pymodified
@@ -93,6 +93,4 @@ def test_default_excludes_catch_known_traps(path: str) -> None:
9393
     ],
9494
 )
9595
 def test_default_excludes_leave_source_alone(path: str) -> None:
96
-    assert not _matches_any_default(path), (
97
-        f"DEFAULT_EXCLUDES wrongly caught: {path}"
98
-    )
96
+    assert not _matches_any_default(path), f"DEFAULT_EXCLUDES wrongly caught: {path}"
tests/unit/directives/test_discovery.pymodified
@@ -79,9 +79,7 @@ def test_schema_violation_logs_and_continues(
7979
     tmp_path: Path, caplog: pytest.LogCaptureFixture
8080
 ) -> None:
8181
     (tmp_path / ".dlm").mkdir()
82
-    (tmp_path / ".dlm" / "training.yaml").write_text(
83
-        "dlm_training_version: 1\nunknown_key: bad\n"
84
-    )
82
+    (tmp_path / ".dlm" / "training.yaml").write_text("dlm_training_version: 1\nunknown_key: bad\n")
8583
     caplog.set_level(logging.WARNING, logger="dlm.directives.discovery")
8684
     configs = discover_configs(tmp_path)
8785
     assert configs[0].config is None
@@ -101,9 +99,7 @@ def test_training_yaml_non_mapping_top_level(
10199
 
102100
 def test_both_files_coexist(tmp_path: Path) -> None:
103101
     (tmp_path / ".dlm").mkdir()
104
-    (tmp_path / ".dlm" / "training.yaml").write_text(
105
-        "dlm_training_version: 1\nexclude: ['a']\n"
106
-    )
102
+    (tmp_path / ".dlm" / "training.yaml").write_text("dlm_training_version: 1\nexclude: ['a']\n")
107103
     (tmp_path / ".dlm" / "ignore").write_text("*.tmp\n")
108104
     (c,) = discover_configs(tmp_path)
109105
     assert c.config is not None
tests/unit/directives/test_expand.pymodified
@@ -81,12 +81,7 @@ def test_max_files_truncates_deterministically(tmp_path: Path) -> None:
8181
     src.mkdir()
8282
     for i in range(5):
8383
         (src / f"{i}.py").write_text(f"# {i}\n")
84
-    body = (
85
-        "  sources:\n"
86
-        "    - path: src\n"
87
-        "      include: ['**/*.py']\n"
88
-        "      max_files: 2\n"
89
-    )
84
+    body = "  sources:\n    - path: src\n      include: ['**/*.py']\n      max_files: 2\n"
9085
     parsed, _ = _make_parsed(body, tmp_path)
9186
     result = expand_sources(parsed, base_path=tmp_path)  # type: ignore[arg-type]
9287
     # Sorted: 0.py, 1.py land; 2/3/4 get dropped
@@ -101,12 +96,7 @@ def test_max_bytes_per_file_skips_oversize(tmp_path: Path) -> None:
10196
     src.mkdir()
10297
     (src / "small.py").write_text("x\n")  # 2 bytes
10398
     (src / "big.py").write_text("x" * 100)
104
-    body = (
105
-        "  sources:\n"
106
-        "    - path: src\n"
107
-        "      include: ['**/*.py']\n"
108
-        "      max_bytes_per_file: 10\n"
109
-    )
99
+    body = "  sources:\n    - path: src\n      include: ['**/*.py']\n      max_bytes_per_file: 10\n"
110100
     parsed, _ = _make_parsed(body, tmp_path)
111101
     result = expand_sources(parsed, base_path=tmp_path)  # type: ignore[arg-type]
112102
     assert len(result.sections) == 1
@@ -157,11 +147,7 @@ def test_strict_policy_refuses_external_path(tmp_path: Path) -> None:
157147
     outside.mkdir(exist_ok=True)
158148
     try:
159149
         (outside / "a.py").write_text("x")
160
-        body = (
161
-            "  sources_policy: strict\n"
162
-            "  sources:\n"
163
-            f"    - path: {outside}\n"
164
-        )
150
+        body = f"  sources_policy: strict\n  sources:\n    - path: {outside}\n"
165151
         parsed, _ = _make_parsed(body, tmp_path)
166152
         with pytest.raises(DirectivePolicyError):
167153
             expand_sources(parsed, base_path=tmp_path)  # type: ignore[arg-type]
@@ -176,7 +162,7 @@ def test_permissive_policy_allows_external_path(tmp_path: Path) -> None:
176162
     outside.mkdir(exist_ok=True)
177163
     try:
178164
         (outside / "a.py").write_text("ok\n")
179
-        body = "  sources:\n" f"    - path: {outside}\n      include: ['**/*.py']\n"
165
+        body = f"  sources:\n    - path: {outside}\n      include: ['**/*.py']\n"
180166
         parsed, _ = _make_parsed(body, tmp_path)
181167
         result = expand_sources(parsed, base_path=tmp_path)  # type: ignore[arg-type]
182168
         assert len(result.sections) == 1
tests/unit/directives/test_merge.pymodified
@@ -99,18 +99,24 @@ def test_training_yaml_exclude_blocks_file(tmp_path: Path) -> None:
9999
     )
100100
     directive = _directive(tmp_path, include=("**/*.py",))
101101
     configs = discover_configs(tmp_path)
102
-    assert effective_config_for(
103
-        tmp_path / "src" / "main.py",
104
-        source_root=tmp_path,
105
-        discovered=configs,
106
-        parent_directive=directive,
107
-    ).included is True
108
-    assert effective_config_for(
109
-        tmp_path / "src" / "test_main.py",
110
-        source_root=tmp_path,
111
-        discovered=configs,
112
-        parent_directive=directive,
113
-    ).included is False
102
+    assert (
103
+        effective_config_for(
104
+            tmp_path / "src" / "main.py",
105
+            source_root=tmp_path,
106
+            discovered=configs,
107
+            parent_directive=directive,
108
+        ).included
109
+        is True
110
+    )
111
+    assert (
112
+        effective_config_for(
113
+            tmp_path / "src" / "test_main.py",
114
+            source_root=tmp_path,
115
+            discovered=configs,
116
+            parent_directive=directive,
117
+        ).included
118
+        is False
119
+    )
114120
 
115121
 
116122
 # ---- .dlm/ignore negation --------------------------------------------------
@@ -136,18 +142,24 @@ def test_ignore_negation_re_includes_file(tmp_path: Path) -> None:
136142
     _write(tmp_path / ".dlm" / "ignore", "*.log\n!special.log\n")
137143
     directive = _directive(tmp_path)
138144
     configs = discover_configs(tmp_path)
139
-    assert effective_config_for(
140
-        tmp_path / "debug.log",
141
-        source_root=tmp_path,
142
-        discovered=configs,
143
-        parent_directive=directive,
144
-    ).included is False
145
-    assert effective_config_for(
146
-        tmp_path / "special.log",
147
-        source_root=tmp_path,
148
-        discovered=configs,
149
-        parent_directive=directive,
150
-    ).included is True
145
+    assert (
146
+        effective_config_for(
147
+            tmp_path / "debug.log",
148
+            source_root=tmp_path,
149
+            discovered=configs,
150
+            parent_directive=directive,
151
+        ).included
152
+        is False
153
+    )
154
+    assert (
155
+        effective_config_for(
156
+            tmp_path / "special.log",
157
+            source_root=tmp_path,
158
+            discovered=configs,
159
+            parent_directive=directive,
160
+        ).included
161
+        is True
162
+    )
151163
 
152164
 
153165
 def test_deeper_ignore_negation_unblocks_parent_exclude(tmp_path: Path) -> None:
@@ -176,18 +188,24 @@ def test_default_excludes_apply_by_default(tmp_path: Path) -> None:
176188
     _write(tmp_path / "src" / "main.py", "x")
177189
     directive = _directive(tmp_path)
178190
     configs = discover_configs(tmp_path)
179
-    assert effective_config_for(
180
-        tmp_path / ".git" / "HEAD",
181
-        source_root=tmp_path,
182
-        discovered=configs,
183
-        parent_directive=directive,
184
-    ).included is False
185
-    assert effective_config_for(
186
-        tmp_path / "src" / "main.py",
187
-        source_root=tmp_path,
188
-        discovered=configs,
189
-        parent_directive=directive,
190
-    ).included is True
191
+    assert (
192
+        effective_config_for(
193
+            tmp_path / ".git" / "HEAD",
194
+            source_root=tmp_path,
195
+            discovered=configs,
196
+            parent_directive=directive,
197
+        ).included
198
+        is False
199
+    )
200
+    assert (
201
+        effective_config_for(
202
+            tmp_path / "src" / "main.py",
203
+            source_root=tmp_path,
204
+            discovered=configs,
205
+            parent_directive=directive,
206
+        ).included
207
+        is True
208
+    )
191209
 
192210
 
193211
 def test_exclude_defaults_false_disables_default_set(tmp_path: Path) -> None:
@@ -230,9 +248,9 @@ def test_metadata_shallow_to_deep_merge(tmp_path: Path) -> None:
230248
         parent_directive=directive,
231249
     )
232250
     assert eff.tags == {
233
-        "language": "python",       # from shallower
251
+        "language": "python",  # from shallower
234252
         "domain": "vendor_override",  # deeper overrides shallower
235
-        "source": "third_party",   # from deeper only
253
+        "source": "third_party",  # from deeper only
236254
     }
237255
 
238256
 
tests/unit/directives/test_safety.pymodified
@@ -130,11 +130,7 @@ def test_enumerate_is_deterministic(tmp_path: Path) -> None:
130130
 def test_enumerate_exclude_wins(tmp_path: Path) -> None:
131131
     (tmp_path / "keep.py").write_text("x")
132132
     (tmp_path / "skip.py").write_text("x")
133
-    got = list(
134
-        enumerate_matching_files(
135
-            tmp_path, include=("**/*.py",), exclude=("skip.py",)
136
-        )
137
-    )
133
+    got = list(enumerate_matching_files(tmp_path, include=("**/*.py",), exclude=("skip.py",)))
138134
     assert [p.name for p in got] == ["keep.py"]
139135
 
140136
 
tests/unit/doc/test_fence_adapter_suffix.pymodified
@@ -43,9 +43,7 @@ class TestParseFenceSuffix:
4343
         assert instr[0].adapter == "tone"
4444
 
4545
     def test_preference_fence_adapter(self) -> None:
46
-        parsed = _parse(
47
-            "::preference#knowledge::\n### Prompt\nq\n### Chosen\nc\n### Rejected\nr\n"
48
-        )
46
+        parsed = _parse("::preference#knowledge::\n### Prompt\nq\n### Chosen\nc\n### Rejected\nr\n")
4947
         pref = [s for s in parsed.sections if s.type == SectionType.PREFERENCE]
5048
         assert pref
5149
         assert pref[0].adapter == "knowledge"
@@ -97,9 +95,7 @@ class TestSectionIdentityUnchanged:
9795
         """Routing is structural, not content — same content with and
9896
         without a `#adapter` suffix must produce the same section_id
9997
         so replay snapshots don't duplicate rows on routing edits."""
100
-        s_plain = Section(
101
-            type=SectionType.INSTRUCTION, content="### Q\nhi\n### A\nbye"
102
-        )
98
+        s_plain = Section(type=SectionType.INSTRUCTION, content="### Q\nhi\n### A\nbye")
10399
         s_routed = Section(
104100
             type=SectionType.INSTRUCTION,
105101
             content="### Q\nhi\n### A\nbye",
tests/unit/doc/test_migration_v1_to_v2.pymodified
@@ -87,9 +87,7 @@ class TestPartialDpoBlock:
8787
 
8888
 class TestReferenceRename:
8989
     def test_pre_dpo_adapter_becomes_pre_adapter(self) -> None:
90
-        raw: dict[str, Any] = {
91
-            "training": {"dpo": {"reference": "pre_dpo_adapter"}}
92
-        }
90
+        raw: dict[str, Any] = {"training": {"dpo": {"reference": "pre_dpo_adapter"}}}
9391
         out = migrate(raw)
9492
         assert out["training"]["preference"]["reference"] == "pre_adapter"
9593
 
tests/unit/doc/test_round_trip_v4_adapters.pymodified
@@ -51,9 +51,7 @@ def test_round_trip_v4_multi_adapter_doc_is_idempotent() -> None:
5151
 
5252
     once = serialize(parse_text(original))
5353
     twice = serialize(parse_text(once))
54
-    assert once == twice, (
55
-        "v4 adapters doc not idempotent under serialize round-trip"
56
-    )
54
+    assert once == twice, "v4 adapters doc not idempotent under serialize round-trip"
5755
 
5856
 
5957
 def test_round_trip_preserves_fence_suffixes() -> None:
tests/unit/doc/test_schema.pymodified
@@ -192,9 +192,7 @@ class TestTrainingConfigPreferenceSubfield:
192192
 
193193
     def test_rejects_unknown_field_inside_preference(self) -> None:
194194
         with pytest.raises(ValidationError):
195
-            TrainingConfig.model_validate(
196
-                {"preference": {"enabled": True, "rubbish": 1}}
197
-            )
195
+            TrainingConfig.model_validate({"preference": {"enabled": True, "rubbish": 1}})
198196
 
199197
 
200198
 class TestCptConfig:
@@ -233,17 +231,13 @@ class TestTrainingConfigCptSubfield:
233231
         assert t.cpt.embed_warmup_steps == 0
234232
 
235233
     def test_accepts_nested_dict_for_cpt(self) -> None:
236
-        t = TrainingConfig.model_validate(
237
-            {"cpt": {"schedule": "dapt", "embed_warmup_steps": 200}}
238
-        )
234
+        t = TrainingConfig.model_validate({"cpt": {"schedule": "dapt", "embed_warmup_steps": 200}})
239235
         assert t.cpt.schedule == "dapt"
240236
         assert t.cpt.embed_warmup_steps == 200
241237
 
242238
     def test_rejects_unknown_field_inside_cpt(self) -> None:
243239
         with pytest.raises(ValidationError):
244
-            TrainingConfig.model_validate(
245
-                {"cpt": {"schedule": "dapt", "rubbish": 1}}
246
-            )
240
+            TrainingConfig.model_validate({"cpt": {"schedule": "dapt", "rubbish": 1}})
247241
 
248242
 
249243
 class TestAdapterConfig:
@@ -317,15 +311,11 @@ class TestNamedAdapters:
317311
 
318312
     def test_flat_lora_r_with_block_rejected(self) -> None:
319313
         with pytest.raises(ValidationError, match="flat per-adapter fields"):
320
-            TrainingConfig.model_validate(
321
-                {"lora_r": 32, "adapters": {"knowledge": {}}}
322
-            )
314
+            TrainingConfig.model_validate({"lora_r": 32, "adapters": {"knowledge": {}}})
323315
 
324316
     def test_flat_learning_rate_with_block_rejected(self) -> None:
325317
         with pytest.raises(ValidationError, match="flat per-adapter fields"):
326
-            TrainingConfig.model_validate(
327
-                {"learning_rate": 1e-3, "adapters": {"tone": {}}}
328
-            )
318
+            TrainingConfig.model_validate({"learning_rate": 1e-3, "adapters": {"tone": {}}})
329319
 
330320
     def test_top_level_shared_knobs_allowed_alongside_block(self) -> None:
331321
         # seed, num_epochs, sequence_len, etc. are explicitly shared
tests/unit/eval/test_summary.pymodified
@@ -130,9 +130,7 @@ class TestMixedModeFields:
130130
 
131131
 class TestSplitLossByMode:
132132
     def test_mixed_rows(self) -> None:
133
-        out = split_loss_by_mode(
134
-            [(1.0, "cpt"), (2.0, "cpt"), (0.5, "sft"), (1.5, "sft")]
135
-        )
133
+        out = split_loss_by_mode([(1.0, "cpt"), (2.0, "cpt"), (0.5, "sft"), (1.5, "sft")])
136134
         assert out == LossByMode(cpt=1.5, sft=1.0)
137135
 
138136
     def test_all_cpt(self) -> None:
@@ -151,9 +149,7 @@ class TestSplitLossByMode:
151149
         assert out.sft is None
152150
 
153151
     def test_unknown_modes_ignored(self) -> None:
154
-        out = split_loss_by_mode(
155
-            [(1.0, "cpt"), (2.0, "preference"), (3.0, "other")]
156
-        )
152
+        out = split_loss_by_mode([(1.0, "cpt"), (2.0, "preference"), (3.0, "other")])
157153
         assert out.cpt == pytest.approx(1.0)
158154
         assert out.sft is None
159155
 
tests/unit/export/test_vendoring.pymodified
@@ -73,9 +73,7 @@ class TestLlamaQuantizeBin:
7373
         assert path.is_file()
7474
         assert path.name == "llama-quantize"
7575
 
76
-    def test_missing_binary_raises(
77
-        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
78
-    ) -> None:
76
+    def test_missing_binary_raises(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
7977
         # Clear PATH so the `shutil.which` fallback can't find a
8078
         # brew-installed llama-quantize on the developer's machine.
8179
         monkeypatch.setenv("PATH", str(tmp_path / "empty"))
tests/unit/export/test_weighted_merge.pymodified
@@ -128,9 +128,7 @@ class TestResolveFirstSourcePath:
128128
         with pytest.raises(InvalidMixSpecError, match="empty mix"):
129129
             resolve_first_source_path(store, [])
130130
 
131
-    def test_missing_adapter_raises_export_error(
132
-        self, tmp_path
133
-    ) -> None:  # type: ignore[no-untyped-def]
131
+    def test_missing_adapter_raises_export_error(self, tmp_path) -> None:  # type: ignore[no-untyped-def]
134132
         from dlm.export.errors import ExportError
135133
         from dlm.export.weighted_merge import resolve_first_source_path
136134
         from dlm.store.paths import StorePath
tests/unit/hardware/test_capabilities.pymodified
@@ -84,9 +84,7 @@ class TestMlxAvailability:
8484
             caps = probe()
8585
         assert caps.has_mlx is True
8686
 
87
-    def test_mps_reports_no_mlx_when_mlx_lm_missing(
88
-        self, monkeypatch: pytest.MonkeyPatch
89
-    ) -> None:
87
+    def test_mps_reports_no_mlx_when_mlx_lm_missing(self, monkeypatch: pytest.MonkeyPatch) -> None:
9088
         from dlm.hardware import capabilities as caps_mod
9189
 
9290
         real_avail = caps_mod._module_available
tests/unit/hardware/test_f28_multi_adapter_qlora.pymodified
@@ -14,17 +14,13 @@ from tests.fixtures.hardware_mocks import force_cuda
1414
 
1515
 def _qlora_multi_doc(num: int) -> TrainingConfig:
1616
     """TrainingConfig with `num` QLoRA adapters declared."""
17
-    adapters = {
18
-        f"a{i}": AdapterConfig(adapter="qlora") for i in range(num)
19
-    }
17
+    adapters = {f"a{i}": AdapterConfig(adapter="qlora") for i in range(num)}
2018
     return TrainingConfig.model_validate({"adapters": adapters})
2119
 
2220
 
2321
 def _qlora_multi_doc_with_rank(num: int, lora_r: int) -> TrainingConfig:
2422
     """Multi-adapter doc with `num` QLoRA adapters at the given lora_r."""
25
-    adapters = {
26
-        f"a{i}": AdapterConfig(adapter="qlora", lora_r=lora_r) for i in range(num)
27
-    }
23
+    adapters = {f"a{i}": AdapterConfig(adapter="qlora", lora_r=lora_r) for i in range(num)}
2824
     return TrainingConfig.model_validate({"adapters": adapters})
2925
 
3026
 
@@ -85,9 +81,7 @@ class TestF28MultiAdapterQLoraRefusal:
8581
         adapters = {"a0": AdapterConfig(), "a1": AdapterConfig()}
8682
         lora_multi = TrainingConfig.model_validate({"adapters": adapters})
8783
         # LoRA bypasses QLoRA refusals entirely.
88
-        check_refusals(
89
-            lora_multi, caps, base_params=1_500_000_000, num_adapters=2
90
-        )
84
+        check_refusals(lora_multi, caps, base_params=1_500_000_000, num_adapters=2)
9185
 
9286
     def test_small_base_low_rank_multi_qlora_passes(self) -> None:
9387
         """The old formula falsely refused small-base multi-QLoRA.
@@ -136,9 +130,7 @@ class TestEffectiveAdapter:
136130
             }
137131
         )
138132
         with pytest.raises(ResolutionError, match="Multi-adapter QLoRA"):
139
-            check_refusals(
140
-                mixed, caps, base_params=7_000_000_000, num_adapters=3
141
-            )
133
+            check_refusals(mixed, caps, base_params=7_000_000_000, num_adapters=3)
142134
 
143135
     def test_mixed_adapter_error_names_only_qlora_offenders(self) -> None:
144136
         with force_cuda(vram_gb=12.0):
@@ -153,9 +145,7 @@ class TestEffectiveAdapter:
153145
             }
154146
         )
155147
         with pytest.raises(ResolutionError) as exc_info:
156
-            check_refusals(
157
-                mixed, caps, base_params=7_000_000_000, num_adapters=3
158
-            )
148
+            check_refusals(mixed, caps, base_params=7_000_000_000, num_adapters=3)
159149
         message = str(exc_info.value)
160150
         assert "qlora_one" in message
161151
         assert "lora_a" not in message
tests/unit/hardware/test_plan.pymodified
@@ -45,9 +45,7 @@ class TestPrecisionPicker:
4545
         with force_mps():
4646
             caps = probe()
4747
         with caplog.at_level(logging.WARNING, logger="dlm.hardware.plan"):  # type: ignore[attr-defined]
48
-            plan = resolve(
49
-                _cfg(precision="fp16"), caps, base_params=8_000_000_000, seq_len=2048
50
-            )
48
+            plan = resolve(_cfg(precision="fp16"), caps, base_params=8_000_000_000, seq_len=2048)
5149
         assert plan.precision == "fp16"
5250
         # The caller must see the risk explicitly — silent fp16 on MPS
5351
         # is what caused the original bug.
@@ -63,9 +61,7 @@ class TestPrecisionPicker:
6361
         with force_mps():
6462
             caps = probe()
6563
         with caplog.at_level(logging.WARNING, logger="dlm.hardware.plan"):  # type: ignore[attr-defined]
66
-            plan = resolve(
67
-                _cfg(precision="bf16"), caps, base_params=1_500_000_000, seq_len=2048
68
-            )
64
+            plan = resolve(_cfg(precision="bf16"), caps, base_params=1_500_000_000, seq_len=2048)
6965
         assert plan.precision == "bf16"
7066
         assert caplog.records == []  # type: ignore[attr-defined]
7167
 
@@ -73,9 +69,7 @@ class TestPrecisionPicker:
7369
         # CUDA default is bf16 (Ampere+) — override to fp32 honored.
7470
         with force_cuda(sm=(8, 0)):
7571
             caps = probe()
76
-        plan = resolve(
77
-            _cfg(precision="fp32"), caps, base_params=1_500_000_000, seq_len=2048
78
-        )
72
+        plan = resolve(_cfg(precision="fp32"), caps, base_params=1_500_000_000, seq_len=2048)
7973
         assert plan.precision == "fp32"
8074
 
8175
 
@@ -204,9 +198,7 @@ class TestDpoPhaseAdjustments:
204198
         # at 1, not round to 0.
205199
         with force_cuda(sm=(8, 9), vram_gb=4.0):
206200
             caps = probe()
207
-        dpo = resolve(
208
-            _cfg(), caps, base_params=1_500_000_000, seq_len=2048, phase="dpo"
209
-        )
201
+        dpo = resolve(_cfg(), caps, base_params=1_500_000_000, seq_len=2048, phase="dpo")
210202
         assert dpo.micro_batch_size >= 1
211203
 
212204
     def test_dpo_peak_vram_exceeds_sft(self) -> None:
@@ -228,12 +220,8 @@ class TestDpoPhaseAdjustments:
228220
     def test_dpo_reason_mentions_phase(self) -> None:
229221
         with force_cuda(sm=(8, 9), vram_gb=24.0):
230222
             caps = probe()
231
-        dpo = resolve(
232
-            _cfg(), caps, base_params=1_500_000_000, seq_len=2048, phase="dpo"
233
-        )
234
-        sft = resolve(
235
-            _cfg(), caps, base_params=1_500_000_000, seq_len=2048, phase="sft"
236
-        )
223
+        dpo = resolve(_cfg(), caps, base_params=1_500_000_000, seq_len=2048, phase="dpo")
224
+        sft = resolve(_cfg(), caps, base_params=1_500_000_000, seq_len=2048, phase="sft")
237225
         assert "phase=dpo" in dpo.reason
238226
         assert "phase=dpo" not in sft.reason
239227
 
tests/unit/inference/test_resolve_adapter_path.pymodified
@@ -49,13 +49,9 @@ class TestNamedLayout:
4949
         v1 = s.adapter_version_for("knowledge", 1)
5050
         v1.mkdir(parents=True)
5151
         s.set_current_adapter_for("knowledge", v1)
52
-        assert (
53
-            resolve_adapter_path(s, adapter_name="knowledge") == v1.resolve()
54
-        )
52
+        assert resolve_adapter_path(s, adapter_name="knowledge") == v1.resolve()
5553
 
56
-    def test_missing_named_pointer_mentions_adapter_name(
57
-        self, tmp_path: Path
58
-    ) -> None:
54
+    def test_missing_named_pointer_mentions_adapter_name(self, tmp_path: Path) -> None:
5955
         s = _store(tmp_path)
6056
         s.ensure_adapter_layout("knowledge")
6157
         with pytest.raises(AdapterNotFoundError, match="'knowledge'"):
tests/unit/lock/test_mismatch_policy.pymodified
@@ -49,9 +49,9 @@ class TestAccelerateUninstall:
4949
         current = _lock(pinned_versions={"torch": "2.5.1"})
5050
         msgs = [m for _s, m in classify_mismatches(prior, current)]
5151
         # `_rule_minor_peers` fires on peer disappear with "no longer pinned".
52
-        assert any(
53
-            "accelerate" in m and "no longer pinned" in m for m in msgs
54
-        ), f"expected accelerate-removal warning, got {msgs!r}"
52
+        assert any("accelerate" in m and "no longer pinned" in m for m in msgs), (
53
+            f"expected accelerate-removal warning, got {msgs!r}"
54
+        )
5555
 
5656
 
5757
 class TestWorldSize:
tests/unit/metrics/test_db_schema.pymodified
@@ -20,10 +20,7 @@ class TestConnect:
2020
     def test_creates_schema(self, tmp_path: Path) -> None:
2121
         with connect(tmp_path) as conn:
2222
             tables = {
23
-                row[0]
24
-                for row in conn.execute(
25
-                    "SELECT name FROM sqlite_master WHERE type='table'"
26
-                )
23
+                row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")
2724
             }
2825
         assert tables == {"runs", "steps", "evals", "exports", "tokenization"}
2926
 
@@ -65,14 +62,10 @@ class TestEnsureSchema:
6562
             conn.execute(
6663
                 "INSERT INTO runs (run_id, started_at, status) VALUES (1, 'now', 'running')"
6764
             )
68
-            conn.execute(
69
-                "INSERT INTO steps (run_id, step, loss, at) VALUES (1, 1, 0.5, 'now')"
70
-            )
65
+            conn.execute("INSERT INTO steps (run_id, step, loss, at) VALUES (1, 1, 0.5, 'now')")
7166
             # Duplicate (1, 1) should violate PK unless we upsert.
7267
             try:
73
-                conn.execute(
74
-                    "INSERT INTO steps (run_id, step, loss, at) VALUES (1, 1, 0.4, 'now')"
75
-                )
68
+                conn.execute("INSERT INTO steps (run_id, step, loss, at) VALUES (1, 1, 0.4, 'now')")
7669
                 raise AssertionError("duplicate PK accepted")
7770
             except sqlite3.IntegrityError:
7871
                 pass
tests/unit/metrics/test_queries.pymodified
@@ -22,9 +22,7 @@ def _seed(store_root: Path) -> None:
2222
     """Populate a DB with three runs and a handful of steps/evals."""
2323
     rec = MetricsRecorder(store_root)
2424
     for run_id in (1, 2, 3):
25
-        rec.record_run_start(
26
-            RunStart(run_id=run_id, adapter_version=run_id, phase="sft", seed=42)
27
-        )
25
+        rec.record_run_start(RunStart(run_id=run_id, adapter_version=run_id, phase="sft", seed=42))
2826
         for step in (10, 20, 30):
2927
             rec.record_step(StepEvent(run_id=run_id, step=step, loss=2.0 - 0.1 * step))
3028
         rec.record_eval(EvalEvent(run_id=run_id, step=30, val_loss=1.5))
tests/unit/replay/test_store.pymodified
@@ -90,29 +90,21 @@ class TestSampleRows:
9090
         assert raw_sid in rows[0]["_dlm_section_id"]
9191
 
9292
 
93
-_PREF_BODY_A = (
94
-    "### Prompt\nqA\n### Chosen\ncA\n### Rejected\nrA"
95
-)
96
-_PREF_BODY_B = (
97
-    "### Prompt\nqB\n### Chosen\ncB\n### Rejected\nrB"
98
-)
93
+_PREF_BODY_A = "### Prompt\nqA\n### Chosen\ncA\n### Rejected\nrA"
94
+_PREF_BODY_B = "### Prompt\nqB\n### Chosen\ncB\n### Rejected\nrB"
9995
 
10096
 
10197
 class TestSamplePreferenceRows:
10298
     def test_empty_corpus_returns_empty(self, tmp_path: Path) -> None:
10399
         s = _store(tmp_path)
104
-        rows = s.sample_preference_rows(
105
-            k=5, now=datetime(2026, 4, 1), rng=random.Random(0)
106
-        )
100
+        rows = s.sample_preference_rows(k=5, now=datetime(2026, 4, 1), rng=random.Random(0))
107101
         assert rows == []
108102
 
109103
     def test_corpus_with_no_preferences_returns_empty(self, tmp_path: Path) -> None:
110104
         s = _store(tmp_path)
111105
         s.append(_snap("a" * 16, "prose", "hello", added=datetime(2026, 1, 1)))
112106
         s.append(_snap("b" * 16, "instruction", "### Q\nq\n### A\na", added=datetime(2026, 1, 1)))
113
-        rows = s.sample_preference_rows(
114
-            k=2, now=datetime(2026, 4, 1), rng=random.Random(0)
115
-        )
107
+        rows = s.sample_preference_rows(k=2, now=datetime(2026, 4, 1), rng=random.Random(0))
116108
         assert rows == []
117109
 
118110
     def test_filters_to_preferences_only(self, tmp_path: Path) -> None:
@@ -120,9 +112,7 @@ class TestSamplePreferenceRows:
120112
         s.append(_snap("a" * 16, "prose", "prose body", added=datetime(2026, 1, 1)))
121113
         s.append(_snap("b" * 16, "preference", _PREF_BODY_A, added=datetime(2026, 1, 1)))
122114
         s.append(_snap("c" * 16, "preference", _PREF_BODY_B, added=datetime(2026, 1, 2)))
123
-        rows = s.sample_preference_rows(
124
-            k=10, now=datetime(2026, 4, 1), rng=random.Random(0)
125
-        )
115
+        rows = s.sample_preference_rows(k=10, now=datetime(2026, 4, 1), rng=random.Random(0))
126116
         assert len(rows) == 2
127117
         assert {r["prompt"] for r in rows} == {"qA", "qB"}
128118
         assert all("chosen" in r and "rejected" in r for r in rows)
@@ -133,15 +123,11 @@ class TestSamplePreferenceRows:
133123
             sid = f"{i:016x}"
134124
             body = f"### Prompt\nq{i}\n### Chosen\nc{i}\n### Rejected\nr{i}"
135125
             s.append(_snap(sid, "preference", body, added=datetime(2026, 1, 1)))
136
-        rows = s.sample_preference_rows(
137
-            k=2, now=datetime(2026, 4, 1), rng=random.Random(0)
138
-        )
126
+        rows = s.sample_preference_rows(k=2, now=datetime(2026, 4, 1), rng=random.Random(0))
139127
         assert len(rows) == 2
140128
 
141129
     def test_replay_sid_prefix_applied(self, tmp_path: Path) -> None:
142130
         s = _store(tmp_path)
143131
         s.append(_snap("a" * 16, "preference", _PREF_BODY_A, added=datetime(2026, 1, 1)))
144
-        rows = s.sample_preference_rows(
145
-            k=1, now=datetime(2026, 4, 1), rng=random.Random(0)
146
-        )
132
+        rows = s.sample_preference_rows(k=1, now=datetime(2026, 4, 1), rng=random.Random(0))
147133
         assert rows[0]["_dlm_section_id"].startswith("replay:")
tests/unit/share/test_peer_tokens.pymodified
@@ -71,9 +71,7 @@ class TestBindResolution:
7171
         assert "refusing" in messages.lower()
7272
 
7373
     def test_public_with_ack_binds_all(self) -> None:
74
-        bind = resolve_bind(
75
-            ServeOptions(public=True, i_know_this_is_public=True)
76
-        )
74
+        bind = resolve_bind(ServeOptions(public=True, i_know_this_is_public=True))
7775
         assert bind == "0.0.0.0"
7876
 
7977
 
tests/unit/store/test_inspect_named_adapters.pymodified
@@ -72,9 +72,7 @@ class TestMultiAdapterDiscovery:
7272
 
7373
         inspection = inspect_store(store)
7474
         assert inspection.named_adapters == [
75
-            NamedAdapterState(
76
-                name="knowledge", has_current=False, latest_version=1
77
-            )
75
+            NamedAdapterState(name="knowledge", has_current=False, latest_version=1)
7876
         ]
7977
 
8078
     def test_empty_adapter_dir_without_versions_skipped(self, tmp_path: Path) -> None:
tests/unit/store/test_paths_named_adapters.pymodified
@@ -26,17 +26,11 @@ class TestNamedAdapterPaths:
2626
 
2727
     def test_adapter_version_for_name_pads_four_digits(self, tmp_path: Path) -> None:
2828
         s = _store(tmp_path)
29
-        assert (
30
-            s.adapter_version_for("tone", 7)
31
-            == s.adapter / "tone" / "versions" / "v0007"
32
-        )
29
+        assert s.adapter_version_for("tone", 7) == s.adapter / "tone" / "versions" / "v0007"
3330
 
3431
     def test_pointer_path_for_name(self, tmp_path: Path) -> None:
3532
         s = _store(tmp_path)
36
-        assert (
37
-            s.adapter_current_pointer_for("knowledge")
38
-            == s.adapter / "knowledge" / "current.txt"
39
-        )
33
+        assert s.adapter_current_pointer_for("knowledge") == s.adapter / "knowledge" / "current.txt"
4034
 
4135
 
4236
 class TestNamedAdapterValidation:
tests/unit/templates/test_registry.pymodified
@@ -25,8 +25,7 @@ def test_bundled_templates_dir_exists() -> None:
2525
 def test_list_bundled_returns_eight_templates() -> None:
2626
     templates = list_bundled()
2727
     assert len(templates) >= 8, (
28
-        f"expected at least 8 templates, got {len(templates)}: "
29
-        f"{[t.name for t in templates]}"
28
+        f"expected at least 8 templates, got {len(templates)}: {[t.name for t in templates]}"
3029
     )
3130
     names = {t.name for t in templates}
3231
     required = {
@@ -69,17 +68,13 @@ def test_registry_drops_template_missing_sidecar(tmp_path: Path) -> None:
6968
 
7069
 
7170
 def test_registry_drops_template_with_malformed_meta(tmp_path: Path) -> None:
72
-    (tmp_path / "broken.dlm").write_text(
73
-        "---\ndlm_id: 01AAAA\nbase_model: foo\n---\n# body\n"
74
-    )
71
+    (tmp_path / "broken.dlm").write_text("---\ndlm_id: 01AAAA\nbase_model: foo\n---\n# body\n")
7572
     (tmp_path / "broken.meta.yaml").write_text("not: a: valid: yaml: mapping\n")
7673
     assert list_bundled(gallery_dir=tmp_path) == []
7774
 
7875
 
7976
 def test_load_template_with_mismatched_name_raises(tmp_path: Path) -> None:
80
-    (tmp_path / "fine.dlm").write_text(
81
-        "---\ndlm_id: 01AAAA\nbase_model: foo\n---\n# body\n"
82
-    )
77
+    (tmp_path / "fine.dlm").write_text("---\ndlm_id: 01AAAA\nbase_model: foo\n---\n# body\n")
8378
     # meta.name doesn't match the filename stem.
8479
     (tmp_path / "fine.meta.yaml").write_text(
8580
         "name: different\ntitle: X\nrecommended_base: qwen2.5-1.5b\nsummary: hi\n"
tests/unit/test_templates_parse.pymodified
@@ -23,8 +23,7 @@ def test_templates_dir_is_populated() -> None:
2323
     # Guard against a silent deletion of the bundled gallery.
2424
     paths = _template_paths()
2525
     assert len(paths) >= 8, (
26
-        f"expected at least 8 gallery templates under {bundled_templates_dir()}, "
27
-        f"got {len(paths)}"
26
+        f"expected at least 8 gallery templates under {bundled_templates_dir()}, got {len(paths)}"
2827
     )
2928
 
3029
 
tests/unit/train/cpt/test_embed_warmup.pymodified
@@ -23,9 +23,7 @@ class _FakeParam:
2323
         self.requires_grad = requires_grad
2424
 
2525
 
26
-def _model(
27
-    *, embed_frozen: bool = True, head_frozen: bool = True, tied: bool = False
28
-) -> Any:
26
+def _model(*, embed_frozen: bool = True, head_frozen: bool = True, tied: bool = False) -> Any:
2927
     embed_param = _FakeParam(requires_grad=not embed_frozen)
3028
     head_param = embed_param if tied else _FakeParam(requires_grad=not head_frozen)
3129
     embed_module = SimpleNamespace(weight=embed_param)
@@ -77,9 +75,9 @@ class TestExtendModulesToSave:
7775
         assert extend_modules_to_save_for_embed_warmup(None, embed_warmup_steps=0) is None
7876
 
7977
     def test_zero_warmup_passes_through_list(self) -> None:
80
-        assert extend_modules_to_save_for_embed_warmup(
81
-            ["embed_tokens"], embed_warmup_steps=0
82
-        ) == ["embed_tokens"]
78
+        assert extend_modules_to_save_for_embed_warmup(["embed_tokens"], embed_warmup_steps=0) == [
79
+            "embed_tokens"
80
+        ]
8381
 
8482
     def test_warmup_on_with_no_existing(self) -> None:
8583
         out = extend_modules_to_save_for_embed_warmup(None, embed_warmup_steps=50)
tests/unit/train/cpt/test_schedule.pymodified
@@ -19,29 +19,20 @@ class TestWarmupRamp:
1919
         assert cosine_with_floor_lr(0, total_steps=100, warmup_steps=20) == 0.0
2020
 
2121
     def test_half_warmup_is_half(self) -> None:
22
-        assert cosine_with_floor_lr(
23
-            10, total_steps=100, warmup_steps=20
24
-        ) == pytest.approx(0.5)
22
+        assert cosine_with_floor_lr(10, total_steps=100, warmup_steps=20) == pytest.approx(0.5)
2523
 
2624
     def test_warmup_end_is_peak(self) -> None:
2725
         # step == warmup_steps: first step of decay phase; cosine is 1.0
2826
         # at decay_progress=0, so we're at peak.
29
-        assert cosine_with_floor_lr(
30
-            20, total_steps=100, warmup_steps=20
31
-        ) == pytest.approx(1.0)
27
+        assert cosine_with_floor_lr(20, total_steps=100, warmup_steps=20) == pytest.approx(1.0)
3228
 
3329
     def test_zero_warmup_jumps_to_peak(self) -> None:
34
-        assert cosine_with_floor_lr(
35
-            0, total_steps=100, warmup_steps=0
36
-        ) == pytest.approx(1.0)
30
+        assert cosine_with_floor_lr(0, total_steps=100, warmup_steps=0) == pytest.approx(1.0)
3731
 
3832
 
3933
 class TestCosineDecay:
4034
     def test_monotone_decrease_through_decay(self) -> None:
41
-        lrs = [
42
-            cosine_with_floor_lr(s, total_steps=100, warmup_steps=20)
43
-            for s in range(20, 100, 5)
44
-        ]
35
+        lrs = [cosine_with_floor_lr(s, total_steps=100, warmup_steps=20) for s in range(20, 100, 5)]
4536
         for a, b in zip(lrs, lrs[1:], strict=False):
4637
             assert a > b
4738
 
@@ -66,9 +57,7 @@ class TestCosineDecay:
6657
         # Midpoint of cosine decay (decay_progress=0.5) gives cos(pi/2)=0,
6758
         # so cosine multiplier = 0.5 → LR = floor + (1-floor)*0.5
6859
         floor = 0.1
69
-        mid = cosine_with_floor_lr(
70
-            60, total_steps=100, warmup_steps=20, floor_ratio=floor
71
-        )
60
+        mid = cosine_with_floor_lr(60, total_steps=100, warmup_steps=20, floor_ratio=floor)
7261
         expected = floor + (1.0 - floor) * 0.5
7362
         assert mid == pytest.approx(expected)
7463
 
@@ -97,9 +86,7 @@ class TestInputValidation:
9786
     @pytest.mark.parametrize("bad", [-0.01, 1.01, 2.0])
9887
     def test_floor_ratio_out_of_range(self, bad: float) -> None:
9988
         with pytest.raises(ValueError, match="floor_ratio must be in"):
100
-            cosine_with_floor_lr(
101
-                0, total_steps=100, warmup_steps=10, floor_ratio=bad
102
-            )
89
+            cosine_with_floor_lr(0, total_steps=100, warmup_steps=10, floor_ratio=bad)
10390
 
10491
 
10592
 class TestDefaultConstants:
@@ -130,11 +117,7 @@ class TestContinuityAcrossWarmup:
130117
         # At warmup_steps, cosine is exactly 1. They should differ by
131118
         # ~1/warmup_steps (the ramp's last sub-peak increment).
132119
         warmup = 50
133
-        last_ramp = cosine_with_floor_lr(
134
-            warmup - 1, total_steps=200, warmup_steps=warmup
135
-        )
136
-        first_decay = cosine_with_floor_lr(
137
-            warmup, total_steps=200, warmup_steps=warmup
138
-        )
120
+        last_ramp = cosine_with_floor_lr(warmup - 1, total_steps=200, warmup_steps=warmup)
121
+        first_decay = cosine_with_floor_lr(warmup, total_steps=200, warmup_steps=warmup)
139122
         assert first_decay == pytest.approx(1.0)
140123
         assert math.isclose(first_decay - last_ramp, 1 / warmup, abs_tol=1e-9)
tests/unit/train/cpt/test_vocab_gap.pymodified
@@ -17,9 +17,7 @@ from dlm.train.cpt.vocab_gap import (
1717
 
1818
 class TestComputeVocabGap:
1919
     def test_empty_inputs(self) -> None:
20
-        r = compute_vocab_gap(
21
-            [], text="", unk_token_id=None, decoded_tokens=[]
22
-        )
20
+        r = compute_vocab_gap([], text="", unk_token_id=None, decoded_tokens=[])
2321
         assert r.total_tokens == 0
2422
         assert r.total_words == 0
2523
         assert r.tokens_per_word == 0.0
@@ -113,9 +111,7 @@ class TestComputeVocabGapValidation:
113111
 
114112
     def test_negative_top_n_rejected(self) -> None:
115113
         with pytest.raises(ValueError, match="top_n must be non-negative"):
116
-            compute_vocab_gap(
117
-                [], text="", unk_token_id=None, decoded_tokens=[], top_n=-1
118
-            )
114
+            compute_vocab_gap([], text="", unk_token_id=None, decoded_tokens=[], top_n=-1)
119115
 
120116
 
121117
 class TestRenderReport:
tests/unit/train/distributed/test_rank_env.pymodified
@@ -40,9 +40,7 @@ class TestDetectRank:
4040
         monkeypatch.delenv("LOCAL_RANK", raising=False)
4141
         assert detect_rank() == 0
4242
 
43
-    def test_rank_takes_precedence_over_local_rank(
44
-        self, monkeypatch: pytest.MonkeyPatch
45
-    ) -> None:
43
+    def test_rank_takes_precedence_over_local_rank(self, monkeypatch: pytest.MonkeyPatch) -> None:
4644
         monkeypatch.setenv("RANK", "3")
4745
         monkeypatch.setenv("LOCAL_RANK", "1")
4846
         assert detect_rank() == 3
tests/unit/train/multi_adapter/test_orchestrator.pymodified
@@ -92,18 +92,14 @@ def _single_adapter_parsed(dlm_id: str) -> ParsedDlm:
9292
             base_model="smollm2-135m",
9393
             training=TrainingConfig(seed=42),
9494
         ),
95
-        sections=(
96
-            Section(type=SectionType.PROSE, content="Single-adapter prose."),
97
-        ),
95
+        sections=(Section(type=SectionType.PROSE, content="Single-adapter prose."),),
9896
     )
9997
 
10098
 
10199
 def _seed_store(tmp_path: Path, dlm_id: str) -> Any:
102100
     store = for_dlm(dlm_id, home=tmp_path)
103101
     store.ensure_layout()
104
-    save_manifest(
105
-        store.manifest, Manifest(dlm_id=dlm_id, base_model="smollm2-135m")
106
-    )
102
+    save_manifest(store.manifest, Manifest(dlm_id=dlm_id, base_model="smollm2-135m"))
107103
     return store
108104
 
109105
 
@@ -220,9 +216,7 @@ class TestMultiAdapterOrchestration:
220216
         # Flat field stays at 0 (untouched) for multi-adapter stores.
221217
         assert manifest.adapter_version == 0
222218
 
223
-    def test_training_run_summaries_carry_adapter_name(
224
-        self, tmp_path: Path
225
-    ) -> None:
219
+    def test_training_run_summaries_carry_adapter_name(self, tmp_path: Path) -> None:
226220
         """Audit-07 M1: each TrainingRunSummary is tagged with the name."""
227221
         dlm_id = "01HZ4X7TGZM3J1A2B3C4D5E6FB"
228222
         store = _seed_store(tmp_path, dlm_id)
tests/unit/train/multi_adapter/test_router.pymodified
@@ -60,9 +60,7 @@ class TestProseFansOut:
6060
         prose_in_knowledge = [
6161
             s for s in plan.by_adapter["knowledge"] if s.type is SectionType.PROSE
6262
         ]
63
-        prose_in_tone = [
64
-            s for s in plan.by_adapter["tone"] if s.type is SectionType.PROSE
65
-        ]
63
+        prose_in_tone = [s for s in plan.by_adapter["tone"] if s.type is SectionType.PROSE]
6664
         assert len(prose_in_knowledge) == 1
6765
         assert len(prose_in_tone) == 1
6866
 
@@ -80,38 +78,23 @@ class TestInstructionRouting:
8078
         parsed = parse_text(_doc(body, multi_adapter=True))
8179
         plan = build_plan(parsed)
8280
         # First-declared is "knowledge".
83
-        assert any(
84
-            s.type is SectionType.INSTRUCTION
85
-            for s in plan.by_adapter["knowledge"]
86
-        )
87
-        assert not any(
88
-            s.type is SectionType.INSTRUCTION for s in plan.by_adapter["tone"]
89
-        )
81
+        assert any(s.type is SectionType.INSTRUCTION for s in plan.by_adapter["knowledge"])
82
+        assert not any(s.type is SectionType.INSTRUCTION for s in plan.by_adapter["tone"])
9083
 
9184
     def test_tagged_instruction_goes_to_named_adapter(self) -> None:
9285
         body = "::instruction#tone::\n### Q\nhi\n### A\nbye\n"
9386
         parsed = parse_text(_doc(body, multi_adapter=True))
9487
         plan = build_plan(parsed)
95
-        assert not any(
96
-            s.type is SectionType.INSTRUCTION
97
-            for s in plan.by_adapter["knowledge"]
98
-        )
99
-        assert any(
100
-            s.type is SectionType.INSTRUCTION for s in plan.by_adapter["tone"]
101
-        )
88
+        assert not any(s.type is SectionType.INSTRUCTION for s in plan.by_adapter["knowledge"])
89
+        assert any(s.type is SectionType.INSTRUCTION for s in plan.by_adapter["tone"])
10290
 
10391
 
10492
 class TestPreferenceRouting:
10593
     def test_tagged_preference_goes_to_named_adapter(self) -> None:
106
-        body = (
107
-            "::preference#tone::\n"
108
-            "### Prompt\nq\n### Chosen\nc\n### Rejected\nr\n"
109
-        )
94
+        body = "::preference#tone::\n### Prompt\nq\n### Chosen\nc\n### Rejected\nr\n"
11095
         parsed = parse_text(_doc(body, multi_adapter=True))
11196
         plan = build_plan(parsed)
112
-        assert any(
113
-            s.type is SectionType.PREFERENCE for s in plan.by_adapter["tone"]
114
-        )
97
+        assert any(s.type is SectionType.PREFERENCE for s in plan.by_adapter["tone"])
11598
 
11699
 
117100
 class TestUnknownAdapter:
@@ -129,10 +112,7 @@ class TestUnknownAdapter:
129112
 
130113
 class TestSingleAdapterDoc:
131114
     def test_single_adapter_doc_routes_all_to_default(self) -> None:
132
-        body = (
133
-            "# Prose\n\nShared.\n\n"
134
-            "::instruction::\n### Q\nh\n### A\nb\n"
135
-        )
115
+        body = "# Prose\n\nShared.\n\n::instruction::\n### Q\nh\n### A\nb\n"
136116
         parsed = parse_text(_doc(body, multi_adapter=False))
137117
         plan = build_plan(parsed)
138118
         assert set(plan.by_adapter) == {"default"}
@@ -149,10 +129,7 @@ class TestSingleAdapterDoc:
149129
 
150130
 class TestSectionsForShortcut:
151131
     def test_returns_same_as_plan_entry(self) -> None:
152
-        body = (
153
-            "shared prose\n\n"
154
-            "::instruction#tone::\n### Q\nh\n### A\nb\n"
155
-        )
132
+        body = "shared prose\n\n::instruction#tone::\n### Q\nh\n### A\nb\n"
156133
         parsed = parse_text(_doc(body, multi_adapter=True))
157134
         plan = build_plan(parsed)
158135
         assert sections_for(parsed, "tone") == plan.by_adapter["tone"]
tests/unit/train/preference/test_determinism_plumbing.pymodified
@@ -90,9 +90,7 @@ def _seed_store(tmp_path: Path, dlm_id: str) -> Any:
9090
 
9191
 
9292
 class TestDpoSeedsRngBeforeTraining:
93
-    def test_explicit_seed_flows_through_to_seed_everything(
94
-        self, tmp_path: Path
95
-    ) -> None:
93
+    def test_explicit_seed_flows_through_to_seed_everything(self, tmp_path: Path) -> None:
9694
         from dlm.train.preference.dpo_phase import run
9795
 
9896
         store = _seed_store(tmp_path, "01KDPOSEED" + "0" * 16)
@@ -100,9 +98,7 @@ class TestDpoSeedsRngBeforeTraining:
10098
 
10199
         with patch(
102100
             "dlm.train.preference.dpo_phase.seed_everything",
103
-            wraps=__import__(
104
-                "dlm.train.determinism", fromlist=["seed_everything"]
105
-            ).seed_everything,
101
+            wraps=__import__("dlm.train.determinism", fromlist=["seed_everything"]).seed_everything,
106102
         ) as spy:
107103
             run(
108104
                 store,
@@ -123,9 +119,7 @@ class TestDpoSeedsRngBeforeTraining:
123119
 
124120
         with patch(
125121
             "dlm.train.preference.dpo_phase.seed_everything",
126
-            wraps=__import__(
127
-                "dlm.train.determinism", fromlist=["seed_everything"]
128
-            ).seed_everything,
122
+            wraps=__import__("dlm.train.determinism", fromlist=["seed_everything"]).seed_everything,
129123
         ) as spy:
130124
             run(
131125
                 store,
@@ -148,9 +142,7 @@ class TestOrpoSeedsRngBeforeTraining:
148142
 
149143
         with patch(
150144
             "dlm.train.preference.orpo_phase.seed_everything",
151
-            wraps=__import__(
152
-                "dlm.train.determinism", fromlist=["seed_everything"]
153
-            ).seed_everything,
145
+            wraps=__import__("dlm.train.determinism", fromlist=["seed_everything"]).seed_everything,
154146
         ) as spy:
155147
             run(
156148
                 store,
tests/unit/train/preference/test_dpo_dataset.pymodified
@@ -12,9 +12,7 @@ from dlm.train.preference.dpo_dataset import (
1212
 )
1313
 
1414
 _PREF_BODY_ONE = (
15
-    "### Prompt\nWhat time is it?\n"
16
-    "### Chosen\nIt is 3 PM.\n"
17
-    "### Rejected\nTime is an illusion.\n"
15
+    "### Prompt\nWhat time is it?\n### Chosen\nIt is 3 PM.\n### Rejected\nTime is an illusion.\n"
1816
 )
1917
 
2018
 _PREF_BODY_TWO = (
tests/unit/train/preference/test_dpo_phase.pymodified
@@ -23,20 +23,14 @@ from dlm.train.state_sidecar import STATE_FILENAME, STATE_SHA_FILENAME
2323
 
2424
 
2525
 def _parsed_with_preferences() -> ParsedDlm:
26
-    pref_body = (
27
-        "### Prompt\nq?\n### Chosen\nc.\n### Rejected\nr.\n"
28
-    )
26
+    pref_body = "### Prompt\nq?\n### Chosen\nc.\n### Rejected\nr.\n"
2927
     return ParsedDlm(
3028
         frontmatter=DlmFrontmatter(
3129
             dlm_id="01KABCD" + "0" * 19,
3230
             base_model="smollm2-135m",
33
-            training=TrainingConfig(
34
-                seed=42, preference=PreferenceConfig(enabled=True)
35
-            ),
36
-        ),
37
-        sections=(
38
-            Section(type=SectionType.PREFERENCE, content=pref_body),
31
+            training=TrainingConfig(seed=42, preference=PreferenceConfig(enabled=True)),
3932
         ),
33
+        sections=(Section(type=SectionType.PREFERENCE, content=pref_body),),
4034
     )
4135
 
4236
 
tests/unit/train/preference/test_dpo_trainer.pymodified
@@ -42,13 +42,9 @@ class TestCoreFields:
4242
         cfg = PreferenceConfig(
4343
             enabled=True,
4444
             loss_type="ipo",
45
-            hyperparams=PreferenceHyperparams(
46
-                beta=0.2, learning_rate=3e-6, num_epochs=2
47
-            ),
48
-        )
49
-        kwargs = build_dpo_config_kwargs(
50
-            cfg, _plan(), output_dir=tmp_path, max_length=1024, seed=7
45
+            hyperparams=PreferenceHyperparams(beta=0.2, learning_rate=3e-6, num_epochs=2),
5146
         )
47
+        kwargs = build_dpo_config_kwargs(cfg, _plan(), output_dir=tmp_path, max_length=1024, seed=7)
5248
         assert kwargs["output_dir"] == str(tmp_path)
5349
         assert kwargs["learning_rate"] == 3e-6
5450
         assert kwargs["num_train_epochs"] == 2
tests/unit/train/preference/test_method_registry.pymodified
@@ -46,6 +46,7 @@ class TestRegisterCanReplace:
4646
     def test_register_overrides_existing(self) -> None:
4747
         saved = resolve("dpo")
4848
         try:
49
+
4950
             def _stub(*args: object, **kwargs: object) -> str:  # type: ignore[return-value]
5051
                 return "stub"
5152
 
tests/unit/train/preference/test_orpo_phase.pymodified
@@ -34,9 +34,7 @@ def _parsed_with_preferences() -> ParsedDlm:
3434
                 preference=PreferenceConfig(enabled=True, method="orpo"),
3535
             ),
3636
         ),
37
-        sections=(
38
-            Section(type=SectionType.PREFERENCE, content=pref_body),
39
-        ),
37
+        sections=(Section(type=SectionType.PREFERENCE, content=pref_body),),
4038
     )
4139
 
4240
 
@@ -85,9 +83,7 @@ def _seed_prior_sft(store, dlm_id: str = "01ORPOTEST") -> None: # type: ignore[
8583
     store.ensure_layout()
8684
     save_manifest(
8785
         store.manifest,
88
-        Manifest(
89
-            dlm_id=dlm_id, base_model="smollm2-135m", adapter_version=1
90
-        ),
86
+        Manifest(dlm_id=dlm_id, base_model="smollm2-135m", adapter_version=1),
9187
     )
9288
     v0001 = store.adapter_version(1)
9389
     v0001.mkdir(parents=True, exist_ok=True)
@@ -172,9 +168,7 @@ class TestRunHappyPath:
172168
 
173169
 
174170
 class TestRunSteps:
175
-    def test_factory_receives_reference_adapter_version(
176
-        self, tmp_path: Path
177
-    ) -> None:
171
+    def test_factory_receives_reference_adapter_version(self, tmp_path: Path) -> None:
178172
         captured: dict[str, Any] = {}
179173
 
180174
         def _capturing_factory(**kwargs: Any) -> MagicMock:
tests/unit/train/preference/test_orpo_trainer.pymodified
@@ -36,9 +36,7 @@ class TestCoreMapping:
3636
         cfg = PreferenceConfig(
3737
             enabled=True,
3838
             method="orpo",
39
-            hyperparams=PreferenceHyperparams(
40
-                alpha=0.15, learning_rate=3e-6, num_epochs=2
41
-            ),
39
+            hyperparams=PreferenceHyperparams(alpha=0.15, learning_rate=3e-6, num_epochs=2),
4240
         )
4341
         kwargs = build_orpo_config_kwargs(
4442
             cfg, _plan(), output_dir=tmp_path, max_length=1024, seed=7
tests/unit/train/preference/test_phase_orchestrator.pymodified
@@ -45,9 +45,7 @@ def _instruction() -> Section:
4545
 def _pref() -> Section:
4646
     return Section(
4747
         type=SectionType.PREFERENCE,
48
-        content=(
49
-            "### Prompt\nq\n### Chosen\nc\n### Rejected\nr\n"
50
-        ),
48
+        content=("### Prompt\nq\n### Chosen\nc\n### Rejected\nr\n"),
5149
         start_line=1,
5250
     )
5351
 
@@ -88,10 +86,7 @@ def _parsed(
8886
     who wrote `training.preference.enabled: true/false` in their
8987
     frontmatter.
9088
     """
91
-    pref = (
92
-        PreferenceConfig() if dpo_enabled is None
93
-        else PreferenceConfig(enabled=dpo_enabled)
94
-    )
89
+    pref = PreferenceConfig() if dpo_enabled is None else PreferenceConfig(enabled=dpo_enabled)
9590
     return _FakeParsed(
9691
         sections=tuple(sections),
9792
         frontmatter=_FakeFrontmatter(training=_FakeTraining(preference=pref)),
tests/unit/train/test_resolve_adapter_hparams.pymodified
@@ -23,9 +23,7 @@ def _parsed(training: TrainingConfig) -> ParsedDlm:
2323
 
2424
 class TestFlatConfig:
2525
     def test_returns_flat_fields_when_adapter_name_is_none(self) -> None:
26
-        training = TrainingConfig(
27
-            lora_r=16, lora_alpha=32, lora_dropout=0.1, learning_rate=1e-3
28
-        )
26
+        training = TrainingConfig(lora_r=16, lora_alpha=32, lora_dropout=0.1, learning_rate=1e-3)
2927
         r, alpha, dropout, lr = _resolve_adapter_hparams(_parsed(training), None)
3028
         assert (r, alpha, dropout) == (16, 32, pytest.approx(0.1))
3129
         assert lr == pytest.approx(1e-3)
@@ -52,32 +50,22 @@ class TestMultiAdapterConfig:
5250
                 }
5351
             }
5452
         )
55
-        k_r, k_alpha, _k_drop, _k_lr = _resolve_adapter_hparams(
56
-            _parsed(training), "knowledge"
57
-        )
58
-        t_r, t_alpha, t_drop, t_lr = _resolve_adapter_hparams(
59
-            _parsed(training), "tone"
60
-        )
53
+        k_r, k_alpha, _k_drop, _k_lr = _resolve_adapter_hparams(_parsed(training), "knowledge")
54
+        t_r, t_alpha, t_drop, t_lr = _resolve_adapter_hparams(_parsed(training), "tone")
6155
         assert (k_r, k_alpha) == (8, 16)
6256
         assert (t_r, t_alpha) == (4, 8)
6357
         assert t_drop == pytest.approx(0.2)
6458
         assert t_lr == pytest.approx(1e-4)
6559
 
6660
     def test_unknown_adapter_name_falls_back_to_flat(self) -> None:
67
-        training = TrainingConfig.model_validate(
68
-            {"adapters": {"knowledge": {"lora_r": 8}}}
69
-        )
61
+        training = TrainingConfig.model_validate({"adapters": {"knowledge": {"lora_r": 8}}})
7062
         # ghost isn't declared; we fall back to defaults rather than crash.
7163
         r, _, _, _ = _resolve_adapter_hparams(_parsed(training), "ghost")
7264
         assert r == 8  # flat default
7365
 
7466
     def test_per_adapter_defaults_when_not_overridden(self) -> None:
75
-        training = TrainingConfig.model_validate(
76
-            {"adapters": {"default_one": {}}}
77
-        )
78
-        r, alpha, dropout, lr = _resolve_adapter_hparams(
79
-            _parsed(training), "default_one"
80
-        )
67
+        training = TrainingConfig.model_validate({"adapters": {"default_one": {}}})
68
+        r, alpha, dropout, lr = _resolve_adapter_hparams(_parsed(training), "default_one")
8169
         # AdapterConfig() defaults: r=8, alpha=16, dropout=0.05, lr=2e-4
8270
         assert (r, alpha) == (8, 16)
8371
         assert dropout == pytest.approx(0.05)
tests/unit/watch/test_status.pymodified
@@ -16,23 +16,17 @@ class TestRenderStatus:
1616
 
1717
     def test_after_cycle_shows_loss_and_steps(self) -> None:
1818
         status = WatchStatus(doc_path="mydoc.dlm", sections=12)
19
-        status.mark_cycle_done(
20
-            train_loss=1.2, val_loss=1.35, steps=50, coalesced=1
21
-        )
19
+        status.mark_cycle_done(train_loss=1.2, val_loss=1.35, steps=50, coalesced=1)
2220
         line = render_status(status)
2321
         assert "val loss: 1.35" in line
2422
         assert "steps: 50" in line
2523
 
2624
     def test_coalesced_only_shown_when_plural(self) -> None:
2725
         status = WatchStatus(doc_path="d")
28
-        status.mark_cycle_done(
29
-            train_loss=None, val_loss=None, steps=10, coalesced=1
30
-        )
26
+        status.mark_cycle_done(train_loss=None, val_loss=None, steps=10, coalesced=1)
3127
         assert "coalesced" not in render_status(status)
3228
 
33
-        status.mark_cycle_done(
34
-            train_loss=None, val_loss=None, steps=10, coalesced=5
35
-        )
29
+        status.mark_cycle_done(train_loss=None, val_loss=None, steps=10, coalesced=5)
3630
         assert "coalesced: 5" in render_status(status)
3731
 
3832
     def test_age_buckets(self) -> None: