Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
23 changes: 19 additions & 4 deletions Tests/MLXFoundationModelsTests/AllowedToolOutputRouterTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe mention in PR description that this fix is unrelated to TF32

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good idea

@Test func plainTextRemainsAResponse() {
var router = AllowedToolOutputRouter(format: .json, tools: tools)
#expect(router.process("Hello") == [.response("Hello")])
Expand Down Expand Up @@ -271,10 +286,10 @@ struct AllowedToolOutputRouterTests {
@Test func ordinaryTagLikeTextRemainsAResponse() {
var jsonRouter = AllowedToolOutputRouter(format: .json, tools: tools)
#expect(
jsonRouter.process("Use <table> for layout") == [.response("Use <table> for layout")])
responseText(jsonRouter.process("Use <table> for layout")) == "Use <table> 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() {
Expand Down Expand Up @@ -366,8 +381,8 @@ struct AllowedToolOutputRouterTests {
@Test func nearProtocolMarkersSuppressWithoutStrippingOrdinaryTags() {
var ordinaryRouter = AllowedToolOutputRouter(format: .json, tools: tools)
#expect(
ordinaryRouter.process("Use <toolbar> and <tool> labels")
== [.response("Use <toolbar> and <tool> labels")])
responseText(ordinaryRouter.process("Use <toolbar> and <tool> labels"))
== "Use <toolbar> and <tool> labels")

var partialRouter = AllowedToolOutputRouter(format: .json, tools: tools)
#expect(partialRouter.process("before <tool_cal") == [.response("before ")])
Expand Down
14 changes: 7 additions & 7 deletions Tests/MLXLMTests/ContinuationAssertions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ struct ContinuationAssertions {
let (logitsW, _) = try prefill(model, t2, cache: cacheW, state: s1)

XCTAssertLessThanOrEqual(
maxAbsDiff(logitsW, logitsF), max(noiseFloor * 10, 1e-3),
maxAbsDiff(logitsW, logitsF), max(noiseFloor * 10, MatmulPrecision.splitTolerance),
"warm continuation diverged from full prefill (noise floor \(noiseFloor))",
file: file, line: line)
}
Expand All @@ -139,7 +139,7 @@ struct ContinuationAssertions {
let (logitsW, _) = try prefill(model, t2, cache: cacheW, state: s1)

XCTAssertLessThanOrEqual(
maxAbsDiff(logitsW, logitsF), 1e-3,
maxAbsDiff(logitsW, logitsF), MatmulPrecision.splitTolerance,
"state-threaded warm continuation diverged from full prefill",
file: file, line: line)
}
Expand Down Expand Up @@ -196,11 +196,11 @@ struct ContinuationAssertions {
let diff = maxAbsDiff(logitsW, logitsF)
if expectsIsolation {
XCTAssertLessThanOrEqual(
diff, 1e-3,
diff, MatmulPrecision.splitTolerance,
"split-suffix prefill diverged from full prefill", file: file, line: line)
} else {
XCTAssertGreaterThan(
diff, 1e-3,
diff, MatmulPrecision.splitTolerance,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't have M5, so can't verify this. Claude thinks TF32 noise might trigger a failure here:

  • When expectsIsolation == false (Qwen2VL), the test asserts diff > splitTolerance. So on TF32
    the required divergence rose from 1e-3 to 2e-2.
  • On M4 (float32), the real cross-image effect in Qwen25VLContinuationTests measures
    0.0468. That leaves only about 2.3× headroom over 2e-2, and TF32 noise can move diff either
    way.
  • Tightening is the right direction: at 1e-3, TF32 noise (~3e-3) could satisfy the check by
    itself. But the cutoff here should be "clearly above noise", not "the equality tolerance".
  • Suggestions:
    • Use a dedicated lower bound, e.g. tolerance(float32: 1e-3, reduced: 1e-2).
    • Or, better, compare against a measured noise floor, as assertWarmTextContinuation already does.
    • At minimum, add the measured value to the failure message.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW the tests do pass on both M4 and M5. The value shouldn't need to be added to the message -- the assert output will already include that.

"cross-image vision attention should have changed the logits",
file: file, line: line)
}
Expand Down Expand Up @@ -230,7 +230,7 @@ struct ContinuationAssertions {
let (logitsW, _) = try prefill(model, t3, cache: cacheW, state: s2)

XCTAssertLessThanOrEqual(
maxAbsDiff(logitsW, logitsF), 1e-3,
maxAbsDiff(logitsW, logitsF), MatmulPrecision.splitTolerance,
"post-image resume state positioned the following turn wrong",
file: file, line: line)
}
Expand All @@ -250,7 +250,7 @@ struct ContinuationAssertions {
let (logitsC, _) = try prefill(model, prompt, cache: cacheC, stepSize: 8)

XCTAssertLessThanOrEqual(
maxAbsDiff(logitsC, logitsS), 1e-3,
maxAbsDiff(logitsC, logitsS), MatmulPrecision.splitTolerance,
"windowed prefill diverged from single-shot", file: file, line: line)
}
}
Expand Down Expand Up @@ -280,7 +280,7 @@ struct ContinuationAssertions {
model, prompt, image: image, cache: cacheC, stepSize: stepSize)

XCTAssertLessThanOrEqual(
maxAbsDiff(logitsC, logitsS), 1e-3,
maxAbsDiff(logitsC, logitsS), MatmulPrecision.splitTolerance,
"windowed image prefill diverged from single-shot at stepSize \(stepSize)",
file: file, line: line)
}
Expand Down
3 changes: 2 additions & 1 deletion Tests/MLXLMTests/GlmOcrContinuationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,8 @@ final class GlmOcrContinuationTests: XCTestCase {
let decodeW = model(LMInput.Text(tokens: next), cache: cacheW, state: s2)

XCTAssertLessThanOrEqual(
maxAbsDiff(decodeW.logits[0..., -1, 0...], decodeF.logits[0..., -1, 0...]), 1e-3,
maxAbsDiff(decodeW.logits[0..., -1, 0...], decodeF.logits[0..., -1, 0...]),
MatmulPrecision.splitTolerance,
"decode after a warm continuation ignored the carried anchor")
}
}
Expand Down
91 changes: 91 additions & 0 deletions Tests/MLXLMTests/MatmulPrecision.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// Copyright © 2026 Apple Inc.

