Manuscript Offprint
arXiv:2610.17132Masked Attention Pooling Is Invariant to Padding and Permutation: A Formal Proof in Lean
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
Attention-based multiple instance learning (MIL) pools a variable-size bag of instance embeddings into one vector. In batched training, bags are padded to a common length, and the pooled output is expected not to depend on how much padding was added or on the order in which instances are stored. This expectation holds only if padded rows are removed from both the numerator and the softmax normalizer. Common implementation idioms meet it only under side conditions. Zeroing padded features alone does not work. Masking logits with fails on empty bags and on nonfinite padding. Masking with a large negative constant is exact only after floating-point underflow. We define masked attention pooling with a guarded normalizer and prove in Lean 4 with mathlib that it is invariant under any bijective reindexing of rows and under appending any finite number of masked rows with arbitrary real features and logits. We also prove that values at masked positions are irrelevant and that an all-masked bag maps to zero. The theorems hold for arbitrary finite index types and feature dimensions. Using the jax-lean certificate pipeline, we connect these theorems to the Jaxpr traced from the JAX kernel itself. Lean checks translation certificates for two concrete shapes, identifies the generated functions with the generic specification, and transfers both invariances to the imported Jaxpr's real-arithmetic semantics. All audited theorems depend only on Lean's three standard axioms. The results concern ideal real arithmetic. Floating-point execution, XLA, and the JAX tracer and importer remain outside the proof. The development is short and publicly available.
1 Introduction
In multiple instance learning [2], a label is attached to a bag of instances rather than to each instance. Attention-based MIL pooling [4] computes a scalar score for every instance, normalizes the scores with a softmax over the bag, and returns the weighted average of the instance embeddings. This construction underlies much of weakly supervised computational pathology, where a whole-slide image is a bag of thousands of tile embeddings and only the slide carries a label [1, 9]. Ilse et al. introduce the operator as a permutation-invariant aggregation over the bag [4], in the same spirit as other set architectures [8, 12].
Bags differ in size, so batched implementations store them in a dense array of n rows together with a validity mask or a length. The model is then expected to satisfy two properties:
-
Padding invariance. Appending masked rows, with whatever contents, does not change the pooled output.
-
Permutation invariance. Reordering the rows, with each row's features, score, and mask moving together, does not change the output.
These properties are easy to state and easy to break. Zeroing the features of padded rows is not enough: a padded row with logit 0 still contributes to the softmax normalizer. Two real instances with values 2 and 6 and equal logits should pool to 4. With zero-feature padded rows left inside the softmax, they pool to , so the output depends on the batch's padding length. Masking logits with fixes the normalizer when every bag has a valid row and all padding is finite. It yields NaN when a bag is empty or a padded feature is nonfinite. Masking with a large negative constant gives exact zeros only through floating-point underflow, and an empty bag then returns the mean of its padding. Table 1 summarizes these behaviours.
This note gives a precise definition of masked attention pooling with a guarded normalizer and machine-checked proofs of its invariances. The contributions are:
-
Size-generic Lean 4 theorems: invariance under any bijection of the row index type, invariance under appending any finite set of masked rows with arbitrary real features and logits, irrelevance of masked values, and a zero output for all-masked bags (Section 4).
-
A corollary covering any shared, instance-local scoring function, such as a linear layer, an MLP, or a gated attention scorer.
-
A connection from the theorems to the code that runs. The JAX kernel is traced to a Jaxpr, translated and independently imported by jax-lean [6], and linked to the generic specification by checked certificates (Section 5).
• A precise statement of the trusted base and of what the proof does not cover (Section 7).
The mathematics is elementary: a bijection reindexes a finite sum, and terms with mass zero vanish. The point is to make the specification exact, including the empty-bag convention and the requirement that masked rows lose their mass, and to check that a specific JAX kernel meets it.
JAX and Jaxprs. JAX [5] traces a Python function at fixed input shapes and dtypes into a Jaxpr, a typed first-order intermediate representation of primitive operations. This trace is what JAX's transformations and compiler consume.
Lean, mathlib, and jax-lean. Lean 4 [7] is an interactive theorem prover with a small trusted kernel, and mathlib [10] supplies the real numbers, the exponential function, and finite sums over Fintypes. The jax-lean library [6] translates a Jaxpr into two Lean artifacts: a readable tensor function, and a separately imported, typed syntax tree of the Jaxpr together with an evaluator that gives it ideal real-arithmetic semantics. For each function it emits a translation certificate, a Lean theorem stating that evaluating the imported Jaxpr agrees with the readable function on every input of that shape. Lean checks this theorem, so the readable function does not have to be trusted. The importer, which decides what the original Jaxpr means in the Lean syntax, does.
3 Masked attention pooling
Let be a finite type of row indices and . A padded bag is given by features , logits , and a mask . The mask may be arbitrary, including invalid rows interleaved with valid ones; a length- prefix mask is the special case .
Definition 1 (Masked attention pooling). The mass and masked feature of row i are
With and if and otherwise,
If some row is valid then , and the coefficients form a probability distribution supported on the valid rows, so this is the usual attention average over the real instances. If no row is valid, or is empty, the numerator is the zero vector and the output is 0. (These two remarks follow directly from ; only the second is formalized, as Proposition 5.) The guard on fixes the value on empty bags and avoids 0/0. The Lean definition is a direct transcription:
noncomputable def mass (logits : ) (mask : ) (i : ) : if mask i then Real.exp (logits i) else 0
noncomputable def pool [Fintype ] (values : ) (logits : ) (mask : ) : Fin d let total := i, mass logits mask i fun j => ( i, mass logits mask i * (if mask i then values i j else 0)) / (if total > 0 then total else 1)
The certified JAX kernel follows the same structure. The where on the logits keeps a masked out of the exponential, and the where on the features keeps out of the product:
def masked_pool(values, logits, mask): safe_logits = jnp.where(mask, logits, 0.0) safe_values = jnp.where(mask[:, None], values, 0.0) weights = jnp.where(mask, jnp.exp(safe_logits), 0.0) total = jnp.sum(weights) denominator = jnp.where(total > 0.0, total, 1.0) return jnp.sum(weights[:, None] * safe_values, axis=0) / denominator
Table 1 compares this kernel with four common alternatives, executed in JAX. “n/a” marks idioms that use , which has no counterpart in . The idiom is correct in float32 because underflows to exactly zero. In real arithmetic the padded rows keep a small positive mass, so exact invariance cannot be proved for it.
4 Theorems
All statements below are proved in MaskedAttention/Basic.lean for arbitrary finite types and arbitrary d. No bag size, feature value, or shape is enumerated. We give the informal argument and the Lean statement for each.
Table 1: Behaviour of common masking idioms in JAX (float32). The bag is the three-instance example of Section 6, whose correct output is (2.0572, 1.3532). “Zero pad”: two appended rows with zero features and zero logits. “NaN pad”: the same rows with NaN features. “Empty”: two rows, both masked, with features (1, 2) and (3, 4). The last column asks whether the idiom is exactly padding-invariant in real arithmetic.
| Idiom | Zero pad | NaN pad | Empty | Exact in |
|---|---|---|---|---|
| Zero padded features only | (1.3563, 0.8921) | (1.3563, 0.8921) | (0, 0) | no |
| Logits , features unmasked | correct | NaN | NaN | n/a |
| Logits , features unmasked | correct | NaN | (2, 3) | no |
| Softmax of -masked logits, features zeroed | correct | correct | NaN | n/a |
| Definition 1 (masked_pool) | correct | correct | (0, 0) | yes |
Theorem 2 (Reindexing). Let and be finite and a bijection. Then .
Proof. Under the reindexing, and . For any , because is a bijection. Applying this to gives , so . Applying it to for each coordinate gives equal numerators.
theorem pool_reindex [Fintype ] [Fintype ] (e : ) (values : ) (logits : ) (mask : ) : pool (values o e) (logits o e) (mask o e) = pool values logits mask := by funext j unfold pool mass simp only [Function.comp_apply] rw [e.sum_comp (fun i => if mask i then Real.exp (logits i) else 0)] rw [e.sum_comp (fun i => (if mask i then Real.exp (logits i) else 0) * (if mask i then values i j else 0))]
Taking gives permutation invariance. The theorem is stated for distinct and because the concrete padding result in Section 5 needs to identify Fin 5 with Fin 3 Fin 2.
Theorem 3 (Padding). Let be any finite type, and let and be arbitrary. Write for the function on that agrees with on and with on , and likewise for the other arguments. Then
Proof. A sum over splits into a sum over plus a sum over . Every padded row is masked, so its mass and masked feature are 0 regardless of and . Both the normalizer and the numerator therefore equal their unpadded values.
theorem pool_padding [Fintype ] [Fintype ] (values : ) (logits : ) (mask : ) (padding : ) (paddingLogits : ) : pool (Sum.elim values padding) (Sum.elim logits paddingLogits) (Sum.elim mask (fun _ => false)) = pool values logits mask := by funext j simp [pool, mass, Fintype.sum_sum_type] rfl

