diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e8611f769..1d07a8b57a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/docs/README.md b/docs/README.md index b66947877a..d09a184507 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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) diff --git a/docs/developer/build.md b/docs/developer/build.md index 88a7234047..120d15d12b 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -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) @@ -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 @@ -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 @@ -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 diff --git a/docs/developer/gemma-mtp-validation.md b/docs/developer/gemma-mtp-validation.md new file mode 100644 index 0000000000..450cad7e22 --- /dev/null +++ b/docs/developer/gemma-mtp-validation.md @@ -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. diff --git a/docs/developer/test.md b/docs/developer/test.md index e7610567de..e5be95765e 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test -> Last updated: 2026-10-08 +> Last updated: 2026-10-09 ## Autopilot rewards @@ -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` diff --git a/libs/mlx b/libs/mlx index cb77239be3..ac97252e68 160000 --- a/libs/mlx +++ b/libs/mlx @@ -1 +1 @@ -Subproject commit cb77239be31b1df7f5db895226af55c39fc4f093 +Subproject commit ac97252e68d4cce305e9c19eefc67bc70d41cbaa diff --git a/libs/mlx-swift b/libs/mlx-swift index 6923a80f62..17bbcba7bf 160000 --- a/libs/mlx-swift +++ b/libs/mlx-swift @@ -1 +1 @@ -Subproject commit 6923a80f624f5c91fbf456efe4e00e9698a72961 +Subproject commit 17bbcba7bf45303d235df6f2d71aae8c93053559 diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 3fd4944c3b..b62182975a 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 3fd4944c3b3ee5cb45c5cbfac8805876332d3a29 +Subproject commit b62182975ac4b38e04bf880a766ca41ba6635226 diff --git a/provider-swift/Sources/ProviderBenchmark/MTPBenchmarkRunner.swift b/provider-swift/Sources/ProviderBenchmark/MTPBenchmarkRunner.swift index ce63aeff40..39ab195452 100644 --- a/provider-swift/Sources/ProviderBenchmark/MTPBenchmarkRunner.swift +++ b/provider-swift/Sources/ProviderBenchmark/MTPBenchmarkRunner.swift @@ -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) @@ -402,7 +403,8 @@ public enum MTPBenchmarkRunner { adaptiveDraftingExpected: Bool, allowedSkipReasons: Set, expectation: MTPBenchmarkMTPExpectation = .active, - requireAutomaticVerification: Bool = false + requireAutomaticVerification: Bool = false, + requireCostLearningEvidence: Bool = true ) throws { try validateActivation( metrics: metrics, @@ -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") } @@ -490,11 +495,14 @@ 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)") } @@ -502,6 +510,18 @@ public enum MTPBenchmarkRunner { } } + /// 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, @@ -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 { @@ -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, diff --git a/provider-swift/Tests/ProviderCoreTests/Benchmark/MTPMetricContractTests.swift b/provider-swift/Tests/ProviderCoreTests/Benchmark/MTPMetricContractTests.swift new file mode 100644 index 0000000000..a8d00a34ad --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Benchmark/MTPMetricContractTests.swift @@ -0,0 +1,124 @@ +import MLXLMCommon +import Testing + +@testable import ProviderBenchmark + +@Suite("MTP execution and cost-learning evidence") +struct MTPMetricContractTests { + private func seedOnly() -> CBv2MTPMetrics { + var value = CBv2MTPMetrics() + value.maxAutomaticRectangularTokens = 8 + value.decodeRowBucket = 8 + value.seedSteps = 1 + value.depthSelections = [0: 127, 3: 1] + value.controllerFallbacks = ["automatic_rectangular_limit": 127] + return value + } + + private func validateSeed(_ value: CBv2MTPMetrics) throws { + try MTPBenchmarkRunner.validateMetrics(MTPBenchmarkMetrics(engineMetrics: value), + mode: .fixed(verificationWidth: 4), batchSize: 8, + adaptiveDraftingExpected: true, allowedSkipReasons: []) + } + + private func executed(depth: Int = 1) -> CBv2MTPMetrics { + var value = CBv2MTPMetrics() + value.maxAutomaticRectangularTokens = 8 + value.decodeRowBucket = 1 + value.rounds = 8 + value.seedSteps = 1 + value.draftedTokens = 8 * depth + value.acceptedTokens = 7 + value.emittedTokens = 15 + value.rectangularVerificationRounds = 8 + value.perPositionAccepted = Array(repeating: 7, count: depth) + value.depthSelections = [0: 8, depth: 9] + value.controllerFallbacks = ["tail_depth": 2] + return value + } + + private func validateExecution(_ value: CBv2MTPMetrics, + mode: MTPBenchmarkMode = .adaptive, + requireCost: Bool) throws { + try MTPBenchmarkRunner.validateMetrics(MTPBenchmarkMetrics(engineMetrics: value), + mode: mode, batchSize: 1, adaptiveDraftingExpected: true, + allowedSkipReasons: [], requireAutomaticVerification: true, + requireCostLearningEvidence: requireCost) + } + + @Test func seedBeforeBatchFillIsNotADraftRound() throws { + try validateSeed(seedOnly()) + var zero = seedOnly() + zero.seedSteps = 0 + zero.depthSelections = [0: 127] + try validateSeed(zero) + } + + @Test func unexplainedSeedOrPositiveSelectionsAreRejected() throws { + for variant in 0..<5 { + var value = seedOnly() + switch variant { + case 0: value.seedSteps = 0 + case 1: value.depthSelections = [0: 127] + case 2: value.depthSelections = [0: 127, 3: 2] + case 3: value.depthSelections = [-1: 1, 0: 127] + default: + value.seedSteps = .max + value.depthSelections = [0: 127, 1: .max, 2: 1] + } + #expect(throws: MTPBenchmarkError.self) { try validateSeed(value) } + } + } + + @Test func seedsNeverExcuseSpeculativeResidueOrAnUnexplainedFallback() throws { + for variant in 0..<9 { + var value = seedOnly() + switch variant { + case 0: value.rounds = 1 + case 1: value.draftedTokens = 1 + case 2: value.acceptedTokens = 1 + case 3: value.emittedTokens = 1 + case 4: value.rectangularVerificationRounds = 1 + case 5: value.serialVerificationRounds = 1 + case 6: value.totalRoundWallTimeNanos = 1 + case 7: value.perPositionAccepted = [0] + default: value.controllerFallbacks = [:] + } + #expect(throws: MTPBenchmarkError.self) { try validateSeed(value) } + } + } + + @Test func cancelledLearningWindowCanStillProveCorrectnessExecution() throws { + let value = executed() + try validateExecution(value, requireCost: false) + #expect(throws: MTPBenchmarkError.self) { try validateExecution(value, requireCost: true) } + } + + @Test func costExemptionRequiresActualVerificationAndAcceptedPositionTracking() throws { + for variant in 0..<4 { + var value = executed() + switch variant { + case 0: value.rectangularVerificationRounds = 0 + case 1: value.perPositionAccepted = [] + case 2: value.rounds = 0 + default: value.draftedTokens = 0 + } + #expect(throws: MTPBenchmarkError.self) { try validateExecution(value, requireCost: false) } + } + } + + @Test func fixedDepthMustHaveBeenRepresentedInFinalizedWork() throws { + var value = executed(depth: 2) + let mode = try MTPBenchmarkMode.fixed(verificationWidth: 3) + try validateExecution(value, mode: mode, requireCost: false) + #expect(throws: MTPBenchmarkError.self) { try validateExecution(value, mode: mode, requireCost: true) } + value.perPositionAccepted = [7] + #expect(throws: MTPBenchmarkError.self) { try validateExecution(value, mode: mode, requireCost: false) } + } + + @Test func productionCorrectnessStillRejectsSerialVerification() throws { + var value = executed() + value.serialVerificationRounds = 1 + #expect(throws: MTPBenchmarkError.self) { try validateExecution(value, requireCost: false) } + } +} diff --git a/scripts/run-mtp-benchmark.py b/scripts/run-mtp-benchmark.py index a4596ff3a3..c8b154e45b 100644 --- a/scripts/run-mtp-benchmark.py +++ b/scripts/run-mtp-benchmark.py @@ -715,6 +715,27 @@ def positive_costs_within_cap(metrics: dict[str, Any], cap: int) -> bool: ) +def has_verified_depth(metrics: dict[str, Any], minimum_depth: int) -> bool: + """Execution evidence for correctness when a cost-learning window was cancelled.""" + counters = [0 if metrics.get(name) is None else metrics[name] for name in + ("rectangularVerificationRounds", "serialVerificationRounds")] + acceptance = metrics.get("acceptanceByPosition") + return (all(type(value) is int and value >= 0 for value in counters) + and sum(counters) > 0 and isinstance(acceptance, list) + and len(acceptance) >= minimum_depth) + + +def has_cost_or_verified_depth( + metrics: dict[str, Any], bucket: int, depth: int, *, exact: bool, require_cost: bool +) -> bool: + measured = any( + item.get("decodeRowBucket") == bucket + and (item.get("draftDepth") == depth if exact else item.get("draftDepth", 0) >= depth) + and item.get("sampleCount", 0) > 0 + for item in metrics.get("costInputs", []) if isinstance(item, dict)) + return measured or (not require_cost and has_verified_depth(metrics, depth)) + + def validate_automatic_fixed_fallback( metrics: dict[str, Any], batch: int, depth: int, label: str ) -> bool: @@ -729,34 +750,37 @@ def validate_automatic_fixed_fallback( if cap is None or batch * (depth + 1) <= cap: return False selections = metrics.get("depthSelections", {}) - has_positive_depth = any( - key.isdigit() and int(key) > 0 and count > 0 - for key, count in selections.items() - if isinstance(key, str) and isinstance(count, int) - ) + if any(not isinstance(key, str) or not key.isdigit() + or type(count) is not int or count < 0 for key, count in selections.items()): + raise ValueError(f"{label} has invalid depth selections") + positive_selections = sum(count for key, count in selections.items() if int(key) > 0) + has_positive_depth = positive_selections > 0 if ( metrics.get("controllerFallbacks", {}).get("automatic_rectangular_limit", 0) <= 0 or not positive_costs_within_cap(metrics, cap) or metrics.get("serialVerificationRounds", 0) != 0 ): raise ValueError(f"{label} escaped its rectangular limit") - if has_positive_depth: + if metrics.get("rounds", 0) > 0: if ( - metrics.get("rounds", 0) <= 0 + not has_positive_depth or metrics.get("proposedTokens", 0) <= 0 or metrics.get("rectangularVerificationRounds", 0) <= 0 ): raise ValueError(f"{label} lacks clamped-depth evidence") return True - # Complete zero-work evidence, mirroring the Swift validator field for - # field: a zero-fit clamp certifies that EXACT canonical fallback - # occurred, so any speculative array, counter, or timing residue must - # reject the report. + # A smaller initial cohort may seed before the requested batch fills. + # Positive plans must be bounded by real seeds; no draft/verify/output + # residue is permitted. This is target-only fallback, not MTP throughput. + seeds = metrics.get("seedRows", 0) + seed_only_plans = type(seeds) is int and ( + (seeds == 0 and positive_selections == 0) + or (seeds > 0 and 0 < positive_selections <= seeds)) if ( metrics.get("selectedDepth") != 0 or selections.get("0", 0) <= 0 or metrics.get("rounds", 0) != 0 - or metrics.get("seedRows", 0) != 0 + or not seed_only_plans or metrics.get("proposedTokens", 0) != 0 or metrics.get("acceptedDraftTokens", 0) != 0 or metrics.get("committedTokens", 0) != 0 @@ -989,9 +1013,12 @@ def validate_report( validate_report_artifact(report.get("target"), target, "target") validate_report_artifact(report.get("assistant"), assistant, "assistant") - expected_purpose = ( - "raw_parity_stress" if mode == "raw-parity" else "production_performance" - ) + purposes = {"raw-parity": "raw_parity_stress", + "production-correctness": "production_correctness", + "production-performance": "production_performance"} + if mode not in purposes: + raise ValueError("unrecognized benchmark mode") + expected_purpose = purposes[mode] expected_stop = ( "raw_fixed_length_no_stop" if mode == "raw-parity" @@ -1005,10 +1032,10 @@ def validate_report( configured_stop_count = stop_policy.get("configuredTokenCount") if mode == "raw-parity" and configured_stop_count != 0: raise ValueError("raw parity report claims configured stop tokens") - if mode == "production-performance" and ( + if mode != "raw-parity" and ( not isinstance(configured_stop_count, int) or configured_stop_count <= 0 ): - raise ValueError("production performance report has no target EOS evidence") + raise ValueError("production report has no target EOS evidence") exposed_token_arrays = recursively_present_keys(report, {"tokenIDs"}) if exposed_token_arrays: raise ValueError("report recursively exposes raw token IDs") @@ -1104,7 +1131,7 @@ def validate_report( baseline_rows[batch] = row_evidence elif baseline_rows.get(batch) != row_evidence: raise ValueError(f"case {kind}/{width}/B{batch} opaque evidence differs from baseline") - if mode != "raw-parity": + if mode == "production-performance": if case.get("medianAggregateDecodeTokensPerSecond") is None: raise ValueError("production performance case omitted aggregate throughput") @@ -1155,13 +1182,8 @@ def validate_report( if depth > 0: if metrics.get("rounds", 0) <= 0 or metrics.get("proposedTokens", 0) <= 0: raise ValueError(f"fixed L{width}/B{batch} did not draft") - if not any( - item.get("decodeRowBucket") == expected_bucket - and item.get("draftDepth") == depth - and item.get("sampleCount", 0) > 0 - for item in metrics.get("costInputs", []) - if isinstance(item, dict) - ): + if not has_cost_or_verified_depth(metrics, expected_bucket, depth, exact=True, + require_cost=mode == "production-performance"): raise ValueError(f"fixed L{width}/B{batch} lacks depth/bucket cost evidence") elif kind == "adaptive": if expect_mtp_inactive: @@ -1196,13 +1218,8 @@ def validate_report( for depth, count in metrics.get("depthSelections", {}).items() ): raise ValueError(f"adaptive B{batch} never selected nonzero depth") - if not any( - item.get("decodeRowBucket") == expected_bucket - and item.get("draftDepth", 0) > 0 - and item.get("sampleCount", 0) > 0 - for item in metrics.get("costInputs", []) - if isinstance(item, dict) - ): + if not has_cost_or_verified_depth(metrics, expected_bucket, 1, exact=False, + require_cost=mode == "production-performance"): raise ValueError( f"adaptive B{batch} lacks positive-depth cost evidence for its requested bucket" ) @@ -1547,7 +1564,7 @@ def parse_arguments() -> argparse.Namespace: parser.add_argument("--max-tokens", type=int, default=16) parser.add_argument( "--mode", - choices=("raw-parity", "production-performance"), + choices=("raw-parity", "production-correctness", "production-performance"), default="raw-parity", help="raw parity recursively omits performance keys; performance requires release", ) @@ -1598,10 +1615,10 @@ def main() -> int: if args.self_test_artifact_provenance: return self_test_artifact_provenance() warmup = args.warmup if args.warmup is not None else ( - 0 if args.mode == "raw-parity" else 1 + 1 if args.mode == "production-performance" else 0 ) repetitions = args.repetitions if args.repetitions is not None else ( - 1 if args.mode == "raw-parity" else 3 + 3 if args.mode == "production-performance" else 1 ) if warmup < 0 or repetitions <= 0: raise SystemExit("--warmup must be nonnegative and --repetitions positive") diff --git a/scripts/test-mtp-metric-contracts.py b/scripts/test-mtp-metric-contracts.py new file mode 100644 index 0000000000..170b1ec02f --- /dev/null +++ b/scripts/test-mtp-metric-contracts.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""CPU-only regressions for executed MTP work versus retained cost learning.""" +from copy import deepcopy +import importlib.util +from pathlib import Path +import sys +import unittest + +spec = importlib.util.spec_from_file_location('mtp_supervisor', Path(__file__).with_name('run-mtp-benchmark.py')) +module = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = module +spec.loader.exec_module(module) + + +def seed_only(): + return dict(active=True, verificationMode='automatic', maxAutomaticRectangularTokens=8, + rectangularVerificationRounds=0, serialVerificationRounds=0, + selectedDepth=0, decodeRowBucket=8, rounds=0, seedRows=1, + proposedTokens=0, acceptedDraftTokens=0, committedTokens=0, + acceptanceByPosition=[], conditionalAcceptance=[], skippedRows={}, + depthSelections={'0': 127, '3': 1}, controllerFallbacks={'automatic_rectangular_limit': 127}, + costInputs=[], totalRoundWallTimeNanos=0) + + +class MetricContracts(unittest.TestCase): + def test_observed_seed_only_cap_fallback(self): + self.assertTrue(module.validate_automatic_fixed_fallback(seed_only(), 8, 3, 'observed')) + + def test_original_zero_seed_fallback(self): + value = seed_only() + value.update(seedRows=0, depthSelections={'0': 127}) + self.assertTrue(module.validate_automatic_fixed_fallback(value, 8, 3, 'zero')) + + def test_unexplained_seed_or_positive_plans_are_rejected(self): + for updates in [dict(seedRows=0), dict(depthSelections={'0': 127}), + dict(depthSelections={'0': 127, '3': 2}), dict(seedRows=-1), + dict(depthSelections={'bad': 1}), dict(depthSelections={'3': True})]: + value = seed_only(); value.update(updates) + with self.subTest(updates=updates), self.assertRaises(ValueError): + module.validate_automatic_fixed_fallback(value, 8, 3, 'invalid') + + def test_seed_does_not_excuse_speculative_residue(self): + for field in ['proposedTokens', 'acceptedDraftTokens', 'committedTokens', + 'rectangularVerificationRounds', 'serialVerificationRounds', + 'totalRoundWallTimeNanos']: + value = seed_only(); value[field] = 1 + with self.subTest(field=field), self.assertRaises(ValueError): + module.validate_automatic_fixed_fallback(value, 8, 3, 'residue') + + def test_fallback_reason_and_work_cap_remain_required(self): + value = seed_only(); value['controllerFallbacks'] = {} + with self.assertRaises(ValueError): + module.validate_automatic_fixed_fallback(value, 8, 3, 'missing reason') + value = seed_only() + value['costInputs'] = [dict(decodeRowBucket=8, draftDepth=1, sampleCount=1)] + with self.assertRaises(ValueError): + module.validate_automatic_fixed_fallback(value, 8, 3, 'over cap') + self.assertFalse(module.validate_automatic_fixed_fallback(seed_only(), 1, 3, 'inside cap')) + + def test_actual_clamped_rounds_still_pass(self): + value = seed_only() + value.update(rounds=2, proposedTokens=2, rectangularVerificationRounds=2, + selectedDepth=1, decodeRowBucket=4, depthSelections={'1': 2}) + self.assertTrue(module.validate_automatic_fixed_fallback(value, 4, 2, 'clamped')) + + def test_executed_work_without_retained_cost_is_correctness_only(self): + value = dict(rectangularVerificationRounds=8, serialVerificationRounds=0, + acceptanceByPosition=[7], costInputs=[]) + self.assertTrue(module.has_cost_or_verified_depth(value, 1, 1, exact=False, require_cost=False)) + self.assertFalse(module.has_cost_or_verified_depth(value, 1, 1, exact=False, require_cost=True)) + + def test_cost_exemption_requires_real_verification_and_requested_depth(self): + valid = dict(rectangularVerificationRounds=8, serialVerificationRounds=0, + acceptanceByPosition=[0, 0], costInputs=[]) + self.assertTrue(module.has_cost_or_verified_depth(valid, 1, 2, exact=True, require_cost=False)) + for updates in [dict(rectangularVerificationRounds=0), dict(acceptanceByPosition=[0]), + dict(rectangularVerificationRounds=-1), dict(serialVerificationRounds=False)]: + value = deepcopy(valid); value.update(updates) + with self.subTest(updates=updates): + self.assertFalse(module.has_cost_or_verified_depth(value, 1, 2, exact=True, require_cost=False)) + + def test_performance_cost_must_match_bucket_depth_and_samples(self): + value = dict(costInputs=[dict(decodeRowBucket=2, draftDepth=3, sampleCount=1)]) + self.assertTrue(module.has_cost_or_verified_depth(value, 2, 3, exact=True, require_cost=True)) + self.assertFalse(module.has_cost_or_verified_depth(value, 1, 3, exact=True, require_cost=True)) + self.assertFalse(module.has_cost_or_verified_depth(value, 2, 2, exact=True, require_cost=True)) + value['costInputs'][0]['sampleCount'] = 0 + self.assertFalse(module.has_cost_or_verified_depth(value, 2, 3, exact=True, require_cost=True)) + + +if __name__ == '__main__': + unittest.main()