import Foundation
import MLX
import XCTest

/// The precision MLX uses for float32 matmuls on the machine running the tests, measured once.
///
/// On hardware with neural accelerators (M5 and later) MLX runs float32 matmuls as TF32 unless
/// `MLX_ENABLE_TF32=0`. That costs about three decimal digits, which matters for every test
/// that computes one prompt two ways — whole against windowed, cold against warm — and asserts
/// the logits agree. Those differences are ~1e-6 with IEEE float32 and ~3e-3 with TF32, so a
/// fixed bound sized for one machine fails on the other for reasons that have nothing to do
/// with the code under test.
///
/// Pinning `MLX_ENABLE_TF32=0` for the test process would remove the variable, but it would
/// also stop testing the path that ships by default on current hardware, and it is read once
/// per process at MLX's first use, so it would have to be set before any test runs. Measure
/// instead.
enum MatmulPrecision {

/// True when float32 matmuls lose precision (TF32 on the neural accelerators).
///
/// Measured rather than inferred from the device or `MLX_ENABLE_TF32`: the same float32
/// inputs are multiplied on the GPU and on the CPU, which always uses IEEE float32. The
/// gap is ~1e-7 relative when the GPU does the same, and ~1e-3 when it uses TF32 — three
/// orders of magnitude apart, so the threshold between them needs no tuning.
static let isReducedFloat32: Bool = relativeMatmulError > 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")
}
}
}
2 changes: 1 addition & 1 deletion Tests/MLXLMTests/NanbeigeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}

Expand Down
4 changes: 2 additions & 2 deletions Tests/MLXLMTests/Qwen35ContinuationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
Expand Down Expand Up @@ -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")
}
}
Expand Down
15 changes: 13 additions & 2 deletions Tests/MLXLMTests/Qwen35MTPTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))
}
}

Expand All @@ -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))
}
}

Expand Down
4 changes: 2 additions & 2 deletions Tests/MLXLMTests/Qwen3VLContinuationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
Expand Down Expand Up @@ -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")
}
}
Expand Down
17 changes: 11 additions & 6 deletions Tests/MLXLMTests/RoPEApplicationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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))
""")
}
}
}
15 changes: 11 additions & 4 deletions Tests/MLXLMTests/SSMTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,23 @@ 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)")
return
}
#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() {
Expand Down Expand Up @@ -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))
}
}
}
Expand Down
6 changes: 4 additions & 2 deletions Tests/MLXLMTests/TurboQuantTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -203,10 +203,12 @@ 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)
#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() {
Expand Down
Loading