Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
f5b0c6e
test(provider): gate the destructive-epoch capability test on DEBUG
davidtai Sep 3, 2026
5e957da
feat(bench/mtp): run the product MTP matrix at THE TEST
davidtai Sep 3, 2026
c8e4ec5
feat(provider/mtp): give Gemma 4 a measured depth policy and let auto…
davidtai Sep 3, 2026
ae8c553
fix(bench/mtp): size the synthetic prompt by measurement, not by a tu…
davidtai Sep 3, 2026
9a1154e
test(provider/mtp): pin the depth policy as shape-independent
davidtai Sep 3, 2026
a7dd134
feat(bench/mtp): measure MTP on real text, and hand stateless drafter…
davidtai Sep 4, 2026
6cdd3b5
feat(bench/mtp): surface the engine's per-round stage timing in the r…
davidtai Sep 4, 2026
d155086
feat(provider): project MLX_MAX_MB_PER_BUFFER=500 before MLX initializes
davidtai Sep 4, 2026
05430ab
feat(bench/mtp): hold between cases inside the runner's own case loop
davidtai Sep 4, 2026
93dfc2c
feat(provider): project MLX_MAX_MB_PER_BUFFER=500 and pin the trimmed…
davidtai Sep 4, 2026
6ef2a52
fix(bench/mtp): give the benchmark process the serving environment
davidtai Sep 4, 2026
408a66d
build(deps): pin mlx-swift to the Gemma 4 perf stack (feat/gemma4-mlx…
davidtai Sep 4, 2026
ffefa9d
fix(provider): make the environment apply seam public for the benchmark
davidtai Sep 4, 2026
abc580c
Merge feat/gemma4-mtp-on-serial into the trimmed provider base
davidtai Sep 4, 2026
885f2f0
test(ssd): DEBUG-gate the destructive-epoch test so release --build-t…
davidtai Sep 4, 2026
eaec7cb
build(deps): bump engine pin to 29828b66 (test-only fixes; product un…
davidtai Sep 4, 2026
aa820e7
build(deps): bump engine pin to eb378720 (drafter RoPE rank fix)
davidtai Sep 4, 2026
17e732b
fix(bench/mtp): let the harness express a baseline arm, and read adap…
davidtai Sep 4, 2026
453499f
Merge the trimmed provider base's DEBUG gate and engine pin
davidtai Sep 4, 2026
b46ee28
build(deps): bump engine pin to the base-compatible drafter fix
davidtai Sep 5, 2026
2ef962f
Merge the base provider's engine pin bump
davidtai Sep 5, 2026
96d4d93
build(deps): bump engine pin to cfa2bb2b (MTP-path regression repair)
davidtai Sep 5, 2026
5009a27
build(deps): bump engine pin to 42ee6692 (final 2 MTP regressions fixed)
davidtai Sep 5, 2026
3e20a24
fix(provider): keep MLX_MAX_MB_PER_BUFFER out of the retained-validat…
davidtai Sep 5, 2026
0048005
Merge the trimmed provider base; repoint the engine pin, take the ser…
davidtai Sep 5, 2026
99acaeb
build(deps): bump engine pin to 0cb4c68d (forcedPolicy engine-queue r…
davidtai Sep 5, 2026
01374e6
fix(bench/mtp): teach the python validator schema 10
davidtai Sep 5, 2026
d21ef35
Integrate Gemma MLXFast ports and qualification metric fixes
jonathan308 Sep 18, 2026
108fde4
Reconcile Gemma integration with current provider production fixes
jonathan308 Sep 18, 2026
49df604
refactor: share the verified-draft-work check in MTP metric validation
davidtai Oct 4, 2026
ad50982
Merge master dccc9ee0 into feat/gemma4-mtp-stacked
davidtai Oct 6, 2026
8db33cc
Merge origin/master 7a0d4c1a into feat/gemma4-mtp-stacked
davidtai Oct 6, 2026
f106679
Merge origin/master 470a86d4 into feat/gemma4-mtp-stacked
davidtai Oct 6, 2026
fb8a429
build(provider): pin mlx 725859207, mlx-swift 9fb21921, mlx-swift-lm …
davidtai Oct 6, 2026
09f0381
Merge origin/master 5f63c8fe into feat/gemma4-mtp-stacked
davidtai Oct 6, 2026
00b2520
Merge origin/master 16823b52 into feat/gemma4-mtp-stacked
davidtai Oct 7, 2026
690bad1
build(provider): pin mlx ac97252e, mlx-swift 17bbcba7, mlx-swift-lm 4…
davidtai Oct 7, 2026
fcc9d1e
Merge origin/master b5c12abf into feat/gemma4-mtp-stacked
davidtai Oct 7, 2026
1b726a5
Merge origin/master (57fe69d8) into feat/gemma4-mtp-stacked
davidtai Oct 9, 2026
bb12625
Merge origin/master (4230fa03) into feat/gemma4-mtp-stacked
davidtai Oct 9, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
# Changelog

## Unreleased — Gemma 4 MLXFast opt-in ports

- Integrate operation-scoped Gemma 4 decode/prefill, expert-routing and cache fast
paths with corrected arithmetic and regression coverage. Keep optimization
flags off by default and preserve current sampled MTP, model weights,
quantization, multimodal support, batching, paging and prefix-cache policy.
- Separate production MTP correctness evidence from retained performance-learning
samples, and recognize bounded seed-only automatic-cap fallback without
weakening exact token/finish comparisons or changing the automatic work cap.
- Keep the known longer fixed-L4/B8 MTP parity failure and separate reasoning/tool
compatibility gaps visible; these ports do not establish full release readiness.

## Unreleased — provider cache storage controls

- Add `darkbloom cache set --daily-write-gb ... --directory ...` and `cache status` for persistent write limits and optional external cache storage. Validate local APFS storage, require encryption for external volumes, pin the volume UUID and refuse unavailable or replaced disks without falling back. Keep encryption keys and the rolling-day write ledger on the Mac; switching disks does not reset usage. Changes apply after restart.
Expand Down
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@
- [`developer/personal-data.md`](developer/personal-data.md): add a personal column, table or writer so account erasure still removes it; marker and parity tests.
- [`developer/threat-model-review.md`](developer/threat-model-review.md): configure PR text scans, provider fallback, and optional conditional merge clearance.
- [`developer/serving-performance-qualification.md`](developer/serving-performance-qualification.md): measure and review exact serving profiles before promoting concurrency limits or prefill policy.
- [`developer/gemma-mtp-validation.md`](developer/gemma-mtp-validation.md): supervised target/assistant correctness, stop-policy and performance gates.

## Operations runbooks (production; human approval per mutation)

Expand Down
37 changes: 19 additions & 18 deletions docs/developer/build.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Build

> Last updated: 2026-10-08
> Last updated: 2026-10-09

Stack maintenance uses Python 3, Git, authenticated `gh`, and a configured commit
signer; it requires no product build. Follow [Maintain a pull-request stack](pull-requests.md)
Expand Down Expand Up @@ -145,6 +145,9 @@ prompt contract cannot reuse a v5 cache identity. The follow-up retains the
merged native SDK pin and does not require new model weights. See
[prompt parity](test.md#9-prompt-contract-parity-fixtures-and-vectors) for the validation procedure.

Use the matching test products for [Gemma MTP validation](gemma-mtp-validation.md);
that procedure keeps production performance evidence distinct from correctness.

Docs Lint needs Git history to validate moved source links in frozen records;
its checkout uses `fetch-depth: 0` (`.github/workflows/ci.yml`, `docs` job).
Freshness stamps contain only dates. The checker recovers legacy verification
Expand Down Expand Up @@ -448,25 +451,26 @@ jobs queued behind a provider quota do not shorten the critical path. See

The provider consumes the local packages through immutable Git submodule pins:

| Package | Merged revision | Included update |
| Package | Revision | Included update |
|---|---|---|
| `libs/mlx` | `cb77239be31b1df7f5db895226af55c39fc4f093` | `gather_mm` / `gather_qmm` row-tile backport |
| `libs/mlx-swift/Source/Cmlx/mlx` | `cb77239be31b1df7f5db895226af55c39fc4f093` | Same merged MLX source used by Cmlx and the provider metallib |
| `libs/mlx-swift` | `6923a80f624f5c91fbf456efe4e00e9698a72961` | [PR #34](https://github.com/Layr-Labs/mlx-swift/pull/34): merged nested MLX row-tile backport and regenerated kernel sources; retains [PR #28](https://github.com/Layr-Labs/mlx-swift/pull/28) exact constant reuse for eligible Bonsai packed projections |
| `libs/mlx-swift-lm` | `3fd4944c3b3ee5cb45c5cbfac8805876332d3a29` | Includes [PR #289](https://github.com/Layr-Labs/mlx-swift-lm/pull/289) bounded demanded checkpoint capture, retention and continuation, [PR #290](https://github.com/Layr-Labs/mlx-swift-lm/pull/290) native cancellation retirement, and [PR #165](https://github.com/Layr-Labs/mlx-swift-lm/pull/165) typical MTP acceptance |
| `libs/mlx` | `ac97252e68d4cce305e9c19eefc67bc70d41cbaa` | [mlx PR #13](https://github.com/Layr-Labs/mlx/pull/13) head: Gemma 4 Metal kernel work, merged with MLX `main` `cb77239b` (the `gather_mm` / `gather_qmm` row-tile backport) |
| `libs/mlx-swift/Source/Cmlx/mlx` | `ac97252e68d4cce305e9c19eefc67bc70d41cbaa` | Same MLX source used by Cmlx and the provider metallib |
| `libs/mlx-swift` | `17bbcba7bf45303d235df6f2d71aae8c93053559` | [PR #19](https://github.com/Layr-Labs/mlx-swift/pull/19) head: Gemma 4 kernel pins and regenerated kernel sources, merged with [PR #26](https://github.com/Layr-Labs/mlx-swift/pull/26) (per-kernel Metal math modes) and Swift `main` `6923a80f` ([PR #34](https://github.com/Layr-Labs/mlx-swift/pull/34)). It contains [PR #27](https://github.com/Layr-Labs/mlx-swift/pull/27) (Hadamard layers) and [PR #28](https://github.com/Layr-Labs/mlx-swift/pull/28) (`0f4fe403`, exact constant reuse for eligible Bonsai packed projections) |
| `libs/mlx-swift-lm` | `b62182975ac4b38e04bf880a766ca41ba6635226` | [PR #138](https://github.com/Layr-Labs/mlx-swift-lm/pull/138) head: Gemma 4 MLXFast kernels and cache fast paths, merged with SDK `main` `3fd4944c`. It includes [PR #289](https://github.com/Layr-Labs/mlx-swift-lm/pull/289) bounded demanded checkpoint capture, retention and continuation, [PR #290](https://github.com/Layr-Labs/mlx-swift-lm/pull/290) native cancellation retirement, and [PR #165](https://github.com/Layr-Labs/mlx-swift-lm/pull/165) typical MTP acceptance |

Keep both local packages in the provider build. The SDK's standalone package
manifest pins Swift `0f4fe403bef6899e8a72882bc6d4036a7a62ae31`, not the provider's
current Swift gitlink; the nested-test
manifest pins Swift `17bbcba7bf45303d235df6f2d71aae8c93053559`, the same revision
as the `libs/mlx-swift` gitlink; the nested-test
procedure in [test.md](test.md#4-provider-swift--unit-tests-with-a-source-matched-metallib) binds it to the recorded local
Swift gitlink. Keep `libs/mlx` and `libs/mlx-swift/Source/Cmlx/mlx` on the same
merged MLX commit for the `gather_mm` / `gather_qmm` row-tile backport. The Swift
pin includes kernel sources regenerated from that nested MLX revision, including
the signed integer floor-division corrections from [MLX PR #32](https://github.com/Layr-Labs/mlx/pull/32)
in the generated binary-operations and CPU preamble sources.
Build `mlx.metallib` from the nested source with
MLX commit. The Swift pin includes kernel sources regenerated from that nested
MLX revision, including the signed integer floor-division corrections from
[MLX PR #32](https://github.com/Layr-Labs/mlx/pull/32) in the generated
binary-operations and CPU preamble sources. Build `mlx.metallib` from the nested source with
`scripts/fetch-metallib.sh`; changing only the top-level MLX gitlink does not
change provider bytes.
change provider bytes. The `libs/mlx-swift` revision pins the C wrapper at
`ad3799cb`, the `codex/gemma4-kernel-math-mode` head that adds explicit math
modes for custom Metal kernels on top of `02cf6f4d`.
Rebuild the consumer after changing pins; earlier full-model measurements are
evidence for their recorded dependency set, not a new benchmark of these pins.
The SDK's acceptance default remains exact; the provider's eligible sampled
Expand All @@ -476,10 +480,7 @@ Neither that policy nor the newer native retirement and MLX kernels are
qualified by the original demanded-prefix full-model results. The
[dependency validation procedure](test.md#merged-sdk-pin-validation) separates
required tiny-fixture regressions from fresh full-model performance qualification.
The earlier SDK [PR #170](https://github.com/Layr-Labs/mlx-swift-lm/pull/170)
pin `4101d4c1bfa6b3175e7f34393e8c235a75a7c1be` had production libraries and a
package manifest matching review head `b52335b839d80c8e6d4194ebbd8809d737cd8eb3`.
That historical comparison is not validation of the current SDK pin above.
All three pins are open pull-request heads, not merged `main` history.

### Native Flash-Next candidate

Expand Down
73 changes: 73 additions & 0 deletions docs/developer/gemma-mtp-validation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Validate Gemma target and assistant behavior

> Last updated: 2026-09-17

Run the supervised Gemma MTP matrix with immutable local target and assistant
snapshots. Keep numerical correctness, production stop behavior and performance
evidence separate.

## Prerequisites

Build the provider tests and matching Metal resources using [Build](build.md).
Reserve one exclusive GPU lane. Keep the target, assistant, quantization,
sampler, source pins and runtime resources fixed across comparisons. The runner
uses cached artifacts only and refuses incomplete or mismatched identities.

## Steps

1. Run the CPU-only supervisor checks from the repository root:

```sh
python3 scripts/test-mtp-metric-contracts.py
python3 scripts/run-mtp-benchmark.py --self-test-output-safety
python3 scripts/run-mtp-benchmark.py --self-test-artifact-provenance
```

2. Run `MTPMetricContractTests` and `MTPBenchmarkTests` in `provider-swift`.
Require nonzero test counts and no skipped tests.
3. Run `scripts/run-mtp-benchmark.py` with explicit `--target-path` and
`--assistant-path` snapshots. Supply `--target-id` and `--assistant-id` when
a path is outside the Hugging Face cache layout. Select the mode below.

| Mode | Stop behavior | Required evidence |
|---|---|---|
| `raw-parity` | Fixed length, configured stops suppressed | Exact token/terminal evidence; no performance fields |
| `production-correctness` | Target's production EOS/stops | Exact token/terminal evidence and automatic verification; no performance fields |
| `production-performance` | Target's production EOS/stops | Release build, timings and retained positive-depth cost samples for applicable active modes |

4. Preserve the complete report, launch fingerprint, commands, source/artifact
identities and any failed attempts. A partial checkpoint is not a passing
matrix. Never quote correctness-mode wall time as throughput.

## Verify

`MTPBenchmarkRunner.validateMetrics` distinguishes completed verification from
retained cost learning. A request or token boundary can cancel a learning window
after real drafts have been verified. Correctness may use actual verification
counters plus tracked acceptance positions when a cost sample is unavailable;
performance still requires the depth/bucket cost evidence. Both modes retain
the exact target-only token and finish-reason comparison.

An automatic work-cap fallback may contain an initial ordinary seed before the
requested batch fills. Positive plans must be bounded by recorded seeds. A
seed-only fallback still requires zero draft proposals, verification rounds,
accepted/emitted speculative tokens, speculative timing and cost residue. It
is not evidence of MTP throughput. The automatic work cap is unchanged.

The Swift checks live in
`provider-swift/Sources/ProviderBenchmark/MTPBenchmarkRunner.swift`; the Python
report checks in `scripts/run-mtp-benchmark.py` mirror them. The regression
fixtures in `MTPMetricContractTests` and `scripts/test-mtp-metric-contracts.py`
reject invented seeds, unexplained positive plans, speculative residue,
out-of-cap work and unsupported cost-evidence claims.

## Troubleshooting

If a performance run has no retained cost sample, use a workload long enough
to measure a complete learning window. Do not increase the automatic work cap,
switch to a serial oracle, suppress production EOS, or weaken token equality
to make a performance report pass. Use a separately labelled correctness run
to investigate execution without making a speed claim.

This matrix does not replace real API/tool/media, cache persistence, memory,
lifecycle or signed/hosted qualification. See [Test](test.md) for those gates.
5 changes: 4 additions & 1 deletion docs/developer/test.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Test

> Last updated: 2026-10-08
> Last updated: 2026-10-09

## Autopilot rewards

Expand Down Expand Up @@ -271,6 +271,9 @@ the docs lint locally; CI runs a subset per pull request (see the CI workflow
map: the Gemma benchmark-wrapper tests run only locally). The e2e suite needs an Apple Silicon
Mac with the test checkpoints cached.

For the supervised target/assistant matrix and its separate correctness and
performance evidence, follow [Gemma MTP validation](gemma-mtp-validation.md).

The registry's `TestCacheAttemptBudget*` tests cover logical byte charging,
checked arithmetic, exact-edge admission, immutable replacement/refunds and
detached tracker storage. `TestCacheAttemptBudgetReclaimsFinishedRecordsBeforeRefusing`
Expand Down
2 changes: 1 addition & 1 deletion libs/mlx-swift-lm
Submodule mlx-swift-lm updated 77 files
+39 −0 Libraries/MLXLLM/Models/Gemma4DenseGateUpPolicy.swift
+97 −0 Libraries/MLXLLM/Models/Gemma4DenseGateUpStorage.swift
+16 −9 Libraries/MLXLLM/Models/Gemma4MTP.swift
+821 −105 Libraries/MLXLLM/Models/Gemma4Text.swift
+5 −1 Libraries/MLXLMCommon/ContinuousBatchingV2/EngineLoopV2.swift
+969 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4B8ExpertDownSources.swift
+81 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4B8ExpertExecution.swift
+1,212 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4B8ExpertGUSources.swift
+35 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4B8ExpertPolicy.swift
+99 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4B8ExpertRouting.swift
+69 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4B8ExpertStorage.swift
+51 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4B8RouteFoldSources.swift
+56 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4B8RouteKernels.swift
+21 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4B8RoutePolicy.swift
+54 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4B8RouteSources.swift
+81 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4CacheEvaluationRoots.swift
+27 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4CacheRootPolicy.swift
+53 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4DecodeGluePolicy.swift
+223 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4DecodeGlueSources.swift
+164 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4DecodeGlueV1.swift
+61 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4DecodeNormalizationCarry.swift
+37 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4DeferredExpertState.swift
+45 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4PositionCycle.swift
+47 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4PrefillExpertOrder.swift
+71 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4PrefillExpertProjection.swift
+169 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4PrefillGluePolicy.swift
+633 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4PrefillGlueSources.swift
+291 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4PrefillGlueV1.swift
+21 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4PrefillNormalizationCarry.swift
+140 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4PrefillRouting.swift
+82 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4PromptGlueSources.swift
+63 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4PromptGlueV1.swift
+78 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4QKVNormPolicy.swift
+493 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4QKVNormSources.swift
+163 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4QKVNormV1.swift
+121 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4RMSBroadcastSources.swift
+194 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4RouteSortSources.swift
+41 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4RouterFinalistsPolicy.swift
+301 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4RouterFinalistsSources.swift
+55 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4RouterFinalistsV1.swift
+27 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4ScaledEmbeddingPolicy.swift
+39 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4ScaledEmbeddingSources.swift
+41 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4ScaledEmbeddingV1.swift
+216 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/Gemma4UnifiedPositions.swift
+51 −7 Libraries/MLXLMCommon/ContinuousBatchingV2/LayerCacheBankV2.swift
+30 −2 Libraries/MLXLMCommon/ContinuousBatchingV2/LayerCacheV2.swift
+7 −15 Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPExecution.swift
+6 −1 Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPTargetVerification.swift
+37 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/MTPSampledTokenAssembly.swift
+5 −0 Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/WindowedSequenceKV.swift
+12 −5 Libraries/MLXLMCommon/ContinuousBatchingV2/SteppableAdapterV2.swift
+4 −0 Libraries/MLXLMCommon/RoPEUtils.swift
+270 −154 Libraries/MLXLMCommon/SwitchLayers.swift
+169 −0 Libraries/MLXLMCommon/WeightedExpertUnsort.swift
+3 −1 Package.swift
+46 −0 Tests/HostOnly/GemmaCatchup/CacheInterfaces.swift
+51 −0 Tests/HostOnly/GemmaCatchup/FinalistsReference.swift
+1,078 −0 Tests/HostOnly/GemmaCatchup/HostContracts.swift
+104 −0 Tests/HostOnly/GemmaCatchup/README.md
+72 −0 Tests/HostOnly/GemmaCatchup/RouteSortReference.swift
+119 −0 Tests/MLXLMTests/Gemma4AssistantDecodeGlueTests.swift
+110 −0 Tests/MLXLMTests/Gemma4B8ExpertTests.swift
+90 −0 Tests/MLXLMTests/Gemma4B8RouteTests.swift
+139 −0 Tests/MLXLMTests/Gemma4CacheEvaluationRootTests.swift
+190 −0 Tests/MLXLMTests/Gemma4DecodeGlueTests.swift
+118 −0 Tests/MLXLMTests/Gemma4DenseGateUpStorageTests.swift
+48 −0 Tests/MLXLMTests/Gemma4NativeParityAssertions.swift
+378 −0 Tests/MLXLMTests/Gemma4PrefillGlueTests.swift
+107 −0 Tests/MLXLMTests/Gemma4PromptGlueTests.swift
+112 −0 Tests/MLXLMTests/Gemma4QKVNormTests.swift
+91 −0 Tests/MLXLMTests/Gemma4RouteSortTests.swift
+91 −0 Tests/MLXLMTests/Gemma4RouterFinalistsTests.swift
+53 −0 Tests/MLXLMTests/Gemma4ScaledEmbeddingTests.swift
+52 −0 Tests/MLXLMTests/Gemma4SharedReductionTests.swift
+108 −0 Tests/MLXLMTests/Gemma4UnifiedPositionTests.swift
+63 −1 fork.yaml
+71 −0 scripts/test_gemma_host_contracts.py
51 changes: 41 additions & 10 deletions provider-swift/Sources/ProviderBenchmark/MTPBenchmarkRunner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,8 @@ public enum MTPBenchmarkRunner {
key.batchSize),
allowedSkipReasons: configuration.allowedSkipReasons,
expectation: configuration.mtpExpectation,
requireAutomaticVerification: configuration.purpose != .rawParityStress)
requireAutomaticVerification: configuration.purpose != .rawParityStress,
requireCostLearningEvidence: configuration.purpose == .productionPerformance)
await session.engine.shutdown()
didShutdown = true
try requireBeforeDeadline(deadlineAt)
Expand All @@ -402,7 +403,8 @@ public enum MTPBenchmarkRunner {
adaptiveDraftingExpected: Bool,
allowedSkipReasons: Set<String>,
expectation: MTPBenchmarkMTPExpectation = .active,
requireAutomaticVerification: Bool = false
requireAutomaticVerification: Bool = false,
requireCostLearningEvidence: Bool = true
) throws {
try validateActivation(
metrics: metrics,
Expand Down Expand Up @@ -458,11 +460,14 @@ public enum MTPBenchmarkRunner {
throw MTPBenchmarkError.invalidMetrics(
"\(mode.label), B=\(batchSize) did not execute active draft rounds")
}
guard metrics.costInputs.contains(where: {
let measuredRequestedCost = metrics.costInputs.contains(where: {
$0.decodeRowBucket == expectedBucket
&& $0.draftDepth == expectedDepth
&& $0.sampleCount > 0
}) else {
})
let verifiedRequestedWork = !requireCostLearningEvidence
&& hasVerifiedDraftWork(metrics, minimumDepth: expectedDepth)
guard measuredRequestedCost || verifiedRequestedWork else {
throw MTPBenchmarkError.invalidMetrics(
"\(mode.label), B=\(batchSize) did not measure requested depth/bucket")
}
Expand Down Expand Up @@ -490,18 +495,33 @@ public enum MTPBenchmarkRunner {
throw MTPBenchmarkError.invalidMetrics(
"adaptive B=\(batchSize) never selected a nonzero depth")
}
guard metrics.costInputs.contains(where: {
let measuredPositiveCost = metrics.costInputs.contains(where: {
$0.decodeRowBucket == expectedBucket
&& $0.draftDepth > 0
&& $0.sampleCount > 0
}) else {
})
let verifiedPositiveWork = !requireCostLearningEvidence
&& hasVerifiedDraftWork(metrics, minimumDepth: 1)
guard measuredPositiveCost || verifiedPositiveWork else {
throw MTPBenchmarkError.invalidMetrics(
"adaptive B=\(batchSize) lacks positive-depth cost evidence for requested bucket \(expectedBucket)")
}
}
}
}

/// Correctness certifies executed verification, not retention of a
/// learning window cancelled at a request/token boundary: verification
/// ran and acceptance was tracked through `minimumDepth`. Performance
/// still requires a measured depth/bucket cost sample.
private static func hasVerifiedDraftWork(
_ metrics: MTPBenchmarkMetrics,
minimumDepth: Int
) -> Bool {
(metrics.rectangularVerificationRounds ?? 0) + (metrics.serialVerificationRounds ?? 0) > 0
&& metrics.acceptanceByPosition.count >= minimumDepth
}

private static func validateAutomaticDepthLimitFallback(
_ metrics: MTPBenchmarkMetrics,
batchSize: Int,
Expand All @@ -526,11 +546,11 @@ public enum MTPBenchmarkRunner {
throw MTPBenchmarkError.invalidMetrics(
"automatic fixed-depth fallback B=\(batchSize) escaped its rectangular limit")
}
if hasPositiveDepth {
if metrics.rounds > 0 {
// The depth controller intentionally refuses cost attribution
// when the finalized depth differs from its requested depth, so
// clamped rounds may record no positive cost inputs at all.
guard metrics.rounds > 0,
guard hasPositiveDepth,
metrics.proposedTokens > 0,
(metrics.rectangularVerificationRounds ?? 0) > 0
else {
Expand All @@ -539,10 +559,21 @@ public enum MTPBenchmarkRunner {
}
return true
}
guard metrics.selectedDepth == 0,
// Selections record plans, including an initial seed at a smaller
// cohort before the requested batch fills. A seed is ordinary target
// decode, not a draft/verify round. Admit only bounded seed-only
// residue while still requiring zero speculative output/work.
let positiveSelections = metrics.depthSelections.reduce(Int?.some(0)) { total, entry in
guard let total, let depth = Int(entry.key), depth >= 0, entry.value >= 0 else { return nil }
let (sum, overflow) = total.addingReportingOverflow(depth > 0 ? entry.value : 0)
return overflow ? nil : sum
}
guard let positiveSelections,
(metrics.seedRows == 0 && positiveSelections == 0)
|| (metrics.seedRows > 0 && positiveSelections > 0 && positiveSelections <= metrics.seedRows),
metrics.selectedDepth == 0,
metrics.depthSelections["0", default: 0] > 0,
metrics.rounds == 0,
metrics.seedRows == 0,
metrics.proposedTokens == 0,
metrics.acceptedDraftTokens == 0,
metrics.committedTokens == 0,
Expand Down
Loading
Loading