From 917849fa4111db7678d2db3ba7455cd21057eb82 Mon Sep 17 00:00:00 2001 From: David Koski Date: Mon, 28 Sep 2026 14:03:47 -0700 Subject: [PATCH 1/2] adjustments for running tests on NAX/TF32 hardware --- .../AllowedToolOutputRouterTests.swift | 23 ++++- Tests/MLXLMTests/ContinuationAssertions.swift | 14 +-- .../MLXLMTests/GlmOcrContinuationTests.swift | 3 +- Tests/MLXLMTests/MatmulPrecision.swift | 91 +++++++++++++++++++ Tests/MLXLMTests/NanbeigeTests.swift | 2 +- .../MLXLMTests/Qwen35ContinuationTests.swift | 4 +- Tests/MLXLMTests/Qwen35MTPTests.swift | 15 ++- .../MLXLMTests/Qwen3VLContinuationTests.swift | 4 +- Tests/MLXLMTests/RoPEApplicationTests.swift | 17 ++-- Tests/MLXLMTests/SSMTests.swift | 15 ++- Tests/MLXLMTests/TurboQuantTests.swift | 4 +- 11 files changed, 162 insertions(+), 30 deletions(-) create mode 100644 Tests/MLXLMTests/MatmulPrecision.swift diff --git a/Tests/MLXFoundationModelsTests/AllowedToolOutputRouterTests.swift b/Tests/MLXFoundationModelsTests/AllowedToolOutputRouterTests.swift index 160e0d4225..78a9fe394c 100644 --- a/Tests/MLXFoundationModelsTests/AllowedToolOutputRouterTests.swift +++ b/Tests/MLXFoundationModelsTests/AllowedToolOutputRouterTests.swift @@ -26,6 +26,21 @@ struct AllowedToolOutputRouterTests { return rejection.reason } + /// The text of `events`, or `nil` if any of them is not a response. + /// + /// The router flushes the text before a possible marker and only later decides whether the + /// marker was real so ordinary tag-like text can arrive as more than one response event. + /// Where a test is about text surviving intact rather than about where the stream was cut, + /// join the events and compare that + private func responseText(_ events: [AllowedToolOutputRouter.Event]) -> String? { + var text = "" + for event in events { + guard case .response(let chunk) = event else { return nil } + text += chunk + } + return text + } + @Test func plainTextRemainsAResponse() { var router = AllowedToolOutputRouter(format: .json, tools: tools) #expect(router.process("Hello") == [.response("Hello")]) @@ -271,10 +286,10 @@ struct AllowedToolOutputRouterTests { @Test func ordinaryTagLikeTextRemainsAResponse() { var jsonRouter = AllowedToolOutputRouter(format: .json, tools: tools) #expect( - jsonRouter.process("Use for layout") == [.response("Use
for layout")]) + responseText(jsonRouter.process("Use
for layout")) == "Use
for layout") var mistralRouter = AllowedToolOutputRouter(format: .mistral, tools: tools) - #expect(mistralRouter.process("[Today] is sunny") == [.response("[Today] is sunny")]) + #expect(responseText(mistralRouter.process("[Today] is sunny")) == "[Today] is sunny") } @Test func malformedProtocolSuppressesOnlyTheMarkerSpan() { @@ -366,8 +381,8 @@ struct AllowedToolOutputRouterTests { @Test func nearProtocolMarkersSuppressWithoutStrippingOrdinaryTags() { var ordinaryRouter = AllowedToolOutputRouter(format: .json, tools: tools) #expect( - ordinaryRouter.process("Use and labels") - == [.response("Use and labels")]) + responseText(ordinaryRouter.process("Use and labels")) + == "Use and labels") var partialRouter = AllowedToolOutputRouter(format: .json, tools: tools) #expect(partialRouter.process("before 1e-5 + + /// Relative difference between a GPU and a CPU float32 matmul of the same inputs. + static let relativeMatmulError: Float = { + let a = withRandomState(MLXRandom.RandomState(seed: 0)) { MLXRandom.normal([64, 512]) } + let b = withRandomState(MLXRandom.RandomState(seed: 1)) { MLXRandom.normal([512, 64]) } + let gpu = matmul(a, b, stream: .gpu) + let cpu = matmul(a, b, stream: .cpu) + return abs(gpu - cpu).max().item(Float.self) / abs(cpu).max().item(Float.self) + }() + + /// A tolerance sized for IEEE float32, and the value to use instead when this machine + /// computes float32 matmuls as TF32. + /// + /// Two explicit numbers rather than one scale factor: what reduced precision costs a + /// comparison depends on how many matmuls feed it and whether the difference is relative + /// or absolute, so each call site states what it measured rather than inheriting a guess. + static func tolerance(float32: Double, reduced: Double) -> Double { + isReducedFloat32 ? reduced : float32 + } + + static func tolerance(float32: Float, reduced: Float) -> Float { + isReducedFloat32 ? reduced : float32 + } + + /// The bound for asserting that two executions of the same prompt produce the same logits. + /// + /// `1e-3` is what these tests have always used, and it stays exactly that on hardware + /// that computes float32 matmuls in float32. TF32 raises the noise of splitting a forward + /// to a few times 1e-3; 2e-2 clears that with margin while staying far below the O(1) + /// shift a real positioning error produces. + static let splitTolerance: Float = tolerance(float32: 1e-3, reduced: 2e-2) +} + +final class MatmulPrecisionTests: XCTestCase { + + /// The probe decides how strict every tolerance derived from it is, so check it on every + /// machine rather than only on the rare one that sets `MLX_ENABLE_TF32=0`. + /// + /// What can be asserted anywhere is that the measurement is unambiguous: float32 lands near + /// 1e-7 and TF32 near 1e-3, so a reading between 1e-5 and 1e-4 means the two regimes are no + /// longer cleanly separated and the threshold needs a human. On pre-M5 hardware — CI, and + /// most developer machines — this is the assertion that catches a probe that has started + /// reporting reduced precision and quietly loosening every bound. + /// + /// There is no converse check that accelerator hardware *must* measure as reduced: nothing + /// exposes "this GPU has neural accelerators", and MLX is free to change when it uses them. + func testPrecisionProbeLandsClearlyInOneRegime() { + let error = MatmulPrecision.relativeMatmulError + XCTAssertTrue( + error < 1e-5 || error > 1e-4, + """ + float32 matmul relative error \(error) falls between the float32 (~1e-7) and \ + TF32 (~1e-3) regimes; MatmulPrecision.isReducedFloat32 can no longer tell them apart + """) + + // When TF32 is disabled the answer is known, whatever the hardware. + if ProcessInfo.processInfo.environment["MLX_ENABLE_TF32"] == "0" { + XCTAssertFalse( + MatmulPrecision.isReducedFloat32, + "float32 matmuls measured as reduced precision despite MLX_ENABLE_TF32=0") + } + } +} diff --git a/Tests/MLXLMTests/NanbeigeTests.swift b/Tests/MLXLMTests/NanbeigeTests.swift index a37af0b0c5..2a2028133e 100644 --- a/Tests/MLXLMTests/NanbeigeTests.swift +++ b/Tests/MLXLMTests/NanbeigeTests.swift @@ -217,7 +217,7 @@ final class NanbeigeTests: XCTestCase { let logitsW = try prefillLogits(model, t2, cache: cacheW) XCTAssertLessThanOrEqual( - maxAbsDiff(logitsW, logitsF), 1e-3, + maxAbsDiff(logitsW, logitsF), MatmulPrecision.splitTolerance, "warm continuation diverged from cold full prefill") } diff --git a/Tests/MLXLMTests/Qwen35ContinuationTests.swift b/Tests/MLXLMTests/Qwen35ContinuationTests.swift index 3fc5b66865..929a4666c6 100644 --- a/Tests/MLXLMTests/Qwen35ContinuationTests.swift +++ b/Tests/MLXLMTests/Qwen35ContinuationTests.swift @@ -127,7 +127,7 @@ final class Qwen35ContinuationTests: XCTestCase { prefill: .init())) XCTAssertLessThanOrEqual( - maxAbsDiff(warmLogits, fullLogits), 1e-3, + maxAbsDiff(warmLogits, fullLogits), MatmulPrecision.splitTolerance, "rank-1 warm continuation diverged from full prefill") } } @@ -262,7 +262,7 @@ final class Qwen35ContinuationTests: XCTestCase { maxAbsDiff(restoredImageLogits, warmImageLogits), 1e-6, "disk-restored state diverged when a later turn added another image") XCTAssertLessThanOrEqual( - maxAbsDiff(restoredImageLogits, coldLogits), 1e-3, + maxAbsDiff(restoredImageLogits, coldLogits), MatmulPrecision.splitTolerance, "restored two-image continuation diverged from full prefill") } } diff --git a/Tests/MLXLMTests/Qwen35MTPTests.swift b/Tests/MLXLMTests/Qwen35MTPTests.swift index afb7f68261..c9a23c5787 100644 --- a/Tests/MLXLMTests/Qwen35MTPTests.swift +++ b/Tests/MLXLMTests/Qwen35MTPTests.swift @@ -111,6 +111,10 @@ func testQwen35MTPDraftInstantiatesDedicatedEmbeddingWhenConfigured() throws { #expect(sanitized["model.embed_tokens.weight"] == nil) } +/// Bound for comparing a gated-delta-net state reached two ways. Wider on machines whose +/// float32 matmuls run as TF32; see ``MatmulPrecision``. +private let gdnStateTolerance = MatmulPrecision.tolerance(float32: 1e-5, reduced: 2e-3) + @Suite(.serialized) struct Qwen35MTPMetalTests { @Test @@ -318,7 +322,12 @@ struct Qwen35MTPMetalTests { #expect(restored.count == expected.count) for (actual, reference) in zip(restored, expected) { eval(actual, reference) - #expect(allClose(actual, reference, rtol: 1e-5, atol: 1e-5).item(Bool.self)) + // The checkpoint and the prefix run reach the same state through + // differently shaped matmuls, so the bound follows the machine's + // float32 matmul precision; see MatmulPrecision. + #expect( + allClose(actual, reference, rtol: gdnStateTolerance, atol: gdnStateTolerance) + .item(Bool.self)) } } @@ -342,7 +351,9 @@ struct Qwen35MTPMetalTests { #expect(speculativeCache.restoreSpeculativeCheckpoint()) for (actual, reference) in zip(speculativeCache.state, prefixCache.state) { eval(actual, reference) - #expect(allClose(actual, reference, rtol: 1e-5, atol: 1e-5).item(Bool.self)) + #expect( + allClose(actual, reference, rtol: gdnStateTolerance, atol: gdnStateTolerance) + .item(Bool.self)) } } diff --git a/Tests/MLXLMTests/Qwen3VLContinuationTests.swift b/Tests/MLXLMTests/Qwen3VLContinuationTests.swift index b264d992b2..96c2730dca 100644 --- a/Tests/MLXLMTests/Qwen3VLContinuationTests.swift +++ b/Tests/MLXLMTests/Qwen3VLContinuationTests.swift @@ -135,7 +135,7 @@ final class Qwen3VLContinuationTests: XCTestCase { prefill: .init())) XCTAssertLessThanOrEqual( - maxAbsDiff(warmLogits, fullLogits), 1e-3, + maxAbsDiff(warmLogits, fullLogits), MatmulPrecision.splitTolerance, "rank-1 warm continuation diverged from full prefill") } } @@ -231,7 +231,7 @@ final class Qwen3VLContinuationTests: XCTestCase { model.prepare(input, cache: windowedCache, state: nil, prefill: .init(stepSize: 8))) XCTAssertLessThanOrEqual( - maxAbsDiff(windowedLogits, singleLogits), 1e-3, + maxAbsDiff(windowedLogits, singleLogits), MatmulPrecision.splitTolerance, "padding changed Qwen3-VL windowed M-RoPE semantics") } } diff --git a/Tests/MLXLMTests/RoPEApplicationTests.swift b/Tests/MLXLMTests/RoPEApplicationTests.swift index 05aa3d08f6..b4548b495b 100644 --- a/Tests/MLXLMTests/RoPEApplicationTests.swift +++ b/Tests/MLXLMTests/RoPEApplicationTests.swift @@ -47,13 +47,18 @@ struct RoPEApplicationTests { eval(outputSeq) // With correct RoPE these would match. The buggy code would use - // different offsets for keys/queries. - let match = allClose(outputBatch, outputSeq, atol: 1e-4) + // different offsets for keys/queries. The tolerance is wider on + // machines whose float32 matmuls run as TF32; see MatmulPrecision. + let match = allClose( + outputBatch, outputSeq, + atol: MatmulPrecision.tolerance(float32: 1e-4, reduced: 5e-3)) eval(match) - print(outputBatch) - print(outputSeq) - print(abs(outputSeq - outputBatch)) - #expect(match.item(Bool.self)) + #expect( + match.item(Bool.self), + """ + batch and sequential attention differ by up to \ + \(abs(outputSeq - outputBatch).max().item(Float.self)) + """) } } } diff --git a/Tests/MLXLMTests/SSMTests.swift b/Tests/MLXLMTests/SSMTests.swift index bdf4e0f35a..8d34a1fa32 100644 --- a/Tests/MLXLMTests/SSMTests.swift +++ b/Tests/MLXLMTests/SSMTests.swift @@ -4,9 +4,15 @@ import MLX import MLXLLM import Testing +/// Compare two float32 results that differ only in how the work was split. +/// +/// The tolerances are wider on machines whose float32 matmuls run as TF32 — see +/// ``MatmulPrecision``. The message reports the worst element so a failure says how far off it +/// was, not just that it was. private func expectAllClose( - _ actual: MLXArray, _ expected: MLXArray, label: String, rtol: Double = 1e-4, - atol: Double = 1e-5 + _ actual: MLXArray, _ expected: MLXArray, label: String, + rtol: Double = MatmulPrecision.tolerance(float32: 1e-4, reduced: 5e-3), + atol: Double = MatmulPrecision.tolerance(float32: 1e-5, reduced: 5e-4) ) { guard actual.shape == expected.shape else { Issue.record("\(label) shape \(actual.shape) != \(expected.shape)") @@ -14,7 +20,7 @@ private func expectAllClose( } #expect( allClose(actual, expected, rtol: rtol, atol: atol).item(Bool.self), - "\(label) values differ") + "\(label) values differ by up to \(MLX.abs(actual - expected).max().item(Float.self))") } @Test func testSSMAttnChunkedMatchesUnchunkedValuesAndGradients() { @@ -81,7 +87,8 @@ private func expectAllClose( for (index, pair) in zip(chunkedGradients, referenceGradients).enumerated() { expectAllClose( pair.0, pair.1, label: "\(gradientLabels[index]) gradient (step \(step))", - rtol: 5e-4, atol: 5e-5) + rtol: MatmulPrecision.tolerance(float32: 5e-4, reduced: 5e-3), + atol: MatmulPrecision.tolerance(float32: 5e-5, reduced: 5e-4)) } } } diff --git a/Tests/MLXLMTests/TurboQuantTests.swift b/Tests/MLXLMTests/TurboQuantTests.swift index 38e385ade2..5547acf526 100644 --- a/Tests/MLXLMTests/TurboQuantTests.swift +++ b/Tests/MLXLMTests/TurboQuantTests.swift @@ -206,7 +206,9 @@ struct TurboQuantMSECodecTests { let product = matmul(codec.rotation, codec.rotationT) let identity = MLXArray.identity(128) let diff = MLX.abs(product - identity).max().item(Float.self) - #expect(diff < 1e-4, "WHT rotation should be orthogonal, max diff: \(diff)") + // TF32 matmuls (neural accelerators) leave ~2e-4 here; see MatmulPrecision. + let tolerance: Float = MatmulPrecision.tolerance(float32: 1e-4, reduced: 1e-3) + #expect(diff < tolerance, "WHT rotation should be orthogonal, max diff: \(diff)") } @Test func whtEncodeDecodeRoundTrip() { From 0669cdce56f0f6ab6b90d8780327c4b8b5076546 Mon Sep 17 00:00:00 2001 From: David Koski <46639364+davidkoski@users.noreply.github.com> Date: Wed, 30 Sep 2026 11:14:16 -0700 Subject: [PATCH 2/2] Apply suggestion from @nwh Co-authored-by: Nick Henderson <525247+nwh@users.noreply.github.com> --- Tests/MLXLMTests/TurboQuantTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/MLXLMTests/TurboQuantTests.swift b/Tests/MLXLMTests/TurboQuantTests.swift index 5547acf526..415d64fdd8 100644 --- a/Tests/MLXLMTests/TurboQuantTests.swift +++ b/Tests/MLXLMTests/TurboQuantTests.swift @@ -203,7 +203,7 @@ struct TurboQuantMSECodecTests { let codec = MSECodec(dim: 128, bits: 3, seed: 42) #expect(codec.useWHT, "dim=128 should use WHT") - let product = matmul(codec.rotation, codec.rotationT) + let product = matmul(codec.rotation, codec.rotationT, stream: .cpu) let identity = MLXArray.identity(128) let diff = MLX.abs(product - identity).max().item(Float.self) // TF32 matmuls (neural accelerators) leave ~2e-4 here; see MatmulPrecision.