Skip to content

[do-not-merge] approximate non-linearities and CKKS management for Transformers - #3402

Open
copybara-service[bot] wants to merge 1 commit into
mainfrom
test_976542552
Open

copybara-service[bot] wants to merge 1 commit into
mainfrom
test_976542552

Conversation

@copybara-service

Copy link
Copy Markdown
Contributor

[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:

    • 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.

…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 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant