Skip to content

Run the recipe on macOS, and cache a voice reference's prefill on Metal - #17

Closed
BobClawblaw wants to merge 1 commit into
plotarmordev:mainfrom
BobClawblaw:macos-and-reference-prefill-cache
Closed

BobClawblaw wants to merge 1 commit into
plotarmordev:mainfrom
BobClawblaw:macos-and-reference-prefill-cache

Conversation

@BobClawblaw

@BobClawblaw BobClawblaw commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Description and motivation

Runs this recipe on macOS and removes the repeated voice-reference prefill from Drama 3 speech. The GB10 path is untouched; scripts/build-engine.sh keeps its previous code on every non-Darwin host.

Contents:

  • scripts/build-engine.sh: on Darwin, omit -Dnvcc and use shasum where sha256sum is absent. -Dnvcc cannot be passed on macOS because the option is declared only inside the CUDA build steps, so the script failed with invalid option: "nvcc" before this change.
  • recipe/pilot_macos.py: the guarded pilot without systemd. It keeps the shared GPU lock, admission check, port check, DRAMA_PILOT_READY and the same evidence files (session.json, ready.json, memory.jsonl, server.log, completion.json); vm_stat replaces /proc/meminfo, process-group signals replace systemd-run, and --host defaults to 0.0.0.0 (--host 127.0.0.1 available). There is no cgroup, so the 54 GiB engine cap has no macOS equivalent; admission is weights + 30 GiB or an explicit --min-available-gib.
  • recipe/README-macos.md: the macOS procedure, the measurements behind it, the voice-cloning steps and service supervision.
  • recipe/build_voice.py: builds a drama3-http-voice/1 catalog from an encoded reference clip and its transcript. It lives in recipe/ because .gitignore excludes voices/ (they hold a person's voice).
  • engine/patches/0012: the Metal host prefills a voice reference once per lane, snapshots the recurrent state and counters, and on a later request with the same reference restores that snapshot and prefills only the per-request rows. It adds reference_rows to SpeechRequest, logs the cache build/hit so the behaviour is observable, and leaves the CUDA path alone. It stacks on 0005 (voice catalogs) and is proposed upstream once 0005 lands.
  • bench/reference_cache_test.py: the deterministic test for 0012.
  • engine/patches/SHA256SUMS regenerated and the patch table extended.

Testing

Host: Mac Studio, Apple M5 Ultra, 256 GiB, macOS 27.0.1, Zig 0.17.0, no CUDA toolkit. Checkpoint fishaudio/drama-3 at e0a9218a; all ten files verified against recipe/checksums/checkpoint.sha256. Engine: d1018b3 + 12 patches; baseline build d1018b3 + 11 patches (no 0012).

  • scripts/build-engine.sh from a clean checkout: applies the whole series and builds tensorfold-native and drama3-generate.
  • zig build test-native on the patched tree: 31 passed, 1 skipped, 0 failed.
  • Deterministic test for 0012, bench/reference_cache_test.py against a freshly started server: {"built": "drama3: reference cache built (222 rows)", "hit": "drama3: reference cache hit (222 rows restored)", "identical": true, "bytes": 385024}. It fails on an engine without the patch, because neither line is ever logged and the second reply would still be a full prefill.
  • Audio-identity gate, two-pass captures of the 24-item corpus against each build (corpus_capture.py ... --passes 2), then compare_gate.py base base new out.json:
    {"identical": true, "normal_mismatches": [], "long05_clipped_identical": [true, true], "base_rtf": 0.977, "new_rtf": 0.683, "speedup_vs_base": 1.43}.
    The clipped directory is the baseline capture itself: long-05 does not reach the frame cap at the default 1024 frames, so its own baseline reply is the reference.
  • bench/stream_check.py against the same server: {"passed": true, ...} with all nine checks true (whole WAV 200, PCM equals WAV data, stream head, stream complete, whole frames, stream equals whole PCM, abandoned stream incomplete, slot free after abandon, repeat whole unchanged).
  • Served over loopback and LAN: GET /health 200; WAV and streamed PCM; X-Finish-Reason stop and length; 400 for response_format: mp3; 503 on capacity; the launcher refuses on an occupied lock, an occupied port and below its admission floor.
  • Content check: whisper-cli (ggml small.en) transcribes replies back to the requested text.
  • Not run: the qualification gates (they need the sglang-omni CUDA reference stack). A2 and the Grill captures were not run because no formal speed claim is made below.

Performance or quality claim

None formal. The numbers above are single-host observations from one A and one B capture, not the recipe's A/B/A2 protocol. On this host the reference prefill was 3.3 s of a 4.7 s first-audio time, and caching it removes that work from every request after the first for a given voice; the corpus gate measured 1.43x on the same replies, byte for byte. The first request after a start, and the first request for a newly selected voice, still pay the full prefill.


Checklist

  • One change per patch, new patches at the end of the series, SHA256SUMS and engine/patches/README.md updated
  • scripts/build-engine.sh applies the whole series and builds from a clean checkout
  • Every behaviour change has a deterministic test that fails without it (bench/reference_cache_test.py; the macOS launcher and build guard are covered by running them, which is how the failure they fix was found)
  • No dead code, debug output or leftovers
  • No personal voices, recordings, private names, host names or private paths in code, fixtures, docs, evidence or commit messages
  • Where audio should not change, compare_gate.py reports "identical": true and stream_check.py passes

Evidence (only with a claim)

n/a: no formal claim. Stated anyway: hardware, OS, Zig and checkpoint revision are above; the two engine HEADs are named; the capture commands were python3 bench/corpus_capture.py http://127.0.0.1:18795 captures/<base|new> --passes 2 against recipe/pilot_macos.py on port 18795 with --voices, --default-voice jones, the silence guard and one redraw.

Adds a macOS path that leaves the GB10 path unchanged, and one engine
patch that removes the repeated reference prefill from Drama 3 speech.

- scripts/build-engine.sh: on Darwin, omit -Dnvcc (the option is only
  declared for the CUDA steps) and use shasum where sha256sum is absent.
  The Linux branch is the previous code.
- recipe/pilot_macos.py: the guarded pilot without systemd. Same shared
  GPU lock, admission check, port check, DRAMA_PILOT_READY and evidence
  files; vm_stat replaces /proc/meminfo and process-group signals replace
  systemd-run. --host defaults to 0.0.0.0, --host 127.0.0.1 available.
- recipe/README-macos.md: the macOS procedure, measurements and the voice
  cloning steps.
- recipe/build_voice.py: builds a drama3-http-voice/1 catalog from an
  encoded reference clip and its transcript.
- engine/patches/0012: the Metal host prefills a voice reference once per
  lane, snapshots the recurrent state and reuses it. Measured 3.59 s to
  1.37 s first audio on a short line and 4.68 s to 2.41 s on a 454
  character paragraph, with byte-identical audio. It stacks on 0005 and is
  proposed upstream once that lands.
- engine/patches/SHA256SUMS and the patch table updated.
@BobClawblaw
BobClawblaw force-pushed the macos-and-reference-prefill-cache branch from ac417dd to e77d80a Compare October 21, 2026 15:25
@jerryfane

Copy link
Copy Markdown
Contributor

Independent verifier: builds and happy path work, but do not merge as-is

I independently checked out and ran e77d80a91e1cdb393238eb059a6d9339eff67bce, without modifying the PR's engine/launcher/test code. This is my own execution evidence, not a restatement of the PR author's results. Verification date: 2026-10-23.

The target is this repository's main. A merge-tree against current main 1209e5fbd6d9cad404643353f53097cd30ef0ca7 is conflict-free (b33678889dc33c546f631771ece4447dec79c367), but textual mergeability is not functional approval. Two real-engine regressions below block approval.

What I actually ran

  • Mac Studio / Apple M5 Ultra / 256 GB; isolated, checksum-verified Zig 0.17.0.
  • Downloaded the exact raw fishaudio/drama-3@e0a9218aa48888270f06ef1ed9ea67622c0e17d2 checkpoint; independently verified all ten files against recipe/checksums/checkpoint.sha256. No substituted MLX/quantized model.
  • Verified all 12 patch checksums. Ran the unmodified scripts/build-engine.sh with JOBS=2: 66/66 build steps succeeded, producing both binaries.
  • Candidate engine: 321fc558b61f3f63a3c72fca5eab16fb9b6364cd (pinned upstream + 12 patches). Native binary SHA-256: 093fd0ebeaf4a4e4b954f8aafcbc6306eef9a0ed8faff184143e31d674df8f0a.
  • Separately built the same pinned engine + patches 0001–0011, 881151c…, as the uncached baseline: 66/66 steps succeeded.
  • Candidate zig build test-native -j2 --summary all: 31 passed, 1 skipped, 0 failed. The final command/build status was successful; the retained output also contains residency-fixture warnings and a failed command: diagnostic, so I am reporting the actual final summary rather than claiming a warning-free run.
  • Ran the actual pilot_macos.py on loopback with normal port binding, one lane, context 8192, no drafts, prompt cache 0, keep-warm 0, --max-frames 512. No guards/redraw tuning, production deployment or service restart.
  • Generated a reference using the baseline's builtin voice, encoded it using the actual codec executable, and created truthful synthetic catalogs. No personal or public-figure recording. Reference A has 100 codec rows; B has the same transcript/codes except one valid residual code in its first row is incremented modulo 1024.
  • Provided reference_cache_test.py: fails on baseline as expected (first request did not build a prefix snapshot); passes on candidate, with built (100 rows), hit (100 rows restored), byte-identical 323,584-byte PCM.
  • Cross-build checks: ordinary repeated reference A, a different text with A, default voice, and B each match the uncached baseline byte-for-byte when not entering the failing transition below.
  • Provided stream_check.py: all nine checks pass on the candidate's builtin/default voice, including whole WAV/PCM identity, streamed identity, abandonment and slot recovery. This script does not select a catalog voice, so this is not claimed as cached-reference stream coverage.

Blocking finding 1: A → default → A changes the audio

With the same text and unchanged request settings, issue PCM requests in order:

voice=synthetic-a
voice=default
voice=synthetic-a

Text:

The train leaves at seven fifteen, and this is the voice you came for.

Engine / sample PCM bytes PCM SHA-256
Baseline A, before and after default 323584 78888f5b1e001ab82317c7bbe32dac536259f42a3f1f5d46e02018577d5ac8da
Candidate A, before default 323584 78888f5b1e001ab82317c7bbe32dac536259f42a3f1f5d46e02018577d5ac8da
Candidate A, after default 352256 b8451e07cd593bfd03307128c03c5c7aeb20993922dd662b864e91a663c6461d

All these responses were HTTP 200 with X-Finish-Reason: stop; this is not a clipped-output or HTTP-failure comparison. The candidate subsequently returns to the original correct A hash after B forces a rebuild and A rebuilds again.

Source explanation: 0012's hit/miss branch preserves lane.cache through an uncached/default prompt. The snapshot copies recurrent buffers/counters, not the attention KV prefix. Default prefill overwrites live KV rows, so the next A hit restores only part of A's state.

Needed before merge: invalidate the cached snapshot whenever an uncached/different-prefix prefill can overwrite its dependent live state, including interruption/error paths, or snapshot/restore all required state. Add baseline-parity regressions for A→default→A and prefill cancellation/voice transitions. The existing same-voice/same-text test demonstrably passes despite this defect.

Blocking finding 2: voice switches grow retained allocation rather than reaching a plateau

In the candidate, every A/B switch rebuilt a snapshot and added 62,880 KiB = 61.40625 MiB to observed process RSS. Eight consecutive switches added 491.25 MiB. The baseline stayed flat across all six corresponding ordinary requests.

Candidate observation RSS, KiB
Before the first B rebuild 15293872
After B 15356752
After A 15419632
After six additional B/A alternations 15796912

Each of the eight adjacent deltas was exactly 62,880 KiB. These are process RSS observations, not direct Metal allocation telemetry.

Source ownership confirms the problem: snapshot() allocates fresh conv/gdn buffers, then lane.cache = try s.e.snapshot() loses the previous snapshot handles without releasing/reusing their owned buffers. The GPU owner retains them until engine close.

Needed before merge: reuse one snapshot buffer pair per lane or implement correct replacement ownership, with an alternating-voice allocation-plateau regression. Simply dropping the struct handles is not enough; a global allocator-tail release also needs care when lanes interleave allocations.

Launcher/helper findings reproduced separately without models

These used the actual Python CLI with a harmless, bounded subprocess fixture and private temporary files—not production services. They are separate from the successful real native execution above.

  1. Memory admission/watchdog double-counts speculative pages. memory_available() adds both free and speculative. XNU's contract explicitly says speculative pages are already included in free_count. With a controlled fixture containing 100 GiB free, all of it speculative, and zero other selected categories, the function reports 200 GiB. This inflates both admission and the abort check. I make no unverified claim here about whether the purgeable category overlaps.
  2. Group cleanup can miss a surviving descendant. kill_tree() does nothing once the leader has exited. A harmless leader that forked a five-second sleeper and exited left that child alive after the pilot returned and released its lock. The test child then naturally exited and its group was confirmed absent. Retain/settle the owned group, not just the leader; do not report cleanup complete merely because worker.wait() returned.
  3. --evidence-reuse leaves stale readiness. Seeded ready.json with a previous-generation marker, then ran a child that exited before readiness. Pilot exited 1 / ready:false, but the previous ready.json remained. Consumers must not mistake it for current readiness; clear/version run-scoped evidence.
  4. Unexpected clean exit after readiness is reported as success. A fixture answered /health, then exited 0 without a stop request. Pilot exited 0, with ready:true and failures:[]. This condition is also present in the older Linux pilot; it is copied behavior, not a claim that this PR originated it.
  5. Voice provenance is hardcoded and validation incomplete. build_voice.py stamped a synthetic fixture source.kind: "consented" and exited 0. It also exited 0 and wrote catalogs for an empty reference and five references, outside the documented/loader contract. Require an explicit truthful source kind and validate the loader's limits before writing. For the real-engine tests I constructed supported source.kind: "synthetic" catalogs directly rather than publishing a false attestation.

Positive launcher checks: an occupied verifier lock, occupied test port, and deliberately impossible admission floor each refused before child spawn. No foreign process was displaced. Actual native shutdowns also completed cleanly; the child-cleanup bug above is from the separate adversarial lifecycle fixture, not an assertion that the real native batch leaked processes.

Additional source-review concern, not a runtime-confirmed result

[INFERENCE] The reusable boundary/key needs a more complete definition: reference_rows is the sum of audio-code counts, not the builder's actual prefix boundary (which also includes system/reference text), while the tower consumes the next prompt row. A snapshot through row N−1 can depend on row N, which is excluded from frames[0..N]'s key. A test with identical first N rows but a differing lookahead row should be added. I did not run that adversarial case or multi-lane/cancel-during-reference-prefill coverage, so I am not counting it as another reproduced audio failure.

Evidence, scope and recommendation

Retained report SHA-256: 35cd284f1d1fa51b158f9d6a6bee72f070257456a537a4c56bc25e551ef447e3.

  • Original live execution receipt SHA-256: c0f6d7aff0dca7ab94687f96359a25d5ed21e9b07e91668d2d208b1faf4ea28c.
  • Original CPU behavioral report SHA-256: 42fef4e932df4b3ba8c0341cfd86543ea04850d9e6dcd94638bb5dd7ec5d3138.
  • Original request bodies, PCM/WAV files, response headers, server logs, exact commands, compiler/checkpoint provenance and the independent verifier scripts are retained privately. Hashes identify retained evidence; they are not claims of a public attachment. This comment omits private host paths/PIDs.

The native batch took 105.38 seconds, under a separately coordinated window with an independent external Studio-priority/memory/deadline guard. Three server activations, one codec encode, and all original clients/pilots/native groups settled; the hold is released. No production Studio/runtime/model changes were made. This is cooperative scheduling, not whole-host exclusivity.

Not run: CUDA/GB10, the full 24-item corpus gate, sglang-omni qualification, a formal A/B/A2 performance study, multi-lane stress, or independent transcript/voice-quality scoring. Passing the targeted checks does not imply these gates passed. I am making no speedup claim.

Recommendation: request changes. The macOS build and normal cached speech path work, but the reproduced audio-identity regression and unbounded per-switch snapshot growth mean this head should not be merged yet. Fix those and the launcher/provenance defects, add the transition/ownership regressions, then reverify the new head.

@jerryfane

Copy link
Copy Markdown
Contributor

Repair implemented and live-retested on Mac

I implemented the fixes and submitted them directly to this PR's source branch through BobClawblaw/drama-tensorfold#1. GitHub reports that contribution MERGEABLE. My account cannot push directly to either repository, so the author/maintainer must merge that contribution to update PR17.

Tested repair head: f119696d1eca0aa53e91e1e7c2c141685e38c9fd. It also incorporates current upstream main (844d0eab) and resolves the README/build-script conflicts without dropping the new weight-format workflow.

What changed

  • One reusable recurrent snapshot pair per Metal lane; invalidate before default/different-prefix prefill and on errors. This fixes the wrong A → default → A audio and per-switch retained allocation.
  • Exact prompt-owned prefix boundary and tower lookahead identity, preserving uncached chunk shapes. No hash-only identity, full-KV copy, or new multi-voice cache.
  • Loopback-first Mac launcher; conservative single-snapshot memory accounting; finite admission controls; lock-protected readiness reuse; bounded owned-group cleanup with an unreaped leader and inherited lock; unexpected exits/observer failures fail closed.
  • Explicit truthful catalog provenance and validation matching the pinned server. Deterministic regressions, actual harmless lifecycle smoke, stronger PCM transition checks, and cached-voice corpus/stream coverage.
  • Correct Mac host-test linkage and documentation. The Mac guide qualifies full-model Metal, not NVFP4.

Observed results

Verification Result
Clean Metal server/generator build 66/66 steps passed; merged --weights full entry produces the same tested hashes
CPU checks 610 engine/server tests; 3 Metal-host checks passed, 1 skipped; 32 Python/lifecycle checks passed
CUDA compatibility Host entry points compile; CUDA runtime not exercised
Full corpus, 24 items × two passes per build 48/48 paired PCM captures byte-identical, all HTTP 200
Voice/default/text transitions and reference variants Passed, including last reference row, transcript changes and two references
Builtin/cached streaming and abandonment Four runs, 9/9 checks each
Eight warmed voice switches 0 KiB RSS spread on both uncached baseline and repair
Two-lane requests Eight replies matched the serial baseline
Settlement All 12 command owners, three native groups and the monitor settled; no production changes

Machine-readable results and paired hashes · Reproducible Mac instructions

The native run used the same pinned full checkpoint and retained synthetic reference, with unchanged prompt-seeded sampling. No model conversion/substitution, Studio restart/deployment, speed claim, or whole-host exclusivity claim. RSS is not direct device-memory telemetry. Initial setup/linkage failures and their corrections are retained in the report.

Merge assessment: the reproduced Mac blockers are fixed in the contribution. Do not merge the unchanged e77d80a head; first merge the contribution normally, preserving its upstream-main merge ancestry, or fast-forward this source branch to the tested repair head. No GitHub check runs were reported on the contribution at publication; local verification is not a claim of hosted CI approval. I authored this repair after the independent review, so this follow-up is a repair/retest report, not independent approval of my own changes.

plotarmordev added a commit that referenced this pull request Oct 24, 2026
Run Drama on macOS (PR #17 with the Mac-tested repair; supersedes #21)
@plotarmordev

Copy link
Copy Markdown
Owner

Thank you for starting the macOS port. Your commits landed in #22 together with jerryfane's Mac Studio repair and verification, with authorship kept (author emails switched to GitHub noreply addresses). I merged #22, so I'm closing this one in favour of it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants