[do-not-merge] approximate non-linearities and CKKS management for Transformers - #3402
Open
copybara-service[bot] wants to merge 1 commit into
Open
copybara-service[bot] wants to merge 1 commit into
copybara-service[bot] wants to merge 1 commit into
Conversation
copybara-service
Bot
force-pushed
the
test_976542552
branch
from
September 5, 2026 01:30
5946edf to
bfef532
Compare
…ansformers
Introduce polynomial approximation pipelines, numerical stability passes,
padding tracking, and scale/bootstrap management optimizations required for
evaluating deep CKKS Transformer models (e.g. BERT-tiny SST-2):
- Frontend canonicalization & domain stamping:
- Add PrepareForLayoutPropagation to canonicalize PyTorch and torch-mlir
export idioms before layout assignment (folding unit-dimension reshapes
and transposes, bias additions into matmuls, and raising generic
subgraphs to linalg).
- Add StampApproximationDomains to attach calibrated approximation interval
attributes to bare math.rsqrt and math.erf ops from unannotated PyTorch
exports, supplying domain bounds and degrees for Chebyshev approximations.
- Numerically stable non-linearities (Softmax, GELU, & Reciprocal):
- Add SoftmaxToNsSoftmax to lower Softmax to normalize-and-square form with
exact compile-time zero-padding cancellation, preventing exponential
overflow in attention matrices.
- Add LowerRecip to lower math_ext.reciprocal using self-correcting
Goldschmidt iterations with calibrated polynomial seeds, preventing NaN
divergence across stacked transformer layers.
- Extend PolynomialApproximation to support operations pinning
approximation_method = "chebyshev" (and "hermite") to enforce
Carathéodory-Fejér minimax polynomial fitting over Taylor series.
- Padding semantics propagation:
- Introduce #tensor_ext.padding attribute, PaddingSemanticsOpInterface, and
PropagatePadding pass to derive trailing zero-padding metadata across
matmuls, transposes, broadcasts, reductions, and elementwise ops.
- Prevent interleaved padding elements in CRT slot layouts from corrupting
reduction statistics in LayerNorm and Softmax.
- Strip padding attributes during TensorExtToTensor conversion.
- CKKS scale management & underdetermined scale resolution:
- Extend ScaleAnalysis and PopulateScaleCKKS to resolve underdetermined
adjust_scale operations in multi-branch DAGs where both join operands
arrive through adjust_scale and modreduce chains.
- Assign consistent canonical target scales (logDefaultScale + logq before
modreduce, or logDefaultScale) to prevent scale inference failures and
mismatches at residual addition joins.
- Secret insert management & bootstrap optimizations:
- Hoist shared bootstraps before rotation fan-out operations when sibling
bootstraps share a common source root in SecretInsertMgmtCKKS.
- Skip terminal refreshes when remaining multiplicative depth is sufficient
to complete the computation without an extra bootstrap.
- Emit adjust_scale and modreduce before bootstrap operations so
bootstrapped ciphertexts are guaranteed to be at base scale, preventing
runtime modulus panics in Lattigo.
- Fix waterline calculation when levelBudget == -1 to prevent spurious
bootstraps in unbudgeted modules.
- Testing:
- Add lit test suites for prepare_for_layout_propagation,
stamp_approximation_domains, polynomial_approximation, propagate_padding,
softmax_to_ns_softmax, lower_recip, and populate_scale.
- Add targeted SecretInsertMgmt lit tests for fan-out bootstrap hoisting,
skipping terminal refreshes, and base-scale bootstrap insertion.
- Align bootstrap_placement_comparison greedy budget with ILP waterline 3.
PiperOrigin-RevId: 976542552
copybara-service
Bot
force-pushed
the
test_976542552
branch
from
September 5, 2026 01:36
bfef532 to
1e33b6d
Compare
copybara-service Bot
pushed a commit
that referenced
this pull request
Sep 5, 2026
…ipeline Introduce the LowerPadToIdentityMatmul pass and pipeline controls to lower zero-padding operations on secret tensors into cleartext identity matrix multiplications, avoiding irregular shift networks during layout conversion. This change is stacked on top of all experimental pending commits: - cl/974067900 (or GitHub PR #3388): cyclic layout support for Transformers - cl/976505644 (or GitHub PR #3400): Lattigo backend support and CKKS fixes - cl/976542552 (or GitHub PR #3402): approximate non-linearities and management - LowerPadToIdentityMatmul pass: - Rewrite static zero tensor.pad ops on secret tensors to explicit linalg.matmul or linalg.batch_matmul with cleartext identity diagonal matrices (P_L * X for row padding, X * P_R for column padding). - Handle 2D tensors ([M, K] -> [M', K']) and 3D batched tensors ([H, M, K] -> [H, M', K']) across row padding, column padding, and simultaneous 2D padding via sequential Left and Right PCMM. - Leverage structured BSGS rotate-and-reduce schedules (2*sqrt(n) Galois keys) of existing Left and Right PCMM kernels, completely avoiding irregular shift networks and eliminating hundreds of Galois rotation keys. - CKKS pipeline integration: - Introduce --enable-identity-pcmm-padding in ArithmeticPipelineRegistration to wire LowerPadToIdentityMatmul into the mlirToRLWE CKKS pipeline prior to layout propagation. - Follow identity PCMM lowering with canonicalization and CSE to fold intermediate structures. - Register createLowerPadToIdentityMatmul pass in heir-opt. - Waterline analysis & forced bootstrapping: - Support mgmt.force_bootstrap attribute in BootstrapWaterlineAnalysis to force bootstrap placement on critical join operations where level consumption must be reset. PiperOrigin-RevId: 976603963
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
[do-not-merge] approximate non-linearities and CKKS management for Transformers
Introduce polynomial approximation pipelines, numerical stability passes,
padding tracking, and scale/bootstrap management optimizations required for
evaluating deep CKKS Transformer models (e.g. BERT-tiny SST-2):
Frontend canonicalization & domain stamping:
export idioms before layout assignment (folding unit-dimension reshapes
and transposes, bias additions into matmuls, and raising generic
subgraphs to linalg).
attributes to bare math.rsqrt and math.erf ops from unannotated PyTorch
exports, supplying domain bounds and degrees for Chebyshev approximations.
Numerically stable non-linearities (Softmax, GELU, & Reciprocal):
exact compile-time zero-padding cancellation, preventing exponential
overflow in attention matrices.
Goldschmidt iterations with calibrated polynomial seeds, preventing NaN
divergence across stacked transformer layers.
approximation_method = "chebyshev" (and "hermite") to enforce
Carathéodory-Fejér minimax polynomial fitting over Taylor series.
Padding semantics propagation:
PropagatePadding pass to derive trailing zero-padding metadata across
matmuls, transposes, broadcasts, reductions, and elementwise ops.
reduction statistics in LayerNorm and Softmax.
CKKS scale management & underdetermined scale resolution:
adjust_scale operations in multi-branch DAGs where both join operands
arrive through adjust_scale and modreduce chains.
modreduce, or logDefaultScale) to prevent scale inference failures and
mismatches at residual addition joins.
Secret insert management & bootstrap optimizations:
bootstraps share a common source root in SecretInsertMgmtCKKS.
to complete the computation without an extra bootstrap.
bootstrapped ciphertexts are guaranteed to be at base scale, preventing
runtime modulus panics in Lattigo.
bootstraps in unbudgeted modules.
Testing:
stamp_approximation_domains, polynomial_approximation, propagate_padding,
softmax_to_ns_softmax, lower_recip, and populate_scale.
skipping terminal refreshes, and base-scale bootstrap insertion.