Skip to content

Generic matmul-based expansion for all-axis mean reduction #128

Description

@AlekseiChirkovVention

Context

While reviewing how downstream consumers adopt framework-owned dependency analysis, lowering, and optimizer tracing, we identified one piece of lowering logic that is not backend-specific and can be generalized in tinychain.autodiff instead of being reimplemented by every consumer.

The mean expansion rewrites an all-axis rank-2 MeanOperator into:

  1. a MATMUL against a column of ones for row-sum reduction,
  2. a MATMUL against a row of ones for column-sum reduction,
  3. a scalar MUL by 1 / (rows * cols).

The core arithmetic uses matrix multiplication and multiplication. Opt-in expanded artifacts represent generated tensor-valued ones with a zero-input FillOperator and, for keepdims=False, represent the truthful [1, 1] to scalar rank transition with a trivial ReshapeOperator. These explicit operators prevent hidden operands and false output shapes.

Decision

The expanded-handler contract is accepted. Backends consuming opt-in expanded artifacts must support FillOperator in both tiers and trivial ReshapeOperator for the rank-reducing tier. MatmulOperator remains an ordinary two-operand operator. Existing non-expanded lowering contracts remain unchanged.

Proposal

Add reusable opt-in expansion passes to tinychain.autodiff, alongside lower_graph and lower_derivative_program, that expand a supported all-axis MeanOperator and the exact generated mean-VJP broadcast-scale region into matmul-based arithmetic with explicit constants and truthful rank changes.

Backends with a native reduce operation remain unaffected unless they explicitly run an expansion pass.

Acceptance criteria

  • Public tinychain.autodiff APIs expand a supported all-axis mean and the exact generated mean-VJP broadcast-scale region for backends without a native reduce operation.
  • Expansion is opt-in and off by default; existing non-expanded lowered output and handler requirements do not change.
  • Expanded artifacts use a zero-input FillOperator for generated tensor-valued constants in both tiers.
  • For keepdims=False, expanded artifacts use a trivial ReshapeOperator for the truthful [1, 1] to scalar rank transition.
  • MatmulOperator remains an ordinary two-operand operator, and every emitted output_typespec matches the true operation result.
  • A backend missing a handler required by an expanded artifact fails closed with unsupported_operator before any handler runs.
  • Numerical equivalence between expanded and non-expanded lowering is validated against a generic limited-operation reference consumer used only for testing.

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions