Test iOS matrix multiplication layout and strides on a cloud Mac
If the same batch of image features produces correct results locally but entire columns are misaligned in iOS regression tests on a cloud Mac, check the memory layout before relaxing floating-point tolerances. Accelerate’s matrix multiplication takes pointers to contiguous storage; it has no way to know how many rows and columns those arrays represent in your application. The caller must specify the dimensions, transpose flags, and strides.
The runnable fixture below uses rectangular matrices. First, verify it from the remote command line, then move its assertions into the application’s test target. It requires no network access, signing, or training data, making it suitable for checking your numerical wrapper before each regression run.
Define the contract
The function under test is cblas_sgemm, which computes C = alpha × op(A) × op(B) + beta × C. Start by fixing the layout as row-major: elements within a row are contiguous, but padding may separate successive rows.
Use the logical dimensions A: 2×3, B: 3×2, and C: 2×2. Choose distinct elements so that an identity matrix cannot mask a transpose error. The inputs are [1,2,3;4,5,6] and [7,8;9,10;11,12], with the expected product [58,64;139,154].
Here, the leading dimension is the physical storage stride, measured in elements, not bytes. For row-major storage without transposition, lda must be at least K, while ldb and ldc must be at least N. Once padding is added, pass the actual row stride rather than the number of active columns.
Correct numerical results and correct buffer boundaries are separate acceptance criteria. Check not only the active cells, but also that the output padding remains untouched.
Run the fixture
On a cloud Mac with the command-line tools installed, save the following as matrix-check.swift. The script uses Accelerate on the host to establish that the test data, reference results, and pointer-based call agree.
import Accelerate
import Foundation
func verify(transposeA: Bool) {
let padding: Float = -777
let a: [Float] = transposeA
? [1, 4, padding, 2, 5, padding, 3, 6, padding]
: [1, 2, 3, padding, 4, 5, 6, padding]
let b: [Float] = [
7, 8, padding,
9, 10, padding,
11, 12, padding
]
var c: [Float] = [
1, 1, padding, padding,
1, 1, padding, padding
]
a.withUnsafeBufferPointer { ap in
b.withUnsafeBufferPointer { bp in
c.withUnsafeMutableBufferPointer { cp in
cblas_sgemm(
CblasRowMajor,
transposeA ? CblasTrans : CblasNoTrans,
CblasNoTrans,
2, 2, 3,
2,
ap.baseAddress!, transposeA ? 3 : 4,
bp.baseAddress!, 3,
3,
cp.baseAddress!, 4
)
}
}
}
let expected: [Float] = [119, 131, 281, 311]
let indices = [0, 1, 4, 5]
for (index, value) in zip(indices, expected) {
let actual = c[index]
let tolerance: Float = 0.00001 + 0.00001 * abs(value)
precondition(actual.isFinite, "Non-finite result")
precondition(abs(actual - value) <= tolerance, "Value mismatch")
}
for index in [2, 3, 6, 7] {
precondition(c[index] == padding, "Padding modified")
}
}
verify(transposeA: false)
verify(transposeA: true)
Preserve the actual exit status when running it:
set -euo pipefail
xcrun swiftc -Onone matrix-check.swift -o matrix-check
./matrix-check
A successful run produces no output; a failed assertion causes a nonzero exit status. This first build deliberately disables optimization to make call-related issues easier to diagnose. Repeat the checks with a release configuration afterward.
Check transposition
The second invocation changes A’s physical storage to 3×2, then transposes it to obtain the logical 2×3 matrix. M, N, and K therefore stay the same, but lda changes from 4 to 3: each physical row contains two values and one padding element.
Do not change only the transpose flag while keeping the original array. That computes with a different set of inputs, so a mismatched result does not by itself indicate a library bug. Likewise, do not switch from row-major to column-major storage and copy the same strides: the two layouts give those strides different physical meanings.
The example also sets alpha=2 and beta=3, with output cells initially set to 1, so the first result must be 2×58+3×1=119. This catches wrappers that fail to pass beta, incorrectly zero C, or repeatedly accumulate previous results.
When extending the cases, cover transposed B, zero alpha, and both zero-beta and nonzero-beta accumulation branches. When beta is zero, assert only that the active output does not depend on C’s previous values; do not infer which internal optimization path the library takes.
Guard buffer boundaries
A production wrapper should reject invalid parameters before entering the pointer closures: negative dimensions, insufficient strides, arrays that are too short, and dimensions that cannot be safely converted to the library’s integer type.
A nonempty row-major buffer needs at least (physical rows−1)×stride+active columns elements. Use integer arithmetic with overflow reporting for the multiplication and addition checks, so the validation expression itself cannot overflow first. Define return behavior separately for empty matrices to avoid force-unwrapping pointers to empty arrays.
Inputs and outputs must not share writable storage. Use Swift array pointers only within their corresponding closures, and do not retain them for asynchronous tasks. Tests should also compare the input arrays before and after the call to confirm that the application’s wrapper has not modified them beforehand.
Sentinels detect overwrites only at the positions being checked; they are not a complete proof of memory safety. Debug tests should also enable memory checking and cover minimum dimensions, tightly packed strides, and padded strides.
Integrate into regression tests
When moving the fixture into the iOS test target, make it call the matrix wrapper the application actually uses, and replace precondition with test assertions. Keep the host script as an independent control for ruling out conversion issues in the application layer.
The test matrix should cover at least rectangular matrices, transposed A, transposed B, output padding, nonzero beta, and rejection of insufficient buffer capacity. Random samples can be checked against a triple-loop reference implementation, but that implementation must not reuse the wrapper’s indexing function; otherwise, the same error could make both implementations appear to agree.
Combine absolute and relative tolerances for floating-point comparisons, rejecting non-finite values first. Do not require bit-for-bit equality across execution environments, and do not use loose tolerances to accept entire rows being out of place.
For each run, record the code commit, toolchain version, execution target, and failing inputs. Get the fixed fixture passing before increasing the sample count. That way, a failure can identify which layout contract was violated rather than merely reporting a numerical difference that cannot be reproduced.
Frequently asked questions
Why are identity matrices and square matrices insufficient?
Symmetry and equal dimensions can hide swapped axes, incorrect transpose flags and bad strides. Use rectangular matrices with distinct values and padding, then check both the computed cells and untouched padding.
Does the Mac command-line test replace simulator testing?
No. It validates the reference fixture and host-side call. Run the same assertions in the iOS test target to exercise the production wrapper, data conversions and buffer lifetime.
Rent a Mac for your testing cycle
Choose a dedicated physical Mac mini and rent by the day, week, month, or quarter. Your rental stops when it expires—no automatic renewal or charges.