Figure 1: Chain of results. Shaded, dashed boxes and the arrows between them are trusted: JAX tracing and the jax-lean importer that encodes the Jaxpr as Lean syntax. The vertical and lower arrows are theorems checked by Lean. The certified_* theorems compose them to state both invariances directly about the imported IR.
The padded features and logits are arbitrary reals; they need not be zero. Rows already masked inside I are allowed, and P may be empty. Combining Theorems 2 and 3, any bijection of the padded index set that moves the mask with the rows also leaves the output unchanged. Padded rows may be interleaved anywhere.
Proposition 4 (Masked values are irrelevant). If and for every with , then .
Proposition 5 (All-masked bags). Pool(x, s, false) = 0 for all x and s, including when I is empty.
Both are proved by case analysis on the mask (pool_masked_congr, pool_all_masked).
Corollary 6 (Instance-local scorers). Let be any function and a permutation. Then
In Lean this is attention_permutation. The logit travels with its instance, so it is Theorem 2 with . No assumption is made about : it can be linear, an MLP, the tanh scorer of [4], or its gated variant. The corollary does not cover scorers that use position or other instances. A positional encoding or a self-attention encoder before pooling needs its own equivariance argument.
5 From the JAX kernel to the theorems
The theorems of Section 4 are about a Lean definition. To connect them with the kernel above, we trace masked_pool with JAX at shapes [3, 2] and [5, 2] (features [n, 2], logits and mask [n]) and pass each Jaxpr to jax-lean's certify_module. The generated files are reproducible: a check script regenerates them and requires byte equality. Figure 1 shows the chain of results.
Translation certificates. For each shape, jax-lean emits a readable function such as Generated3.pool and an imported program Generated3.pool_ir, plus helper functions for each jnp.where. The theorem pool_translation_correct states that evaluating pool_ir with Jaxpr.Program.eval gives the readable function on every real tensor input of that shape. It is proved by jax-lean's certificate tactic from local evaluator lemmas.
Table 2: Size of the development (lines, including comments).
| File | Lines | Content |
|---|---|---|
| Basic.lean | 79 | Definition 1, Theorems 2–3, Props. 4–5, Cor. 6 |
| Connection.lean | 79 | specification lemmas, concrete and certified invariances |
| Generated3.lean | 200 | emitted function, imported IR, certificates for [3, 2] |
| Generated5.lean | 200 | the same for [5, 2] |
Specification lemmas. generated3_spec and generated5_spec prove that each readable function equals the generic pool, read at the corresponding indices. These are the steps that check the kernel's content: the three mask branches, the leading-axis reductions, the comparison total > 0, and the guarded division. A kernel that zeroed only the features would fail here, because its normalizer would include for masked rows.
Certified invariances. The final theorems are stated about the imported program:
-
certified_permutation: for every : Fin 3 Fin 3 and all real , , , evaluating the [3, 2] program on the row-permuted inputs gives the same result as on the original inputs.
-
certified_padding: for all such and arbitrary , , evaluating the [5, 2] program on the inputs with two masked rows appended gives the same result as the [3, 2] program on the original inputs.
The padding statement relates two separately traced programs. Its proof rewrites both sides through their certificates and specification lemmas, reindexes Fin 5 as Fin 3 Fin 2 with Theorem 2, and applies Theorem 3. The generic theorems hold for every size, but a Jaxpr has fixed shapes, so certificates exist only for the shapes that were traced.
6 Validation
The development was built with Lean 4.33.0, the mathlib release pinned by jax-lean at revision 570aed6, and JAX/jaxlib 0.8.0 on a CPU device. A single script regenerates and compares the generated Lean files, runs the Python tests, builds the Lean library, and audits seven theorems: the five theorems of Section 4 and the two certified invariances. Each depends only on propext, Classical.choice, and Quot.sound, the standard axioms used throughout mathlib. None depends on sorryAx or on a project-specific axiom. Table 2 gives the size of the development.
The theorems concern real arithmetic, so we also test execution separately. Six JAX tests compare the kernel and a numerically stabilized variant (Section 7) against an independent NumPy formula. They cover bag sizes 1, 3, and 17, random permutations, 0, 1, and 11 appended rows filled with NaN features and +∞ logits, all-masked and empty bags, eager and JIT execution, and logits near 1000. As a worked example, take
With all three rows valid, the pooled output is (2.057208, 1.353158) in both float64 and float32. Appending two rows of NaN or shuffling the rows gives the same float32 output. Tests use tolerances because reordering a floating-point sum can change its last bits [3]. They are evidence about execution and do not replace the proofs.
7 Scope and limitations
Real arithmetic. The theorems are exact identities over . They do not model IEEE-754 rounding, overflow, NaN, or infinities, and they say nothing about XLA's compiled code. In floating point the permuted and padded outputs agree only up to rounding, which is why the tests use tolerances.
Trusted components. The Lean kernel and mathlib's definitions are trusted, as in any Lean development. On the JAX side, JAX's tracer is trusted to produce the Jaxpr that is executed, and the jax-lean importer is trusted to encode that Jaxpr faithfully as Lean syntax with real-number semantics, with dtype conversion erased [6]. The readable generated functions are not trusted: they are linked to the imported program by checked certificates.
Fixed shapes. The generic theorems quantify over every finite index type and feature dimension, but only the [3, 2] and [5, 2] traces are certified. Another shape requires tracing and certifying it again, which the generator script does mechanically.
The stabilized kernel is not certified. In practice the exponentials are shifted by the maximum valid logit to avoid overflow. The repository's stable_masked_pool does this and is covered by the numerical tests. Its own Jaxpr is not certified in this version: the masked maximum uses as an initial value and identity, which falls outside the finite-real fragment that jax-lean models. Mathematically the shift cancels between numerator and normalizer, so it does not change Definition 1 for finite logits. A certified version would need a finite formulation of the masked maximum or an extended-real semantics.
Architecture scope. Corollary 6 covers scorers applied to each instance separately. Encoders that mix instances before pooling, such as a transformer over instances, positional encodings, or clustering losses, need their own equivariance proofs. The results are structural. They make no claim about accuracy, calibration, or clinical validity.
8 Related work
Selsam et al. wrote a learning system and its correctness theorem together in Lean and verified that its sampled gradients are unbiased [11]. Our goal is narrower and works after the fact: we prove one structural property of an existing JAX kernel and connect it to the traced program through jax-lean's translation certificates [6]. That library's examples include softmax normalization, masking, and transformer components. The present development follows its transformer proofs and adds a mask-aware pooling specification, padding across separately traced shapes, and the instance-local scorer corollary.
Permutation-invariant set functions are a standard design principle for learning on sets [8, 12], and attention MIL pooling is introduced as one [4]. Those works establish invariance of the mathematical operator on unpadded sets. We address the padded, masked implementation and give the empty-bag convention explicitly. Verification of trained neural networks usually concerns input–output properties of particular weights, such as robustness. Our results hold for all weights and all scorers and concern the aggregation layer only.
9 Conclusion
Masked attention pooling is padding- and permutation-invariant if masked rows contribute zero mass to the normalizer as well as the numerator, and the normalizer is guarded for empty bags. We stated this precisely, proved it in Lean for every finite bag and feature dimension, and connected the proofs to the Jaxpr traced from a JAX kernel for two concrete shapes. The proofs are short, and the main value is the exact specification: it rules out the feature-only masking error and fixes behaviour on empty bags and nonfinite padding. Natural extensions are a certified max-shifted kernel and proofs for encoders placed before pooling.
Code availability
Source, generated files, tests, and the validation log are at https://github.com/y2x0/masked-attention-lean, commit 97978b6. The jax-lean dependency is pinned as a sub-module at revision
570aed69049f8e2931df9f55175313a340bcb456.
The full check runs with ./scripts/check.sh.
Acknowledgments
Claude (Anthropic, Claude Opus 5.5) helped write and revise this manuscript from the project's source, documentation, and validation record. The authors reviewed the text and take full responsibility for its content.
References
[1] G. Campanella, M. G. Hanna, L. Geneslaw, A. Miraflor, V. Werneck Krauss Silva, K. J. Busam, E. Brogi, V. E. Reuter, D. S. Klimstra, and T. J. Fuchs. Clinical-grade computational pathology using weakly supervised deep learning on whole slide images. Nature Medicine, 25(8):1301–1309, 2019.
[2] T. G. Dietterich, R. H. Lathrop, and T. Lozano-Pérez. Solving the multiple instance problem with axis-parallel rectangles. Artificial Intelligence, 89(1–2):31–71, 1997.
[3] D. Goldberg. What every computer scientist should know about floating-point arithmetic. ACM Computing Surveys, 23(1):5–48, 1991.
[4] M. Ilse, J. M. Tomczak, and M. Welling. Attention-based deep multiple instance learning. In Proceedings of the 35th International Conference on Machine Learning, volume 80 of PMLR, pages 2127–2136, 2018.
[5] J. Bradbury, R. Frostig, P. Hawkins, M. J. Johnson, C. Leary, D. Maclaurin, G. Necula, A. Paszke, J. VanderPlas, S. Wanderman-Milne, and Q. Zhang. JAX: composable transformations of Python+NumPy programs, 2018. https://github.com/jax-ml/jax.
[6] S. Rush. jax-lean: provably correct tensor puzzles. Software, https://github.com/srush/jax-lean, revision 570aed6, 2026.
[7] L. de Moura and S. Ullrich. The Lean 4 theorem prover and programming language. In Automated Deduction – CADE 28, volume 12699 of Lecture Notes in Computer Science, pages 625–635. Springer, 2021. doi:10.1007/978-3-030-79876-5_37.
[8] J. Lee, Y. Lee, J. Kim, A. Kosiorek, S. Choi, and Y. W. Teh. Set transformer: a framework for attention-based permutation-invariant neural networks. In Proceedings of the 36th International Conference on Machine Learning, volume 97 of PMLR, pages 3744–3753, 2019.
[9] M. Y. Lu, D. F. K. Williamson, T. Y. Chen, R. J. Chen, M. Barbieri, and F. Mahmood. Data-efficient and weakly supervised computational pathology on whole-slide images. Nature Biomedical Engineering, 5(6):555–570, 2021.
[10] The mathlib Community. The Lean mathematical library. In Proceedings of the 9th ACM SIGPLAN International Conference on Certified Programs and Proofs (CPP 2020), 2020. doi:10.1145/3372885.3373824.
[11] D. Selsam, P. Liang, and D. L. Dill. Developing bug-free machine learning systems with formal mathematics. In Proceedings of the 34th International Conference on Machine Learning, volume 70 of PMLR, pages 3047–3056, 2017.
[12] M. Zaheer, S. Kottur, S. Ravanbakhsh, B. Póczos, R. R. Salakhutdinov, and A. J. Smola. Deep sets. In Advances in Neural Information Processing Systems 30, 2017.