SMT-Based Translation Validation for Machine Learning Compiler
Paper · 2022 · Seongwon Bang, Nam SeungHyeon, Inwhan Chun et al.
Summary
A compiler can make a tensor program faster by changing how its data is laid out, combining operations into a single loop, or replacing intermediate tensors with writes to memory. Each change also creates an opportunity to alter the result. The paper presents mlir-tv, a tool that checks what happened in one compilation by comparing the program before and after a pass. It works on Multi-Level Intermediate Representation, or MLIR, a framework in which successive forms of a program can express anything from a convolution to a loop over a buffer. The authors focus on changes inside individual functions and on passes that are independent of the eventual hardware target.
The tool represents both functions and their shared inputs as logical expressions. A solver then looks for an input on which the compiled function violates a requirement imposed by the original. Tensor programs make this search expensive, especially when it involves floating-point arithmetic or reductions such as summing a tensor. Mlir-tv starts with an abstraction that leaves many arithmetic details open while retaining properties needed for the check. If the solver cannot find a failure even with that added freedom, the transformation passes under the encoded semantics. If the first attempt fails or times out, the tool can retry with a more detailed encoding. The authors also introduce a symbolic hash encoding for reductions whose order or grouping may legally change under relaxed arithmetic rules.
On 57 function pairs written to check the validator, the authors report that abstract floating-point encoding was 13.6x faster on average than concrete IEEE-754 encoding. In the official MLIR unit-test corpus, which contained 2,467 function pairs, mlir-tv validated 433 tests, timed out on 8, and failed on 8. The investigation exposed discrepancies involving signed zero, special floating-point values, and the rules for read-only buffers. The authors report a correction to a signed-zero rewrite and a clarification to the documentation for buffer cloning.
The authors also checked a sequence of compilation passes on text_classification_v2, SqueezeNet, and MobileNet after splitting the programs into small functions and adjusting the handling of zero for certain operations. Every tested pass validated for text_classification_v2. Unsupported operations prevented validation of the final passes for SqueezeNet and MobileNet. These results establish what the checker could prove about the tested transformations under its arithmetic, memory, and input assumptions. They also show how a failed check can help locate a disagreement between compiler code and the rules the compiler is expected to follow.
Deep dive: SMT-Based Translation Validation for Machine Learning Compiler
How mlir-tv uses SMT solving to check whether compiler passes preserve the behavior of tensor programs as they are rewritten in MLIR. · about 40 minutes to read
The problem and its context
What a compiler pass has to preserve
A compiler for machine learning starts with operations that describe what to compute over arrays of values. A convolution, for instance, names a whole computation over tensors in a single operation. The compiler gradually replaces that description with operations closer to what hardware can execute. Along the way it can choose a different layout for the data, fuse loops to reuse nearby values, or replace temporary tensors with accesses to allocated storage. The resulting instructions can bear little resemblance to the original expression even when they compute the same result.
A compiler pass can therefore succeed at producing a well-formed program and still make a semantic mistake. A loop can read an element from the wrong location. A rewrite can preserve the usual cases of an arithmetic operation while changing its behavior at a special value. A pass can keep every arithmetic operation intact and still introduce a write to a buffer that the original was allowed only to read. The consequences range from a crash to a change in prediction accuracy or performance that occurs without an obvious failure.
The authors locate their work within a particular part of code and programming languages: the rules of the intermediate language used between passes. An intermediate representation, abbreviated IR, is the form in which a compiler records a program while it is working on it. XLA, Glow, and MLIR are examples of projects the paper describes as changing frequently. Their IRs serve internal compiler needs, and their documentation can leave some cases unspecified. A correctness argument therefore needs to keep up with changes in the passes and with changes in what their input and output operations are understood to mean.
The paper discusses a compiler-bug survey that identifies high-level IR transformations as a frequent source of problems and emphasizes the difficulty of detecting wrong code generation. The level of a transformation matters to how one can check it. At a high level, the IR may say which tensor coordinate a loop reads and whether iterations can run independently. At a lower level, those facts can be distributed across loop counters, address calculations, and memory operations. Mlir-tv takes advantage of the information still present in the higher-level operations.
Why check the programs before and after a pass?
Translation validation is the practice of checking a particular translation by inspecting its input and output. The “translation” here is between forms of computer code. Given a function before a pass and the corresponding function after it, mlir-tv asks whether the latter preserves behavior under the rules encoded for both. A compiler can continue to introduce and revise passes as long as the validator can interpret their output. The authors' tool works from the two programs and receives no annotation identifying the transformation the compiler performed.
The paper describes earlier work along both the compiler-verification and translation-validation routes. Icing gives a language a way to express floating-point optimizations that strict arithmetic would forbid, and CakeML provides a verified compiler in that line of work. An earlier verified tensor optimizer lets users explore optimizations through Coq tactics. Those projects address how to establish correctness for the optimization process itself. Mlir-tv's proof obligation instead arises anew from each pair of functions.
The authors also discuss a translation validator for Halide, a language for array processing. Its treatment of fast arithmetic relies mainly on Z3's theory of real numbers. For lower-level LLVM transformations, they name Alive2, LLVM-MD, and Peggy as validators that use different techniques. The encoding of memory in Alive2 is especially relevant because mlir-tv uses a related analysis to bound the number of memory blocks it must represent. The paper also points to previous validators that check smaller program pairs after splitting a larger problem.
Previous work on floating-point verification addressed several different questions. Some approaches use abstract interpretation, SMT solving, or computer algebra to estimate rounding error. Others formalize floating-point arithmetic in a theorem prover. For solvers, techniques discussed in the paper include using approximate arithmetic domains and translating floating-point operations into bit-level expressions. These approaches inform the choice facing mlir-tv. A validator has to decide how much of the arithmetic to expose to the solver when the immediate question might be whether a pass moved an unchanged calculation to the right place.
Work on arrays offered another set of choices. The paper mentions solvers that express reads and writes using functions and array axioms, as well as approaches that use constrained Horn clauses or induction to reason about loops. Induction can establish a property that must hold throughout the execution of a loop. MLIR's structured tensor loops already expose bounds, index mappings, and iteration types, so the authors can often give the solver an expression for an output element directly. That opportunity is specific to operations with enough structure for the encoding.
Why MLIR makes the problem tractable and difficult
MLIR divides its operations and types into dialects. A dialect defines a part of the intermediate language, and a single function can use operations from several dialects. Tensor and TOSA operations can describe values and computations common in neural networks. The linalg dialect can express structured computations over tensors and buffers. Memory-reference operations describe views of storage, and arithmetic operations can appear inside a structured loop body. Through successive changes of dialect, an MLIR program can eventually be lowered toward code-generation inputs such as LLVM IR or SPIR-V.
The paper illustrates these levels with a function that performs a TOSA convolution, a memory reference with a column-major layout, and a structured computation that adds a matrix product to an existing matrix. Each example exposes a different correctness obligation. The convolution encodes a high-level operation whose lowering must preserve the rules for its arithmetic and padding. The layout determines which storage location a logical coordinate denotes. The structured matrix calculation exposes a reduction whose successive iterations feed an accumulator. A validator needs to understand each of these forms to compare programs that move between them.
Floating-point arithmetic complicates the comparison in two ways. The authors explain that bit-precise encodings can generate large formulas even for transformations that depend very little on the exact arithmetic. They also describe compiler optimizations that deliberately rely on laws which strict IEEE-754 arithmetic does not satisfy. Reordering a sum can be useful for execution, although different groupings of additions can change where rounding occurs. Validating such a rewrite calls for a clear statement of the arithmetic permission, as well as an efficient expression of it.
These two demands are related but distinct. Making an encoding cheaper concerns how much work the solver must do. Allowing changes of reduction order concerns which behaviors the source and target are required to share. The paper's scope is high-level, target-independent transformations within a function, including lowering tensor operations into loops, replacing tensors with buffers, simplifying operations, and performing simple loop optimizations. Within that scope, an encoding has to connect arithmetic, shapes, indexing, memory, and defined behavior before the solver can compare the functions.
The method, step by step
From a pair of functions to a question for the solver
Mlir-tv pairs functions of the same signature from the original and compiled programs. The signature gives the comparison a common interface for arguments and results. Both versions start from the same symbolic arguments and initial memory. A symbolic argument stands for any admissible value. An operation on it produces a logical expression for its result, so the validator can describe many possible executions in one formula.
The solver uses satisfiability modulo theories, abbreviated SMT. Satisfiability asks whether some assignment makes a formula true. The “theories” give meaning to the objects in the formula, such as bit vectors and arrays. A bit vector is a fixed-width sequence of bits with operations such as comparison and addition. An array in this setting is a function-like object whose value can be read at a given index. Mlir-tv also uses uninterpreted functions. The solver can choose the outputs of such a function, subject to the rule that identical arguments to the same function yield the same result and to any constraints supplied by the encoding.
The validator builds a final-state expression for each function, including whether it encountered undefined behavior, what it returns, and the state of memory. It asks the solver whether there is an input for which the target violates the refinement relation. Refinement is the rule that says how the second execution must respect the obligations created by the first. The asymmetry matters when the original itself can encounter undefined behavior. The comparison begins by establishing what the source promises for an input and then asks the target to honor that promise.
How mlir-tv checks a compiler transformation
The steps in order.
The encoding rules do double duty. They tell the solver how to interpret each instruction, and they state the semantics on which the check depends. At the level of an operation, a rule describes how its execution changes the symbolic state. At the level of a function, the resulting expression describes its final state. The authors constructed these rules from the dialect documentation and examined the expected behavior of compiler passes where the documentation left questions open.
There is no training procedure in this method. Given the function pair, the validator constructs the problem from the IR, analyzes the number of values or memory blocks it may need, and invokes a solver. The function pairs examined in the experiments are inputs to that process. They have no role in fitting parameters or learning how to judge a new pair.
Giving floating-point values just enough detail
If a transformation only swaps the operands to an addition, the decisive property is commutativity. The solver can establish that property without calculating a rounded sum. The paper uses this observation to motivate a representation in which abstract floating-point values are bit vectors and arithmetic operations can have a range of interpretations. This is an over-approximation. The abstract search permits behaviors beyond those of the arithmetic it represents, so ruling out a violation in that search also rules out a concrete violation covered by the encoding.
The authors illustrate the choice of bit width with two functions that return the sum of shared f32 arguments. The source adds the first argument to the second. The target reverses them. Each function has the inputs and its own result, and the inputs are shared across the comparison. Before imposing commutativity, the bound on distinct observed values is written as follows.
4 = 3 + 3 − 2
The 3 for each function counts its floating-point registers, including its inputs and result. The 2 removes the duplicate count of the shared inputs. The 4 bounds the distinct values visible across the pair. The + and − signs denote addition and subtraction in this count. For this example the authors say that a bit vector of 2 bits is enough in theory, since it can distinguish the values needed to witness a violation.
Without constraints on the abstract addition, the solver could assign different results to the two operand orders. Mlir-tv instead constructs a commutative operation from an uninterpreted function by applying it to both orders and combining the output bit vectors. It also gives selected special cases an explicit interpretation. The paper illustrates the two decisions together with the case in which an operand is NaN, the special floating-point value that represents a result outside ordinary numerical values.
ite(isNaN(x) ∨ isNaN(y), NaN, H(x, y) & H(y, x))
Here x and y are abstract floating-point operands. isNaN tests their representations, and ∨ means logical or. The conditional ite returns its second argument when the test is true and its third argument otherwise. NaN is the abstract special value returned in the first case. H is the same uninterpreted function in both calls, and & is bitwise conjunction. Reversing the operands exchanges the two results combined by &, leaving the combined value unchanged. Any commutative bit-vector function can be represented this way by choosing H to be that function, in which case the two operands of the conjunction coincide.
Other conditionals encode selected behavior for signed zeros, signed units, signed finite extrema, infinities, and NaN. Subtraction uses addition with a negated operand. Division has a function of its own because replacing it with multiplication by a reciprocal does not preserve floating-point behavior in the presence of subnormal values. Subnormal values are representable magnitudes near zero for which that replacement can matter. The paper also gives multiplication and exponentiation abstract interpretations. Comparison, negation, and absolute value can use the structure of the abstract bit vectors directly.
The most significant bit is the sign bit. The rest form the magnitude field, ordered by absolute value for finite numbers. Comparing finite magnitudes can therefore use the integer order of the magnitude fields. The representation reserves high-end patterns for infinities and NaNs, with one NaN representation per sign. Literal constants are assigned magnitude fields subject to constraints that preserve their order. The solver can choose how the abstract codes are spaced while respecting those constraints.
Casts between floating-point types require relations between their representations. In the refined encoding the magnitude field of the wider type contains limit, truncated, and precision bits, in descending order of significance. The limit field signals when narrowing overflows to signed infinity. The truncated field describes the magnitude floored to a value in the narrower type. The precision field records whether the original value differs from that floor. A zero precision field describes an exact truncation, while a non-zero field allows a rounding choice selected by a Boolean-valued uninterpreted function. To extend a value, the encoding puts the old magnitude into the truncated field and sets the other fields to zero.
Counting the values a disagreement can expose
The authors need enough bit patterns to express a concrete counterexample if one exists. Counting declared registers is a starting point, but some instructions use intermediate floating-point values that never appear as results in the IR. The paper illustrates this with an integrality test. It can compare a value with the result of a floor operation even though its declared result is Boolean. The intermediate float from the floor must be counted because it can affect the comparison. Mlir-tv therefore counts applications of the relevant floating-point uninterpreted functions during encoding, along with the floating-point arguments and distinct constants in the pair.
w = ⌈log₂ N⌉
The symbol w is the chosen width of the bit-vector field. N is the bound derived from the relevant function applications, floating-point arguments, and distinct constants. log₂ is the base-2 logarithm, and the ceiling brackets choose the least integer at least as large as its argument. The equation gives the width used to obtain enough distinguishable patterns for that bound.
A tensor can otherwise make this count large because each element could hold a different value. The paper observes that a disagreement between two result tensors can be demonstrated with a single mismatching element. If every operation under consideration is elementwise, then tracing the disagreement at a chosen index only requires tracing the corresponding scalar inputs. An elementwise addition reads the left and right value at that index, and the solver can compare the scalar computations that produce it. The tensor operations need to have the stated elementwise structure for this reasoning to apply. If an output depends on many input positions, as a sum can, those positions can contribute to the bound. In the general case a memory reference contributes its accessible size, with the paper using the elementwise simplification where applicable.
The distinction is between testing one chosen location and reasoning symbolically about an arbitrary location. The method does the latter. The solver can choose any valid index when looking for a mismatch. Reducing the investigation to one symbolic coordinate therefore leaves the choice of a witness open. At the same time, it avoids allocating abstract values for every position when the witness can never depend on all of them together.
Representing tensors with expressions for their elements
A tensor has an element type and a shape, and some of its dimensions can be known only when the function runs. An MLIR tensor value is held in static single assignment form, which means that a virtual register is assigned once. Tensor registers do not alias one another. Mlir-tv uses a fresh SMT array for the data of each tensor argument and fresh bit-vector variables for its dynamic dimension sizes. The encoding constrains the total number of elements by the capacity of the address space. A multidimensional index is flattened into a one-dimensional position in row-major order.
A result tensor can be described by a lambda expression. A lambda gives the value of the array at an arbitrary index by specifying an expression in that index. For negation, the output at any position is the negation of the input value there.
λi. negate(select(t, i))
The symbol λ introduces a function of the index i, which is a 32-bit index in the paper's example. The dot separates the parameter from the function body. t denotes the input tensor's SMT array. select reads the value at i, and negate flips the abstract floating-point sign while retaining the magnitude. Applying the lambda to a valid output index gives the corresponding result element.
An operation that rearranges positions can use the same representation. The paper's square transpose takes a flat output index, recovers its coordinates, and reads the input with those coordinates exchanged.
λi. select(t, (i % N) × N + ⌊i / N⌋)
Here i is the flat output index and N is the size of each side of the square tensor. t and select again designate the input array and its element selection. The % operator takes the remainder, giving the output column. / with floor brackets gives the output row. The multiplication × and addition + form the flat input index after the exchange. The lambda defines the entire output by giving this rule for any valid position.
An SMT array can denote values outside the tensor's shape. The meaning of a tensor operation only uses its valid positions. The lambda for negation therefore does not need an internal bounds check for every possible index. Bounds matter when executing an operation that accesses a tensor, and they matter again when an uninterpreted reduction is given an entire array. In that case the solver must be prevented from using arbitrary entries outside the shape to distinguish two legitimate reduction inputs.
The encoding tracks element initialization in a separate Boolean array. Arguments are assumed initialized. An operation such as linalg.init_tensor creates an uninitialized tensor, and writing individual elements can produce a partially initialized one. A read from a position that has not been initialized is treated as undefined behavior. The authors relate this choice to bufferization, where the corresponding operation can become allocation of memory whose bytes have yet to be set. They also treat out-of-bounds accesses and violations of dynamic shape requirements as undefined. These decisions enter the refinement condition alongside the value expressions.
Reading the structure of a loop from its indexing maps
A linalg.generic operation carries indexing maps that say how loop variables select positions in each operand. It also identifies the role of each iterator. An iterator marked parallel selects independent work, while a reduction iterator can contribute to a shared output through an accumulator. The body receives the elements selected by the maps and yields an element computed from them. This structure lets the validator use the indices advertised by the operation to describe what it yields.
The paper illustrates the parallel case with a loop that adds a matrix to the transpose of another matrix. The map for the first input preserves the loop coordinates. The map for the second exchanges them. The output map preserves the coordinates, and the body ignores the initial value supplied through the output operand.
C[i, j] = A[i, j] + B[j, i]
A and B are the input tensors, C is the result, and i and j are logical row and column indices. Brackets enclose a tensor coordinate. The + is the body’s floating-point addition in the selected arithmetic encoding. The equality gives the value yielded at the indicated result coordinate. Because the iterators are parallel, that value comes from the current coordinates without an accumulating dependence on previous iterations. A row-major lambda can then expose the result at a flat array index.
Finding the loop bounds is itself a semantic decision. The authors compare two transformations to decide how the validator should interpret a structured loop when operand sizes differ. Conversion to an explicit loop looks for a dimension whose indexing expression exactly matches an induction variable. It takes the first such dimension to determine the corresponding upper bound. A shifted expression would not serve the same purpose. If a variable has no suitable dimension, the operation is considered syntactically invalid by the conversion described in the paper.
The authors also consider a canonicalization that replaces a loop returning input elements unchanged with the input tensor. Taking the loop bounds from the first matching operand while allowing incompatible dimensions elsewhere could make that replacement change the result. The encoding thus first determines the bounds using the rule for conversion to an explicit loop and then requires the relevant operand dimensions to agree with those bounds through their maps. In the transpose example, comparison of the second input's dimensions follows the swapped coordinates. An incompatible shape gives undefined behavior in the encoding.
The same loop can operate on buffers. Mlir-tv represents the computation as reading the inputs into tensor expressions, computing the result, and writing it back to the output buffer. This encoding uses a disjointness condition for the input and output buffers of linalg.generic. With an identity layout for the output, the memory update can be given directly by a lambda. For a nonidentity layout that the encoding can handle, the tool creates a fresh array for the updated block and uses universally quantified conditions to describe the contents of changed and preserved locations. A universally quantified condition applies to every eligible index.
The paper's matrix-product example illustrates a reduction loop. Parallel iterators select the output matrix position, while an inner iterator visits the terms that contribute to that position. The loop fetches elements of the input matrices, multiplies them, and adds their product to the accumulator. Mlir-tv recognizes common reduction forms by inspecting the operand of the loop's final yield and then uses the appropriate abstract reduction function. This recognition step limits the kinds of loop bodies the technique covers. Within those patterns, the indexing maps and reduction encoding supply a description of the output without requiring the solver to invent an invariant for a general loop.
Encoding reductions and permissions to reorder them
A reduction combines many elements into one value. The baseline abstraction for summation uses an uninterpreted function from an array to a floating-point result. If its solver-level input included arbitrary out-of-bounds entries, two arrays with the same legal elements could produce different sums for reasons unavailable to the program. Mlir-tv wraps the array so that out-of-bounds positions return a neutral value for the reduction. The paper uses −0.0 as an example for summation. The reduction then receives an array whose irrelevant entries cannot cause a difference.
A compiler that is allowed to change the order of summation needs more than congruence of the plain array function. Reordering elements changes which value appears at each position. What remains the same is the collection of elements counted with repetitions, called a multiset. When the rules permit order-independent summation, corresponding reductions must agree for arrays with equal multisets. The paper considers multiset equality as a direct way to express the condition. A solver with a native multiset theory can use that representation. Another can represent the multiset by an array mapping each element to its count.
The authors' alternative is to give each possible element a symbolic bit-vector hash and combine the hashes using bit-vector addition. They use the technique for arrays of known constant length. In the following formula, the sum ranges over occurrences, so repeated elements contribute more than once.
F(A) = Σₓ∈A f(x)
A is an array presented to a reduction. x is the value at an occurrence in that array, and f is the function assigning each value a bit-vector hash. Σ adds the resulting bit vectors, with x ∈ A denoting the occurrences being visited. F(A) is the combined hash. Reordering the elements preserves the addition because bit-vector addition is commutative and associative.
The proof argument concerns agreement across all choices of the element hash, which is a stronger premise than agreement under one choice. If the multiplicities differ for a value, the proof attempts to isolate it by choosing a hash that assigns a unit contribution to that value and zero to the rest. The paper states the distinguishing condition as follows.
(∀f : T → BV(⌈log₂ max(|A|, |A′|)⌉), F(A) = F(A′)) ⇒ A′ is a permutation of A
A and A′ are the two arrays, T is their element type, and BV denotes the type of bit vectors of the width in parentheses. The bars in |A| and |A′| give the array lengths. max selects the larger length, log₂ and the ceiling brackets determine the stated width, and → describes the type of f. ∀ ranges over all such functions, with F evaluated using each choice. ⇒ introduces the conclusion that the two arrays contain the same multiplicities. Because fixed-width addition can wrap, the multiplicity argument needs enough range to distinguish the relevant counts. The stated width requires care where the maximum length itself cannot be represented at that width.
Operationally, the point of the hash is to support the solver's search for a disagreement. If two reductions that should agree are assigned different outputs, a witness hash should distinguish their input multisets. A permutation cannot yield a different hash for any choice of the element function. The witness function can be left free in the solver query, avoiding an explicit universal quantifier for that check. This is a symbolic use of hashing. The method does not sample hashes or estimate whether an accidental collision is likely.
Flattening a nested reduction creates a related problem. A sum over inner sums receives intermediate values, whereas a flat sum receives all the original terms. Even with permission to regroup the arithmetic, those input arrays have different elements. The paper handles this case by linking the hash assigned to an inner result to the aggregate of its inputs' hashes.
h(sum(A)) = Σₓ∈A h(x)
sum(A) denotes the abstract summation of the array A. The function h assigns hashes to floating-point values, which include the result of sum as well as the individual terms x. The Σ expression adds the hashes over the occurrences in A. The equality is an added constraint on the hash assignments. It lets the hash contribution of an inner sum represent all the terms it contains when the outer reduction is compared with a flat reduction.
The initial construction can give different pairs of reductions their own hash functions. Connecting inner and outer reductions then creates additional constraints between the functions. The authors reduce that overhead by sharing a hash function and give a range requirement for the shared version.
[0, p²n)
This interval describes the required range in the supplementary argument cited by the paper. The square bracket includes 0 and the parenthesis excludes the upper endpoint. p is the number of summation pairs, p² is its square, and n is the largest array size. The juxtaposition in p²n denotes multiplication. The paper presents this requirement in connection with combining the hash functions across pairs. The constraints describe a permission to flatten or reorder the reduction under the selected semantics. The IEEE-754 mode disables these permissions.
Keeping memory effects visible
Bufferization replaces tensor values with computations involving memory references. In MLIR a memory reference, or memref, points to a region with a shape and a layout. The reference records a block identifier, an offset, dimensions, a layout map, and whether it is a view. The map translates logical indices into an offset in storage. A view can start partway through a block or access locations in an order different from the default row-major arrangement. Two memrefs can point into the same block, so changing the contents through one can affect reads through the other.
The paper's column-major example makes layout visible in a small expression.
offset(i, j) = i + j × 3
Here i and j are logical coordinates. offset gives the location relative to the reference point, and 3 is the stride multiplying j in the example. × is multiplication and + adds the contribution of i. The layout must be injective under the assumptions the paper describes for MLIR transformations, so distinct valid logical coordinates refer to distinct locations within a view.
A memory block is the storage associated with an allocation or a global variable. It has a size and an identifier, and its state records the contents, initialization, writability, liveness, and whether it was created by the allocation operation relevant to its block type. A newly allocated block is alive and writable, with uninitialized contents. Freeing it ends its lifetime. A clone-like operation can make the source block permanently read-only under the encoding described by the authors.
Returning a tensor load from a memref requires live storage, an in-bounds region, and initialized values at the locations read. A store requires a live, writable block and an in-bounds destination. These checks account for different failures. A view can have valid logical indices while its region extends past the allocated block. An address can be within bounds but refer to an uninitialized element. The same addresses can support reads and forbid writes if the block is read-only.
Mlir-tv uses SMT arrays for contents and initialization, and variables for properties that are unknown at the beginning of validation. A visible definition, such as a global definition, can supply known properties directly. Static analysis bounds how many blocks have to be represented. Global definitions and allocations in the function receive constant identifiers, while a reference whose block is unknown can select among the possible blocks. A load is expressed as a conditional on the identifier, reading from the selected block at the reference's offset. A store uses conditionals to update the block that the reference denotes, preserving the others.
The paper distinguishes local blocks, allocated within the function under validation, from non-local blocks such as storage supplied to the function. The final memory check covers non-local blocks. The implementation does not handle calls, and a memref cannot store another memref as an element, so the authors exclude those escape routes for local storage. Returning a memref to a local block is also outside the supported refinement check. For disjointness tests, the implementation restricts the layout to the trivial row-major case. This makes the question of overlap simpler than it would be for two arbitrarily strided views.
Asking for a violation and refining the search
After encoding the functions, the validator has an expression for each final state. The state combines a flag for undefined behavior, the final memory, and the return value. The paper's refinement relation can be written compactly as follows.
(u, m, v) ⪯ (u′, m′, v′) ⇔ u ∨ ((u = u′) ∧ (v = v′) ∧ R(m, m′))
u, m, and v describe undefined behavior, memory, and the return value in the source state. The primed symbols describe the corresponding target state. The symbol ⪯ denotes the refinement requirement from source to target in this article, and ⇔ gives its defining condition. ∨ means or, ∧ means and, and = is equality under the relevant comparison. R is the memory refinement test. If u is true, the source imposes no further condition for that input. Otherwise the two flags must match, the return values must agree, and the memory relation must hold.
For the memory clause, the paper describes comparing non-local blocks with equal identifiers. A read that is successful in the source must also be successful in the target at the corresponding offset. Source writability must be retained as well. The paper treats NaNs of either sign as equivalent in float return values. For return values that reference local allocations, it identifies limits on the comparison and the possibility of false alarms.
∀I. fₛᵣ꜀(I) ⪯ fₜ₉ₜ(I)
I is the common initial state, comprising the argument values and initial memory. ∀ asks for the condition to hold across input states. The dot introduces the body of that statement. fₛᵣ꜀ denotes the source function and fₜ₉ₜ the target function, with each application returning a final state. The ⪯ relation is the one defined above. The solver checks the negation by looking for an input under which refinement fails. With symbolic variables for the unknown input, that search avoids expressing the outer universal quantifier directly.
If the solver proves the problem unsatisfiable, there is no violating input in the encoded search space. If it finds a satisfying assignment under an abstraction, the assignment may rely on arithmetic behavior that concrete operations cannot exhibit. A timeout gives no verdict. The validator uses failure or timeout as a reason to retry with additional arithmetic structure.
Initially, dot products over integers and floats have their own uninterpreted functions. Float types are represented independently, and casts are also uninterpreted. At the next level, dot products are expressed through multiplication and summation, and casts use the related bit fields described earlier. This exposes the link between an operation in one dialect and the component arithmetic used to lower it. If another attempt is needed, sums over small, constant-size arrays can be expanded into additions. An expansion can establish the equality of a short abstract sum and the same expression written out with addition.
For transformations that depend on evaluating arithmetic on constants, the paper also provides a concrete IEEE-754 option. An abstract addition can know that two equal operand pairs give equal results and that exchanging operands is harmless. It can still leave the actual numerical result open. That freedom explains why the abstraction has difficulty with general constant folding and why precise arithmetic can help with those cases. The choice also changes the supported arithmetic laws for reductions. Concrete arithmetic takes precedence over the relaxed laws in that mode.
Experiments and results
Implementation and measures
Mlir-tv consists of 8,900 lines of C++. The authors report support for 25 TOSA operations, 13 linalg operations, 11 memref operations, and 10 tensor operations. Arithmetic contributes 29 supported operations, bufferization contributes 3, and another 8 belong to other groups. These counts describe the implementation's operation coverage. They do not measure how many complete programs can be checked, since support for a program also depends on how its operations, shapes, and memory references are used.
The tool uses Z3 4.8.13 and cvc5 0.0.3, with a 30 s timeout. The authors used Z3 for the main validation experiments after observing better performance in their sanity tests. The comparison of reduction encodings includes experiments with both solvers. The reported hardware was an Apple M1 CPU with 16 GB RAM, and the MLIR checkout was fixed at b5a0f0f, identified in the paper with 26/Dec.
The experiments answer different questions. Handwritten function pairs test whether the method recognizes intended correct and incorrect cases and let the authors compare arithmetic encodings. Official compiler unit tests give a corpus of actual pass inputs and outputs. The network compiles exercise a sequence of passes on larger starting programs after splitting them into smaller pairs. Finally, a reduction benchmark measures the running time of the hash and multiset approaches. A successful semantic validation, an encoding speedup, and a timeout are different outcomes and have to be read in the context of their experiment.
Handwritten function pairs
The authors wrote 57 function pairs to see whether mlir-tv would validate correct transformations and produce counterexamples for incorrect ones. This was also the setting for their comparison with concrete IEEE-754 arithmetic. They report an average speedup of 13.6x for the abstract encoding relative to the concrete one. They report a 2.2x speedup from shrinking the bit width of the abstract floating-point representation relative to using 32 bits in that representation.
The comparisons have different baselines. The first changes the arithmetic representation from concrete to abstract. The second compares widths within abstract arithmetic. Both report validator speed on the handwritten cases. They give no estimate of the runtime of a program produced by the compiler, and the benchmark does not measure changes in task accuracy.
Official MLIR unit tests
The unit tests ordinarily apply a transformation to a small program and check that the resulting IR matches an expected syntactic pattern. Mlir-tv compares the behaviors of the before-and-after functions. A pass can produce the expected operation or loop and still change the value on a particular input, so the semantic check adds a different condition to the test. The authors bounded the size of dynamically shaped tensors to 100 in this experiment to avoid timeouts.
The official test corpus comprised 2,467 function pairs. Mlir-tv validated 433 tests, timed out on 8, and failed on 8. These reported outcomes account for only part of the full corpus. The counts give an absolute measure of successful validations and reported solver difficulties, without requiring the rest of the pairs to be treated as failed checks. The following chart shows the reported outcomes within the corpus.
Reported validation outcomes on official MLIR unit tests by test count
Successful validations were the most frequent outcome among the outcomes reported for mlir-tv.
The numbers
| System or setting | tests |
|---|---|
| mlir-tv timed out | 8 |
| mlir-tv failed validation | 8 |
| mlir-tv validated (this paper) | 433 |
The validated unit tests did not need the relaxed arithmetic properties for reductions. Thus this corpus demonstrates the reach of several parts of the encoding, including arithmetic and memory checks, while the dedicated reduction comparison supplies the performance evidence for the hash technique. The authors were aware of additional transformations that require the relaxed reduction rules.
Several failures led them to inspect how passes handled special floating-point values. The lowerings for TOSA convolution and depthwise convolution padded input tensors with +0.0. A separate rewrite folded addition of +0.0 into the unchanged operand. That replacement can change the sign of the result when the operand is −0.0, and the TOSA specification cited by the paper requires support for signed zero. The authors found related initialization behavior in the lowerings for fully connected computation and summation. They reported these issues and say that the addition rewrite was fixed. They also found that lowerings for the clamp and max-pooling operations could change output in cases involving NaN and negative infinity.
The memory issues arose from interactions between passes. With a read-only destination, the authors could not find a rule for linalg.fill that explained both bufferization and generalization of named operations. If the fill is undefined on a read-only block, bufferization can introduce that undefined behavior. If the fill is defined, generalizing it to a loop of stores can introduce undefined behavior at the writes. This inconsistency concerns the meaning assigned to a pass's output at the point the next pass sees it.
The authors also found that buffer deallocation could insert a free for an unused result of memref.clone, despite the restrictions on mutating the clone result. Separately, the documentation left the timing of the source's read-only status unclear. The paper reports that after discussion, the documentation specified that the status begins immediately after the clone. The successful addition fix and the clone clarification are the concrete follow-up changes the authors report. The other cases describe mismatches or ambiguities encountered in validation.
A pass sequence on larger programs
The authors retrieved TFLite versions of text_classification_v2, SqueezeNet, and MobileNet from official TensorFlow resources. They first used the TOSA-to-linalg and TOSA-to-standard conversions, then canonicalization and elementwise fusion. The sequence also included tensor constant bufferization, linalg bufferization, and tensor bufferization. These passes test lowering between dialects, simplification and fusion, and the transition from abstract tensor values to memory operations. MobileNets
Two interventions define what the experiment establishes. The authors modified mlir-tv so that +0.0 at certain affected operations was interpreted as −0.0, addressing the signed-zero failures in the TOSA-to-linalg step. They also split the source and target into smaller functions to make validation finish within a reasonable time. The programs' control flow was mainly loops, which made the splitting manageable in these cases. The split functions contained an average of 9.5 to 11.6 instructions. That range describes the functions passed to the validator after splitting.
All tested passes validated for text_classification_v2. For SqueezeNet and MobileNet, the final passes, linalg bufferization and tensor bufferization, failed to validate because they contained unsupported operations. The earlier checked stages therefore carry a different conclusion from those final stages. The experiment shows how a pass sequence can be checked in smaller pieces, with the signed-zero adjustment in effect. It does not turn an unsupported operation into a counterexample or report a single check over an intact compilation.
Hashing compared with multiset encodings
The reduction evaluation compares the time to encode and check reduction equivalences with symbolic hashes versus a multiset representation. In cvc5 the baseline uses the solver's native multiset theory. In Z3 the authors simulate a multiset with an array that counts occurrences. The Z3 runs start with QF_AUFBV and fall back to ALL when the initial solver attempt fails. The cvc5 runs similarly use HO_AUFBV and HO_ALL. The names designate solver logics that specify the kinds of expressions supported by that check.
Each test was run 10 times, and the authors report average execution times. The timeout was 30 s, shown as 30,000 ms in the figures. The comparison includes reductions over tensors, with a separate figure tracing the dot-RV case as tensor size changes. The figures' measured quantity is mlir-tv running time. Their tensor sizes are inputs to the validation problem.
Across the comparisons the authors describe hash encoding as faster overall than the multiset approaches. The native cvc5 multiset implementation performed better than the Z3 counter-array implementation in the reported tests, while remaining slower than hashing. The authors also observed consistent running times for hash encoding across the tensor sizes they tried. This is evidence about the reported solver workloads under their selected logics and cutoff. The results concern how quickly the solver established a reduction property, even though the source of the workload was a computation on tensors.
What the ablations show
Floating-point abstraction and width
The paper's closest comparisons to ablations are changes to arithmetic precision, width, and the encoding of reductions. There is no full breakdown that removes each feature of mlir-tv in turn. The comparisons it does offer expose costs at distinct parts of the solver problem.
On the handwritten pairs, the contrast between abstract and concrete arithmetic shows the value of separating numerical behavior from structural behavior where the transformation permits it. A bufferization can keep the same arithmetic expression while changing the way its operands are stored. A swap of addition operands can depend on commutativity alone. A precise numeric encoding would still give the solver the machinery to determine IEEE-754 results for those operations. The reported 13.6x average speedup establishes that retaining less arithmetic detail improved running time in this benchmark.
The width comparison makes a finer distinction. Both sides use abstract floating-point values. The variable being changed is how large their representation is: one configuration uses the width calculated from the function pair, while the other uses 32 bits. The resulting 2.2x speedup on the handwritten pairs shows that width matters after the decision to abstract has been made. That supports the authors' effort to count the values needed for a witness, including intermediate values implicit in operations, instead of taking the original floating-point width as the default.
The benchmark does not give a separate timing contribution for every counting rule. In particular, the scalar treatment of elementwise tensor chains is part of the method's rationale for tighter bounds, but the width comparison does not isolate it from the rest of the bound calculation. The same caution applies to the special-value cases and cast encoding. The reported average compares encodings at broader levels than individual semantic rules.
Alternative ways to express reduction equality
The reduction experiments hold fixed the relationship the programs are meant to satisfy and change how the solver is asked to establish it. Counting every value can describe a multiset exactly in a direct representation. The symbolic hash describes the consequences of equality through additions and an uninterpreted function, and the solver can look for a distinguishing assignment when considering a violation. The authors offer the comparison because the nominally direct representation can be expensive for the solver to compare.
Using a native multiset theory in one solver and a counter array in the other reveals an implementation difference in the baseline. The authors' reported ordering shows that native multiset support helped relative to the array encoding in their chosen configurations, and that the hash approach performed better than either overall. The comparison thus gives evidence for avoiding explicit multiset machinery in these cases. The authors conjecture that the solvers' procedures for proving equality of multisets or counter arrays are a source of the cost. The measurements do not isolate the time spent inside those particular procedures.
The tensor-size sweep tests a different question from the comparison at a given size. A fast result on a small array would leave open whether the cost rises rapidly with the number of elements. In the cases the paper tests, the hash encoding produced relatively consistent running times as size varied. Its practical advantage therefore includes the behavior of the tested scaling curve, under the fixed timeout. The construction still depends on arrays of constant length for the reduction-property encoding described in the paper, so the sweep gives no evidence about symbolic lengths.
What the failures diagnose
The compiler failures offer qualitative analysis. Signed-zero cases expose a pass that uses an arithmetic identity whose validity depends on exactly how the language distinguishes zeros. The fill example exposes a conflict between the conditions needed to justify two passes. In one case an ordinary calculation supplies a specific input value at which the rewrite can disagree. In the other, trying to assign a consistent meaning to the intermediate buffer operation reveals that different passes are working with incompatible assumptions.
The network experiment provides another kind of boundary observation. The final passes for SqueezeNet and MobileNet reached unsupported operations, while the same pass sequence validated for the text-classification program under the experiment's setup. This difference identifies where the implemented dialect coverage mattered in that sequence. The experiment did not rerun the sequence under controlled choices of split size or report timings for each round of refinement. Accordingly, the paper offers examples of how splitting and added precision make validation possible, while its measured comparisons address floating-point representation and reduction encoding more directly.
Limitations
Limits the authors identify
The authors target intraprocedural, high-level, hardware-independent transformations. Their symbolic interpreter covers a subset of MLIR operations and structured loops that provide the indexing and iteration information used by the encoding. The reduction loop technique recognizes common syntactic forms. The implementation does not encode calls or loops that contain allocations. The memory analysis can bound the number of allocated blocks in part because allocation does not recur inside a supported loop.
Memory references also have limits distinct from general instruction coverage. While the encoding allows selected nonidentity layouts for memory updates, the disjointness check only supports trivial row-major layouts. Arbitrary layouts can describe noncontiguous sets of locations, where overlap cannot be determined by a simple check on the ends of a region. The paper also notes that the physical-address representation it supports is one-dimensional, and that functions returning references to local blocks may produce false alarms. These conditions matter particularly for bufferization, where a function may expose storage views that have no direct counterpart among the tensor values it replaced.
The authors explicitly say that their abstract arithmetic cannot validate general constant folding. Iterative refinement helps when a disagreement is due to an overly free dot product, cast, or small sum. Concrete IEEE-754 arithmetic provides another option when the exact result is the reason a rewrite works. It also disables relaxed reduction properties. The paper offers ways to check transformations under different arithmetic requirements, with each attempt inheriting the chosen requirements.
Dynamic tensor sizes were bounded in the unit-test experiments. The authors acknowledge that this can miss bugs whose witnesses require larger tensors. Their argument for shrinking the floating-point domain is different. It aims to preserve enough distinguishable values for some witness of a real disagreement, whereas the size restriction excludes inputs outside the bound. The former is intended as a sound abstraction step for the supported cases. The latter changes the inputs covered by the validation.
The authors also describe the dependence on dialect semantics assembled from textual specifications. Some conditions, such as matching dimensions in a structured loop or the effect of reading uninitialized storage, need interpretation when the documented behavior is unclear. The resulting check is formal with respect to the encoding. Its applicability to MLIR itself depends on whether the encoding captures the guarantees a programmer and a pass can rely on. The fill and clone examples show why that dependency can matter in practice.
Limits visible in the setup and argument
The unit-test corpus supplies useful examples of transformations developers expected to perform. It also supplies small programs that were designed to trigger particular output shapes. Its confirmed cases do not imply similar coverage for arbitrary functions in those dialects. Unsupported cases, failures, and timeouts carry different implications. A timeout leaves the solver question open, and an abstract failure may require a refinement or semantic investigation before it can establish a defect.
The compilation study uses selected TensorFlow artifacts, split function pairs, the stated timeout, and a signed-zero adjustment in the checker. Thus the passes validated for text_classification_v2 under the experimental setup, and the other programs reached the final unsupported stages described in the paper. The study measures preservation of encoded program behavior for these transformations. It does not evaluate prediction quality, hardware performance, or the numerical error incurred when reduction order is relaxed. The permission to reorder a sum is an assumption of the selected semantics, rather than an experimentally measured tolerance for changes in its output.
The hash argument also invites a distinction between its central idea and the written width bound. The central idea is to use an indicator hash for a value whose multiplicity differs. With modular addition, the resulting hash is the multiplicity modulo the size of the bit-vector range. For the proof to distinguish counts in all its stated cases, that range must separate every relevant multiplicity. At a maximum array length that is a power of the radix, the ceiling-logarithm width printed in the theorem can leave the maximum count congruent to zero. Arrays repeating different elements can then defeat the stated counting argument at that width. The reported timing comparisons do not settle which widths suffice in every case. The later shared-hash range condition is stated for the extension involving multiple sums and likewise has to be read with the intended range guarantee in mind.
Care is also needed about the direction of the reduction obligation. For an order-independent sum, equal multisets must force equal results. Equal results can arise from different multisets. A witness hash is useful when searching for distinct reduction results, since the solver then has to justify treating the input multisets as different. Reading an equality of hash expressions for some choice of function as evidence of multiset equality would be insufficient. This follows directly from the difference between a single assigned hash and the proof's claim about all hash assignments.
Finally, the reported speedups and the reduction timing ordering reflect the test cases, solver versions, and evaluation machine in the paper. The handwritten comparison shows the aggregate effect of using abstract arithmetic and reducing its width. The reduction suite shows the observed cost of alternative encodings in its configurations. Neither reports the benefit of each stage of refinement independently or a general upper bound on solver time. The resulting evidence is strongest for the specific kinds of function pairs and reductions the authors evaluated.
What came after
A later work citing the paper examines how rigorously automatically generated code is evaluated. Its title frames correctness as something that has to be established about the generated program. Bang and colleagues ask a narrower relational question about a compiler pass: whether the behavior of a particular target function respects the obligations of its source. The common concern is the strength of the evidence used to judge a transformation or output, while the objects being compared differ. The citation establishes a connection between the papers. The account of the later study does not establish whether it reused mlir-tv, the refinement check, or the reduction encoding. Is Your Code Generated by ChatGPT Really Correct?
Cite
Cite as Seongwon Bang, Nam SeungHyeon, Inwhan Chun, Ho Young Jhoo and Juneyoung Lee. 2022. SMT-Based Translation Validation for Machine Learning Compiler. Lecture notes in computer science.
@inproceedings{bang2022smt,
title = {{SMT-Based Translation Validation for Machine Learning Compiler}},
author = {Seongwon Bang, Nam SeungHyeon, Inwhan Chun, Ho Young Jhoo and Juneyoung Lee},
booktitle = {Lecture notes in computer science},
year = {2022},
doi = {10.1007/978-3-031-13188-2\_19},
url = {https://doi.org/10.1007/978-3-031-13188-2_19}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/bang-2022-smt-based-translation-validation-machine/