Skip to content

API Reference

This page is generated from clifra's source docstrings. Public documented modules, classes, methods, functions, and attributes are included once from their defining modules. Private names and undocumented implementation details are omitted.

Algebra and Runtime

config

Algebra construction config.

AlgebraConfig dataclass

Planner-first algebra declaration.

Parameters:

Name Type Description Default
p int

Number of positive-square basis vectors.

required
q int

Number of negative-square basis vectors.

0
r int

Number of null basis vectors.

0
device str

PyTorch device used by planned executor buffers.

'cuda'
dtype dtype

Floating-point dtype used by the algebra host.

float32
default_grades Optional[tuple[int, ...]]

Optional grade set returned by algebra.layout().

None
planning_limits Optional[PlanningLimits]

Optional injected lane and interaction limits.

None
product_execution_policy Optional[ProductExecutionPolicy]

Optional injected product-executor cost model.

None
bivector_exp_execution_policy Optional[BivectorExpExecutionPolicy]

Optional injected bivector exponential policy.

None

from_mapping(config, **overrides) classmethod

Build an algebra declaration from a mapping-like config.

Explicit non-None keyword overrides take precedence over mapping values, including all injected planning and execution policies.

make_algebra(p, q=0, r=0, *, device='cuda', dtype=torch.float32, default_grades=None, planning_limits=None, product_execution_policy=None, bivector_exp_execution_policy=None)

Construct the planner-owned algebra host.

Planning limits and executor policies are stored on the returned host and shared by every layout, plan, and layer built from it.

make_algebra_from_config(config, **overrides)

Construct an algebra from a mapping-like config.

The mapping accepts every :class:AlgebraConfig field. Explicit non-None overrides take precedence over values from the mapping.

formatting

Debug formatting for multivector coefficient tensors.

This module intentionally avoids algebra operations. Multivector is a display proxy for development and logging, not a runtime tensor wrapper.

Multivector dataclass

Lightweight display proxy for multivector coefficient tensors.

The proxy stores only formatting options and never overloads arithmetic. Compact tensors must be declared with layout or grades so the formatter can map lanes to blade labels without guessing.

format(*, sample=None, include_shape=True)

Return a blade-term string for the tensor or one tensor sample.

format_multivector(algebra, values, *, layout=None, grades=None, name=None, max_terms=16, precision=4, atol=None, sample=None, include_shape=True)

Format a coefficient tensor as a sum of basis-blade terms.

Full tensors are recognized by values.shape[-1] == algebra.dim. Compact tensors require layout or grades. Batched tensors format a single sample by default to keep debug output bounded.

basis_blade_label(index, *, n, scalar='1', prefix='e')

Return the canonical display label for a basis blade bitmask.

basis

Canonical bitmask-basis utilities for Clifford algebra planning.

normalize_grade_product_op(op)

Return the internal grade-product key for a public product operation name.

normalize_grades(grades, n, *, name='grades')

Return sorted unique grades validated against 0 <= grade <= n.

basis_index_tuple_for_grades(n, grades)

Return canonical bitmask basis indices whose popcount is in grades.

basis_count_for_grades(n, grades)

Return the number of basis blades represented by grades.

basis_indices_for_grades(n, grades, *, device=None)

Return canonical bitmask basis indices as a tensor.

basis_indices_tensor(indices, *, n=None, role='basis indices', device=None)

Tensorize canonical basis bitmasks with a clear signed-int64 boundary.

geometric_product_output_grades(left_grade, right_grade, n)

Return the possible output grades of a homogeneous geometric product.

expand_output_grades(left_grades, right_grades, n, *, op='gp', project_grades=None)

Expand input grade sets into output grades required by op.

product_output_grades(left_grade, right_grade, n, *, op='gp')

Return possible output grades for one homogeneous product route.

basis_product(index_a, index_b, p, q, r)

Return (index, sign) for two canonical basis blade products.

reverse_sign(index)

Return the reversion sign for a canonical basis blade.

operation_coefficient(index_a, index_b, p, q, r, op)

Return the scalar coefficient multiplying A_i * B_j for op.

operation_may_be_nonzero(index_a, index_b, p, q, r, op)

Return whether an operator can have a non-zero coefficient for a basis pair.

device

Low-level device and dtype helpers.

Core algebra uses this module only for device and dtype normalization. The DeviceConfig class is retained as a direct-module training convenience for application code that wants one place to coordinate pin_memory, torch.compile, cudnn.benchmark, and AMP.

DeviceConfig dataclass

Resolved device / backend settings for application training loops.

Attributes:

Name Type Description
device str

Resolved device string (cuda, mps, cpu).

pin_memory bool | None

Whether DataLoaders should pin memory. None -> auto (True for CUDA).

num_workers int | None

DataLoader worker count. None -> auto (4 for CUDA, 2 otherwise).

compile_model bool

Wrap the model with :func:torch.compile.

compile_backend str | None

torch.compile backend. None -> auto (aot_eager for MPS, inductor for CUDA/CPU). MPS does not fully support the inductor backend.

amp bool

Enable automatic mixed precision (CUDA only).

amp_dtype dtype | str | None

Optional autocast dtype. None uses PyTorch's autocast default; explicit values should be float16 or bfloat16.

cudnn_benchmark bool | None

Set :attr:torch.backends.cudnn.benchmark. None -> auto (True for CUDA).

apply_backend_settings()

Apply cudnn.benchmark, TF32 matmul precision, etc.

maybe_compile(model)

Optionally wrap model with :func:torch.compile.

get_scaler()

Return a :class:GradScaler when AMP is active, else None.

autocast_context()

Return an autocast context manager or :func:nullcontext.

optional_dtype(value)

Parse a torch dtype declaration, preserving None as unset.

resolve_dtype(value, default=torch.float32)

Parse a torch dtype declaration and fall back to default when unset.

dtype_name(dtype)

Return the canonical short name for a torch dtype.

resolve_device(device='auto')

Resolve 'auto' to the best available accelerator.

Priority: cuda > mps > cpu.

host

Shared algebra host API for planner-owned layout contracts.

AlgebraHostMixin

Planner-facing algebra API with no runtime layout inference.

layout(grades=None)

Return the declared grade layout, or the host default layout.

default_layout()

Return the configured default layout, falling back to all grades.

resolve_layout(*, layout=None, grades=None, mv=None)

Resolve explicit layout metadata. Tensor inspection is intentionally not supported.

grade_indices(grades, *, device=None)

Return canonical basis indices for grades.

conjugate_scalar_form_signs(layout=None, *, grades=None, device=None, dtype=None)

Return signs for the signed Clifford-conjugation scalar form.

product_executor(*, left_grades, right_grades, op='gp', output_grades=None, dtype=None, device=None, cache=True)

Return a preplanned product executor.

plan_product(*, op='gp', left_grades=None, right_grades=None, output_grades=None, left_layout=None, right_layout=None, output_layout=None, dtype=None, device=None, cache=True)

Return an compact-lane product handle with no runtime request inference.

plan_unary(*, op, input_grades=None, output_grades=None, input_layout=None, output_layout=None, dtype=None, device=None, cache=True)

Return an compact-lane unary handle with no runtime request inference.

plan_signature_norm_squared(*, grades=None, input_grades=None, layout=None, input_layout=None, dtype=None, device=None, cache=True)

Return a signed signature-norm executor for declared compact-lane values.

plan_pseudoscalar_product(*, input_grades=None, output_grades=None, input_layout=None, output_layout=None, dtype=None, device=None, cache=True)

Return a right-pseudoscalar product executor for compact-lane values.

plan_bivector_exp(*, input_grades=None, output_grades=None, input_layout=None, output_layout=None, dtype=None, device=None, cache=True, spectral_max_planes=None, spectral_tol_abs=None, spectral_tol_rel=None, spectral_dominant_rel=None, spectral_transition_n=None, spectral_allow_degenerate=None, spectral_allow_truncated_degenerate=None)

Return a bivector exponential executor for compact-lane values.

plan_sandwich_action(*, layout=None, dtype=None, device=None, cache=True)

Return a full-layout sandwich action handle.

plan_versor_action(*, grade, input_grades=None, output_grades=None, input_layout=None, output_layout=None, parameter_layout=None)

Return a grade-1 or grade-2 versor action handle.

plan_multi_versor_action(*, grade, input_grades=None, output_grades=None, input_layout=None, output_layout=None, parameter_layout=None)

Return a weighted multi-versor action handle.

plan_paired_bivector_action(*, input_grades=None, output_grades=None, input_layout=None, output_layout=None, parameter_layout=None)

Return an independent left/right bivector action handle.

projected_product(A, B, *, left_grades=None, right_grades=None, output_grades=None, left_layout=None, right_layout=None, output_layout=None, op='gp', left_storage=None, right_storage=None, output_storage=LaneStorage.COMPACT, return_layout=False, pairwise=False)

Execute a planner-resolved grade-restricted product.

projected_geometric_product(A, B, **kwargs)

Projected geometric product convenience wrapper.

projected_wedge(A, B, **kwargs)

Projected wedge product convenience wrapper.

symmetric_product(A, B, **kwargs)

Apply the normalized anti-commutator (A B + B A) / 2.

commutator_product(A, B, **kwargs)

Apply the commutator A B - B A.

anti_commutator_product(A, B, **kwargs)

Apply the unnormalized anti-commutator A B + B A.

projected_left_contraction(A, B, **kwargs)

Projected left contraction convenience wrapper.

projected_right_contraction(A, B, **kwargs)

Projected right contraction convenience wrapper.

left_contraction(A, B, **kwargs)

Apply left contraction through a planned product executor.

right_contraction(A, B, **kwargs)

Apply right contraction through a planned product executor.

planned_unary(values, *, op, input_grades=None, output_grades=None, input_layout=None, output_layout=None, input_storage=None, output_storage=LaneStorage.COMPACT, return_layout=False)

Execute a unary operation through the planner.

signature_norm_squared(values, *, grades=None, input_grades=None, layout=None, input_layout=None)

Return <values reverse(values)>_0 through a planned diagonal executor.

pseudoscalar_product(values, *, input_grades=None, output_grades=None, input_layout=None, output_layout=None, output_storage=LaneStorage.COMPACT, return_layout=False)

Apply right multiplication by the unit pseudoscalar.

bivector_exp(values, *, input_grades=None, output_grades=None, input_layout=None, output_layout=None, spectral_max_planes=None, spectral_tol_abs=None, spectral_tol_rel=None, spectral_dominant_rel=None, spectral_transition_n=None, spectral_allow_degenerate=None, spectral_allow_truncated_degenerate=None, output_storage=LaneStorage.COMPACT, return_layout=False)

Exponentiate a declared bivector through a planner-owned executor.

blade_inverse(blade, *, grades=None, input_grades=None, layout=None, input_layout=None, return_layout=False)

Return reverse(blade) / <blade reverse(blade)>_0 through planned executors.

blade_project(values, blade, *, input_grades=None, blade_grades=None, output_grades=None, input_layout=None, blade_layout=None, output_layout=None, return_layout=False)

Project values onto a blade subspace through left contraction.

blade_reject(values, blade, *, input_grades=None, blade_grades=None, output_grades=None, input_layout=None, blade_layout=None, output_layout=None, return_layout=False)

Reject values from a blade subspace through planned projection.

reflect(values, normal, *, input_grades=None, normal_grades=None, output_grades=None, input_layout=None, normal_layout=None, output_layout=None, return_layout=False)

Reflect values through a vector normal using planned products.

versor_product(versor, values, *, versor_grades=None, input_grades=None, output_grades=None, versor_layout=None, input_layout=None, output_layout=None, return_layout=False)

Apply grade_involution(versor) * values * inverse(versor) through planned products.

planned_linear_action(values, matrix, *, input_grades=None, output_grades=None, input_layout=None, output_layout=None, return_layout=False)

Execute a planned vector-space linear action.

sandwich_action_matrices(left, right=None, *, layout=None)

Return full-layout sandwich action matrices through the planner.

sandwich_product(left, values, right=None, *, layout=None)

Apply one full-layout sandwich action per leading batch item.

per_channel_sandwich(left, values, right=None, *, layout=None)

Apply one full-layout sandwich action per channel.

multi_rotor_sandwich(left, values, right=None, *, layout=None)

Apply every full-layout sandwich action to every input channel.

versor_action(values, weights, **kwargs)

Execute a planned grade-1 or grade-2 versor action.

multi_versor_action(values, weights, mix, **kwargs)

Execute a planned weighted grade-1 or grade-2 versor action.

paired_bivector_action(values, left_weights, right_weights, channel_to_pair, **kwargs)

Execute a planned independent left/right bivector rotor action.

grade_norms(values, *, input_grades=None, layout=None)

Return per-grade coefficient norms for declared-layout values.

multivector(values, **kwargs)

Return a debug-only multivector formatter for values.

format_multivector(values, **kwargs)

Format values as basis-blade terms for debugging.

layout

Static algebra and compact grade-layout value objects.

AlgebraSpec dataclass

Immutable Clifford signature metadata used by grade planners.

n property

Number of basis vectors.

dim property

Number of canonical basis blades.

from_algebra(algebra) classmethod

Build a spec from any algebra-like object with p, q, and r attributes.

layout(grades)

Return a compact layout for grades.

full_layout()

Return the canonical all-grades layout.

Full is only a grade set: grades 0..n in canonical basis order. It is not a separate runtime storage mode.

GradeLayout dataclass

Compact basis-lane layout for a fixed grade set.

basis_indices property

Canonical basis indices represented by this compact layout.

dim property

Number of compact lanes.

full_dim property

Full multivector lane dimension.

contains_grade(grade)

Return whether grade is present in this layout.

indices_tensor(*, device=None)

Return basis indices as a tensor on device.

grade_indices_tensor(*, device=None)

Return per-lane grade ids on device.

positions_for_grades(grades, *, device=None)

Return compact lane positions for the requested grades.

convert(values, source)

Convert compact values from source into this layout.

Shared basis lanes are copied by canonical basis index. Lanes present in this layout but absent from source are filled with zeros, which makes the method usable for both projections and sparse layout unions without materializing a full-lane multivector.

compact(full)

Gather compact lanes from a full-lane multivector tensor.

full(values)

Materialize compact lane values into a full-lane multivector tensor.

manifold

Optimizer dispatch tags for framework parameters.

The three labels select the retraction applied by clifra's optimizers; layers and actions provide the geometric interpretation.

format_valid_manifolds()

Return a stable, user-facing list of supported manifold names.

validate_manifold(manifold)

Validate and return an optimizer manifold tag.

tag_manifold(param, manifold)

Tag a parameter for optimizer retraction dispatch and return it.

module

Base PyTorch module for components that share a Clifford algebra.

AlgebraLike

Bases: Protocol

Protocol implemented by planner-capable algebra hosts and references.

device property

Return the device of algebra-owned buffers.

dtype property

Return the dtype of algebra-owned floating-point buffers.

layout(grades=None)

Return a compact grade layout or the algebra's default layout.

default_layout()

Return the algebra default layout.

resolve_layout(*, layout=None, grades=None, mv=None)

Resolve static layout metadata for tensors or multivectors.

grade_indices(grades, *, device=None)

Return canonical basis indices for grades.

conjugate_scalar_form_signs(layout=None, *, grades=None, device=None, dtype=None)

Return signs for the signed Clifford-conjugation scalar form.

projected_product(A, B, **kwargs)

Apply a declared grade-restricted binary product.

plan_product(**kwargs)

Return a hot-path product handle for compact-lane values.

plan_unary(**kwargs)

Return a hot-path unary handle for compact-lane values.

plan_signature_norm_squared(**kwargs)

Return a signed signature-norm executor for compact-lane values.

plan_pseudoscalar_product(**kwargs)

Return a right-pseudoscalar product executor for compact-lane values.

plan_bivector_exp(**kwargs)

Return a bivector exponential executor for compact-lane values.

plan_sandwich_action(**kwargs)

Return a full-layout sandwich action handle.

plan_versor_action(**kwargs)

Return a grade-1 or grade-2 versor action handle.

plan_multi_versor_action(**kwargs)

Return a weighted multi-versor action handle.

plan_paired_bivector_action(**kwargs)

Return an independent left/right bivector action handle.

geometric_product(A, B, **kwargs)

Apply the geometric product.

wedge(A, B, **kwargs)

Apply the exterior product.

symmetric_product(A, B, **kwargs)

Apply the normalized anti-commutator (A B + B A) / 2.

commutator_product(A, B, **kwargs)

Apply the commutator A B - B A.

anti_commutator_product(A, B, **kwargs)

Apply the unnormalized anti-commutator A B + B A.

left_contraction(A, B, **kwargs)

Apply left contraction.

right_contraction(A, B, **kwargs)

Apply right contraction.

grade_projection(mv, grade, **kwargs)

Project to a single grade.

reverse(mv, **kwargs)

Apply reversion.

grade_involution(mv, **kwargs)

Apply grade involution.

clifford_conjugation(mv, **kwargs)

Apply Clifford conjugation.

signature_norm_squared(mv, **kwargs)

Return the signed Clifford signature norm squared.

pseudoscalar_product(mv, **kwargs)

Apply right multiplication by the pseudoscalar.

blade_inverse(blade, **kwargs)

Return the inverse of a non-null blade.

blade_project(values, blade, **kwargs)

Project values onto a blade subspace.

blade_reject(values, blade, **kwargs)

Reject values from a blade subspace.

reflect(values, normal, **kwargs)

Reflect values through a vector normal.

versor_product(versor, values, **kwargs)

Apply a general versor product.

bivector_exp(mv, **kwargs)

Exponentiate a declared bivector.

planned_linear_action(values, matrix, **kwargs)

Apply a vector-space linear action to full-lane or compact grade lanes.

sandwich_action_matrices(left, right=None, **kwargs)

Return full-layout sandwich action matrices.

sandwich_product(left, values, right=None, **kwargs)

Apply one full-layout sandwich action per leading batch item.

per_channel_sandwich(left, values, right=None, **kwargs)

Apply one full-layout sandwich action per channel.

multi_rotor_sandwich(left, values, right=None, **kwargs)

Apply every full-layout sandwich action to every input channel.

versor_action(values, weights, **kwargs)

Apply a planned grade-1 or grade-2 versor action.

multi_versor_action(values, weights, mix, **kwargs)

Apply a planned weighted grade-1 or grade-2 versor action.

paired_bivector_action(values, left_weights, right_weights, channel_to_pair, **kwargs)

Apply independent left/right bivector rotor pairs.

grade_norms(values, **kwargs)

Return per-grade coefficient norms for declared-layout values.

multivector(values, **kwargs)

Return a debug-only multivector formatter for values.

format_multivector(values, **kwargs)

Format values as basis-blade terms for debugging.

CliffordModule

Bases: Module

Base module for Clifford algebra-aware components.

CliffordModule belongs to :mod:core because it is shared by layers, criteria, and functional modules. Keeping it out of :mod:layers prevents functional code from importing the eager layer package just to subclass this base type.

The module stores a shared algebra reference without registering it as a PyTorch submodule. In clifra, one algebra instance often owns the precomputed geometric tensors used by many modules.

algebra property

Return the shared algebra instance.

p property

Return the algebra's positive metric dimension.

q property

Return the algebra's negative metric dimension.

r property

Return the algebra's null metric dimension.

__init__(algebra)

Set up the module with a shared algebra instance.

forward(x)

Perform the forward pass computation.

numerics

Numerical guard helpers shared across clifra core and layers.

eps_for(dtype, *, multiplier=1.0, min_value=0.0)

Return a floating-point epsilon scaled for dtype.

eps_like(values, *, multiplier=1.0, min_value=0.0)

Return a dtype-aware epsilon for values.

signed_clamp_min(values, eps)

Clamp magnitude while preserving denominator sign.

covariance_regularizer(covariance, *, multiplier=DEFAULT_EPS_MULTIPLIER)

Return a scale-aware diagonal regularizer for covariance matrices.

validation

Lightweight input validation for clifra tensors.

Assertion helpers use assert so they are free under python -O. Set VALIDATE = False to disable even without the -O flag.

Public boundary validators raise ValueError. They intentionally remain enabled outside the hot unchecked executor paths.

check_multivector(x, algebra, name='x')

Assert x looks like a multivector for algebra.

Checks x.ndim >= 1 and x.shape[-1] == algebra.dim.

check_channels(x, expected, name='x')

Assert the channel dimension of x equals expected.

Assumes layout [Batch, Channels, Dim] (ndim >= 3, channel at -2).

validate_layout_lanes(values, layout, name='values')

Validate that the trailing lane axis matches layout.

validate_channel_values(values, layout, channels, name='values')

Validate [..., channels, lanes] tensors against a grade layout.

algebra

Differentiable Clifford Algebra core.

Implements the geometric product, grade projections, and rotor operations for arbitrary signatures Cl(p, q, r).

AlgebraContext

Bases: AlgebraHostMixin

Signature and planning host for layout-first Clifford Algebra.

device property

Return the context device used for planned executor buffers.

dtype property

Return the context floating-point dtype.

bivector_squared_signs(*, device=None, dtype=None)

Return (e_ab)^2 signs in canonical grade-2 layout order.

to(device=None, dtype=None)

Move the context and cached executors.

geometric_product(A, B, **kwargs)

Plan and execute a geometric product.

wedge(A, B, **kwargs)

Plan and execute an exterior product.

symmetric_product(A, B, **kwargs)

Plan and execute the normalized anti-commutator (A B + B A) / 2.

commutator_product(A, B, **kwargs)

Plan and execute the commutator A B - B A.

anti_commutator_product(A, B, **kwargs)

Plan and execute the unnormalized anti-commutator A B + B A.

grade_projection(mv, grade, **kwargs)

Project declared multivector coefficients to one grade.

embed_vector(vectors)

Embed grade-1 vector coordinates into full-lane multivector coefficients.

reverse(mv, **kwargs)

Reverse full-lane or compact multivector coefficients.

grade_involution(mv, **kwargs)

Apply grade involution to full-lane or compact multivector coefficients.

clifford_conjugation(mv, **kwargs)

Apply Clifford conjugation to full-lane or compact multivector coefficients.

bivector_exp(mv, *, input_grades=None, output_grades=None, input_layout=None, output_layout=None, spectral_max_planes=None, spectral_tol_abs=None, spectral_tol_rel=None, spectral_dominant_rel=None, spectral_transition_n=None, spectral_allow_degenerate=None, spectral_allow_truncated_degenerate=None, output_storage=LaneStorage.COMPACT, return_layout=False)

Exponentiate a declared bivector through the shared planner route.

energy

Positive-definite coefficient-lane geometry.

lane_dot_product(algebra, A, B, *, layout=None, grades=None)

Return the positive-definite coefficient dot product over compact lanes.

lane_energy(algebra, values, *, layout=None, grades=None)

Return positive-definite coefficient energy sum_i x_i**2.

lane_norm(algebra, values, *, layout=None, grades=None)

Return positive-definite coefficient norm.

lane_distance(algebra, A, B, *, layout=None, grades=None)

Return positive-definite coefficient distance.

lane_grade_energy(algebra, values, *, layout=None, grades=None)

Return per-grade positive coefficient energy.

lane_grade_norms(algebra, values, *, layout=None, grades=None)

Return per-grade positive coefficient norms.

lane_grade_distribution(algebra, values, *, layout=None, grades=None, eps=1e-08)

Return normalized per-grade lane-energy distribution.

forms

Algebraic scalar forms that may be indefinite or degenerate.

conjugate_scalar_form_signs(algebra, layout=None, *, grades=None, device=None, dtype=None)

Return signs for <bar(A) B>_0 in a compact layout.

conjugate_scalar_form(algebra, A, B, *, layout=None, left_layout=None, right_layout=None, grades=None, left_grades=None, right_grades=None)

Return the signed Clifford-conjugation scalar form <bar(A) B>_0.

conjugate_form_magnitude(algebra, values, *, layout=None, grades=None)

Return sqrt(abs(<bar(A) A>_0)) for the signed conjugate form.

conjugate_form_distance_like(algebra, A, B, *, layout=None, left_layout=None, right_layout=None, grades=None, left_grades=None, right_grades=None)

Return sqrt(abs(<bar(A-B) (A-B)>_0)); not a metric in general.

conjugate_grade_magnitude_spectrum(algebra, values, *, layout=None, grades=None)

Return per-grade absolute signed conjugate-form magnitudes.

signature_trace_form(algebra, A, B)

Return the signed Clifford scalar product <~A B>_0.

signature_norm_squared(algebra, A)

Return the raw signed signature norm squared <A~A>_0.

metric

Metric-facing helpers with explicit positive and signed forms.

Lane geometry is the positive-definite coefficient space used for optimization. Algebraic scalar forms preserve Clifford-signature information and may be indefinite or degenerate.

lane_distance(algebra, A, B, *, layout=None, grades=None)

Return positive-definite coefficient distance.

lane_dot_product(algebra, A, B, *, layout=None, grades=None)

Return the positive-definite coefficient dot product over compact lanes.

lane_energy(algebra, values, *, layout=None, grades=None)

Return positive-definite coefficient energy sum_i x_i**2.

lane_grade_distribution(algebra, values, *, layout=None, grades=None, eps=1e-08)

Return normalized per-grade lane-energy distribution.

lane_grade_energy(algebra, values, *, layout=None, grades=None)

Return per-grade positive coefficient energy.

lane_grade_norms(algebra, values, *, layout=None, grades=None)

Return per-grade positive coefficient norms.

lane_norm(algebra, values, *, layout=None, grades=None)

Return positive-definite coefficient norm.

conjugate_form_distance_like(algebra, A, B, *, layout=None, left_layout=None, right_layout=None, grades=None, left_grades=None, right_grades=None)

Return sqrt(abs(<bar(A-B) (A-B)>_0)); not a metric in general.

conjugate_form_magnitude(algebra, values, *, layout=None, grades=None)

Return sqrt(abs(<bar(A) A>_0)) for the signed conjugate form.

conjugate_grade_magnitude_spectrum(algebra, values, *, layout=None, grades=None)

Return per-grade absolute signed conjugate-form magnitudes.

conjugate_scalar_form(algebra, A, B, *, layout=None, left_layout=None, right_layout=None, grades=None, left_grades=None, right_grades=None)

Return the signed Clifford-conjugation scalar form <bar(A) B>_0.

conjugate_scalar_form_signs(algebra, layout=None, *, grades=None, device=None, dtype=None)

Return signs for <bar(A) B>_0 in a compact layout.

signature_norm_squared(algebra, A)

Return the raw signed signature norm squared <A~A>_0.

signature_trace_form(algebra, A, B)

Return the signed Clifford scalar product <~A B>_0.

scalar_product(algebra, A, B, *, left_layout=None, right_layout=None, left_grades=None, right_grades=None)

Return the Clifford scalar product <A B>_0.

This is an algebraic projection, not the positive-definite optimizer geometry. Use lane_dot_product for Euclidean coefficient geometry.

signature_magnitude(algebra, values)

Return sqrt(abs(<~A A>_0)) for the signed signature form.

signature_distance_like(algebra, A, B)

Return sqrt(abs(<~(A-B) (A-B)>_0)); not a metric in mixed signatures.

grade_purity(algebra, values, grade, *, layout=None, grades=None)

Return the fraction of positive lane energy carried by one grade.

mean_grade(algebra, values, *, layout=None, grades=None)

Return the lane-energy weighted mean grade.

clifford_conjugate(algebra, values)

Return Clifford conjugation, i.e. grade involution after reversion.

tensors

Explicit tensor contracts for Clifford coefficient lanes.

GradeLayout describes the semantic basis subset and order. LaneStorage describes the physical last-axis storage used by an executor or layer.

LaneStorage

Bases: str, Enum

Physical lane storage for a tensor's final coefficient axis.

TensorContract dataclass

Resolved tensor lane contract: one semantic layout plus one storage form.

uses_compact_storage property

Return whether tensor lanes are stored as layout.dim compact lanes.

uses_canonical_storage property

Return whether tensor lanes are stored as canonical spec.dim lanes.

lane_dim property

Return required last-axis lane width.

grades property

Return semantic grades represented by this contract.

compact(spec, layout) classmethod

Return a compact-lane contract for layout.

canonical(spec, layout) classmethod

Return a canonical full-basis storage contract with layout metadata.

validate(values, *, name='value')

Validate that values obeys this contract.

validate_input(values, *, channels, name)

Validate layer input with a channel axis before the lane axis.

to_compact(values)

Return compact values for this contract's semantic layout.

to_canonical(values)

Return canonical full-basis values for this contract's semantic layout.

scalar_mask(*, device=None, dtype=None)

Return a scalar-lane mask for this contract's storage form.

grade_positions(grade, *, device=None)

Return lane positions for one grade in this contract's storage form.

normalize_lane_storage(storage)

Return a validated lane storage enum.

check_layout_spec(spec, layout, name)

Validate that layout belongs to spec.

resolve_layout(algebra_or_spec, *, layout=None, grades=None)

Resolve explicit layout metadata without inspecting tensor shapes.

resolve_contract(algebra_or_spec, *, layout=None, grades=None, storage=LaneStorage.COMPACT)

Resolve a tensor contract from explicit semantic layout and storage.

infer_contract(spec, tensor, *, layout=None, grades=None, storage=None, side='value')

Infer storage at a public boundary, then return an explicit contract.

compact_values(algebra, value, *, layout=None, grades=None)

Return compact values and resolved semantic layout.

canonical_values(algebra, value, *, layout=None, grades=None)

Return canonical full-basis values.

union_layout(algebra_or_spec, left, right)

Return a compact layout containing every grade from left and right.

compact_pair_values(algebra_or_spec, left, right, *, layout=None, left_layout=None, right_layout=None, grades=None, left_grades=None, right_grades=None)

Return compact values aligned to one runtime layout.

metric_self_signs(layout, *, device=None, dtype=None)

Return basis self-product signs for a layout.

Planning

action

Intent and layout plans for linear and versor-style actions.

LinearActionPlan dataclass

Resolved contract for a vector-space action lifted to multivector grades.

input_grades property

Return the grades accepted by the action input layout.

output_grades property

Return the grades emitted by the action output layout.

VersorActionPlan dataclass

Resolved contract for grade-1 or grade-2 versor actions.

linear_action property

Return the equivalent linear action over the same input/output layouts.

PairedBivectorActionPlan dataclass

Resolved contract for independent left/right bivector rotor actions.

input_grades property

Return the grades accepted before the paired bivector action.

output_grades property

Return the grades retained after the paired bivector action.

build_linear_action_plan(*, input_layout, output_layout=None)

Build a plan-only linear action contract.

build_versor_action_plan(algebra, *, grade, input_layout, output_layout=None, parameter_layout=None)

Build a plan-only versor action contract.

build_paired_bivector_action_plan(algebra, *, input_layout, output_layout=None, parameter_layout=None)

Build a plan for R_left x R_right_reverse with independent rotors.

Unlike a true versor sandwich R x R~, independent left/right rotors are not generally grade-preserving. The planner therefore expands the default output layout through both geometric products and lets callers explicitly project with output_layout when they want a narrower result.

exp

Static bivector exponential plans and executor-family selection.

BivectorExpExecutionPolicy dataclass

Public policy knobs for planned bivector exponentials.

spectral_local keeps the dominant plane spectrum up to spectral_max_planes. Use the diagnostics in this module when evenly distributed rotation energy would make the clipped tail numerically relevant.

.. caution:: Spectral truncation diagnostics (spectral_exp_angle_diagnostics) are intended for static design-time evaluation or validation/inference logging. Avoid extracting scalar values inside compiled training loops to prevent hardware stream synchronization bottlenecks.

BivectorExpPlan dataclass

Static layout contract for a bivector exponential executor.

SpectralExpPreselection dataclass

Static eligibility record for the spectral-local exp path.

See :data:SPECTRAL_LOCAL_TRUNCATION_NOTICE for the precision caveat when max_planes is smaller than the full orthogonal plane count.

SpectralExpAngleDiagnostics dataclass

Runtime truncation diagnostics for a solver angle spectrum.

SpectralExpUniformTailStress dataclass

Static uniform-energy stress row for spectral-local truncation.

build_bivector_exp_plan(spec, *, input_layout, output_layout, dtype, device, spectral_max_planes=None, spectral_tol_abs=None, spectral_tol_rel=0.0, spectral_dominant_rel=None, spectral_transition_n=10, spectral_allow_degenerate=True, spectral_allow_truncated_degenerate=True)

Build a static plan for the bivector exponential exp(B) where B is grade-2.

spectral_exp_angle_diagnostics(angle_spectrum, *, max_planes=SPECTRAL_LOCAL_MAX_PLANES, sort=True)

Return tail-bound and GVC diagnostics for an actual angle spectrum.

tail_angle_sum_bound is the sum of the omitted absolute plane angles. It is a conservative truncation diagnostic; interpreting it as a bound on a multivector norm requires a specified representation, norm, and the corresponding assumptions. geometric_variance_captured is the retained squared angle energy divided by the total squared angle energy. By default, angles are sorted by absolute value before selecting the dominant planes.

.. note:: This function internally detaches the input tensor to ensure diagnostics are not tracked in autograd.

spectral_exp_uniform_tail_stress(signatures, *, max_planes=SPECTRAL_LOCAL_MAX_PLANES, bivector_norm=1.0)

Estimate worst-case spectral-local clipping for static signatures.

This static stress model assumes angle energy is uniformly distributed across M = n // 2 orthogonal planes, so each angle has magnitude abs(bivector_norm) / sqrt(M). It is intentionally conservative for degenerate signatures; use :func:spectral_exp_angle_diagnostics on the actual solver spectrum for runtime supervision.

format_spectral_exp_uniform_tail_stress(rows)

Format static spectral-local truncation stress rows as a compact table.

spectral_exp_preselection(spec, device, *, dtype, max_planes=None, tol_abs=None, tol_rel=0.0, dominant_rel=None, transition_n=10, allow_degenerate=True, allow_truncated_degenerate=True)

Return the static eligibility record for the spectral-local exp path.

select_bivector_exp_executor_family(spec, device, *, dtype=torch.float32, spectral_max_planes=None, spectral_tol_abs=None, spectral_tol_rel=0.0, spectral_dominant_rel=None, spectral_transition_n=10, spectral_allow_degenerate=True, spectral_allow_truncated_degenerate=True)

Return the planner-selected bivector-exp executor family.

flow

Grade-flow metadata for AoT layout propagation.

GradeFlow dataclass

Static grade/layout metadata passed between planned operations.

grades property

Active grades represented by this flow.

dim property

Compact lane count represented by this flow.

from_grades(spec, grades) classmethod

Create a flow from selected grades.

full(spec) classmethod

Create a full-layout flow.

scalar(spec) classmethod

Create a scalar-only flow.

vector(spec) classmethod

Create a vector-only flow.

project(grades)

Narrow the flow to a subset of selected grades.

unary(op, output_grades=None)

Propagate flow through a unary operation.

product(other, *, op='gp', output_grades=None)

Propagate flow through a bilinear grade product.

merge(other)

Union two flows, e.g. for addition or concatenation.

layouts

Layout and request normalization for static grade planning.

ProductRequest dataclass

Fully resolved static request for one bilinear product.

The request is the planner's intermediate representation. It removes ambiguity from caller input before any executor is built: layouts and lane widths are normalized, and output grades are inferred when callers do not explicitly project them.

left_layout property

Return the resolved layout for the left operand.

right_layout property

Return the resolved layout for the right operand.

output_layout property

Return the resolved layout for the product output.

left_uses_compact_storage property

Return whether the left tensor is already compact.

right_uses_compact_storage property

Return whether the right tensor is already compact.

left_grades property

Return the grades selected from the left operand.

right_grades property

Return the grades selected from the right operand.

output_grades property

Return the grades selected for the product output.

cache_key property

Stable key for executor caching.

check_layout_spec(spec, layout, name)

Validate that layout belongs to spec.

build_product_request(spec, left, right, *, op='gp', left_grades=None, right_grades=None, output_grades=None, left_layout=None, right_layout=None, output_layout=None, left_storage=None, right_storage=None, output_storage=LaneStorage.COMPACT)

Resolve caller input into a static product request.

normalize_product_op(op)

Validate and normalize a product operation name.

resolve_output_layout(spec, *, op, left_layout, right_layout, output_grades=None, output_layout=None)

Resolve the output layout for a product request.

metric

Static metric plans for diagonal Clifford forms.

SignatureNormSquaredPlan

Static diagonal plan for <x reverse(x)>_0 over one layout.

input_grades property

Return input grades represented by the plan.

input_dim property

Return the compact input lane count.

build_signature_norm_squared_plan(spec, *, input_layout, device=None, dtype=torch.float32)

Build a static diagonal signed norm plan for input_layout.

permutation

Static permutation plans for Clifford lane maps.

PseudoscalarProductPlan

Static gather/sign plan for right multiplication by the pseudoscalar.

input_grades property

Return input grades.

output_grades property

Return output grades.

build_pseudoscalar_product_plan(spec, *, input_layout, output_layout=None, device=None, dtype=torch.float32)

Build a static right-pseudoscalar multiplication plan.

planner

Grade-aware planner from algebraic intent to static executors.

GradePlanner

Owns layout and product-plan lowering for one algebra instance.

The planner is deliberately not an nn.Module. It builds static executor modules keyed by signature, grades, dtype, and device.

layout(grades)

Return the compact layout for grades.

full_layout()

Return the canonical all-grades layout.

grade_indices(grades, *, device=None)

Return canonical basis indices for grades.

convert_values(values, *, source_layout, target_layout)

Convert compact values between layouts without full-lane materialization.

bivector_squared_signs(*, device=None, dtype=None)

Return (e_ab)^2 signs in canonical grade-2 layout order.

clear_cache()

Drop cached executor modules.

product_executor(*, op, left_grades, right_grades, output_grades, dtype, device, cache=True)

Return a cached static executor for a projected bilinear product.

product_request(left, right, *, op='gp', left_grades=None, right_grades=None, output_grades=None, left_layout=None, right_layout=None, output_layout=None, left_storage=None, right_storage=None, output_storage=LaneStorage.COMPACT)

Normalize product intent into a static request without executing tensors.

product_executor_for_request(request, *, cache=True)

Return an executor for an already normalized product request.

product_executor_for_layouts(*, op, left_layout, right_layout, output_layout, dtype, device, cache=True)

Return a cached executor when layout resolution is already complete.

product_tree(*, op, left_grades, right_grades, output_grades=None)

Return planner-only grade tree metadata for a product route.

unary_request(values, *, op, input_grades=None, output_grades=None, input_layout=None, output_layout=None, input_storage=None, output_storage=LaneStorage.COMPACT)

Normalize unary intent into a static request without executing tensors.

unary_executor(*, op, input_grades, output_grades=None, dtype, device, cache=True)

Return a cached static executor for a unary operation.

signature_norm_squared_executor(*, input_grades, dtype, device, cache=True)

Return a cached diagonal executor for signed signature norm squared.

signature_norm_squared_executor_for_layout(*, input_layout, dtype, device, cache=True)

Return a cached signed signature-norm executor for a resolved layout.

pseudoscalar_product_executor_for_layout(*, input_layout, output_layout=None, dtype, device, cache=True)

Return a cached right-pseudoscalar product permutation executor.

bivector_exp_executor_for_layouts(*, input_layout, output_layout, dtype, device, cache=True, spectral_max_planes=None, spectral_tol_abs=None, spectral_tol_rel=None, spectral_dominant_rel=None, spectral_transition_n=None, spectral_allow_degenerate=None, spectral_allow_truncated_degenerate=None)

Return a cached executor for the bivector exponential exp(B).

full_sandwich_action_executor_for_layout(*, layout, dtype, device, cache=True)

Return a cached full-layout sandwich action executor.

linear_action_plan(*, input_layout, output_layout=None)

Return a plan-only contract for a grade-preserving linear action.

versor_action_plan(*, grade, input_layout, output_layout=None, parameter_layout=None)

Return a plan-only contract for a grade-1 or grade-2 versor action.

paired_bivector_action_plan(*, input_layout, output_layout=None, parameter_layout=None)

Return a plan-only contract for independent bivector rotor pairs.

unary_executor_for_request(request, *, cache=True)

Return an executor for an already normalized unary request.

policy

Static planning policy for plan-cost diagnostics.

PlanningLimits dataclass

Static cost limits for planned grade execution.

max_lanes protects compact tensor width. max_pairs protects the gather/reduce interaction count generated by a bilinear product plan.

PlanCost dataclass

Static cost summary for a layout or planned operation.

max_lanes property

Return the largest lane width among the planned operands.

ProductExecutionPolicy dataclass

Flexible static cost model for product executor selection.

The model is deliberately equation-based. Benchmarks can validate and tune these weights, but product dispatch itself only depends on declared layouts, grade-tree metadata, dtype, and backend.

ProductExecutorCost dataclass

Static executor-selection score for one declared product request.

selected_score property

Return the score for the selected executor family.

planning_limits_for(algebra)

Return per-algebra planning limits, falling back to defaults.

product_execution_policy_for(algebra)

Return per-algebra product executor policy, falling back to defaults.

estimate_product_executor_cost(algebra, *, op, left_layout, right_layout, output_layout, dtype, device, policy=None)

Return static product executor scores and the selected family.

Sparse execution is always selected for non-full layouts because the full-table executor is defined only for canonical full-lane input and output. Full-layout requests compare full-table and sparse grade-tree equations.

validate_layout_cost(algebra, layout, *, role='layout')

Validate one compact layout against static lane limits.

validate_grades_cost(algebra, spec, grades, *, role='layout')

Validate a grade set before materializing its basis indices.

validate_product_grades_cost(algebra, spec, *, op, left_grades, right_grades, output_grades=None)

Validate product grade sets before materializing layouts.

product_plan_cost(request)

Return static cost summary for a product request.

unary_plan_cost(request)

Return static cost summary for a unary request.

validate_product_request(algebra, request)

Validate product request static cost.

validate_unary_request(algebra, request)

Validate unary request static cost.

validate_plan_cost(algebra, cost, *, limits=None)

Raise on excessive static cost and warn once near configured limits.

product

Static grade-path plans for Clifford product execution.

This module describes the lower-level AoT shape needed by high-dimensional product execution: input grades are declared or inferred at construction time and all basis interactions are expanded once. Hot tensor execution lives in clifra.core.execution.product.

GradeProductPlan

AoT basis interaction plan for one grade-restricted bilinear product.

p property

Return the positive metric dimension.

q property

Return the negative metric dimension.

r property

Return the null metric dimension.

left_grades property

Return the left operand grades.

right_grades property

Return the right operand grades.

output_grades property

Return the output grades.

n property

Return the total algebra dimension.

dim property

Return the full multivector lane count.

pair_count property

Return the number of nonzero basis interactions.

output_dim property

Return the compact output lane count.

is_empty property

Return whether the product has no nonzero basis interactions.

density property

Return realized interaction density relative to the grade tree estimate.

FullTableProductPlan

Full-layout Cayley-table product plan owned by the planner.

This executor family is available for requests where both operands and the output are the canonical all-grades layout.

p property

Return the positive metric dimension.

q property

Return the negative metric dimension.

r property

Return the null metric dimension.

n property

Return the total algebra dimension.

dim property

Return the full multivector lane count.

output_dim property

Return the output lane count.

left_grades property

Return all left operand grades.

right_grades property

Return all right operand grades.

output_grades property

Return all output grades.

build_grade_product_plan(p, q=0, r=0, *, left_grades, right_grades, output_grades=None, op='gp', device=None, dtype=torch.float32)

Build an exact static basis-pair plan for a grade-restricted operation.

build_grade_product_plan_from_request(request, *, device=None, dtype=None)

Build a plan from a normalized product request.

build_grade_product_plan_from_tree(tree, *, device=None, dtype=torch.float32)

Lower a planner tree into flat Torch gather/reduce buffers.

build_full_table_product_plan_from_request(request, *, device=None, dtype=None)

Build a full-table product plan from a normalized request.

build_full_table_product_plan(spec, *, op, device=None, dtype=torch.float32)

Build Cayley-style buffers for one full-layout product.

request_is_full_layout_product(request)

Return whether a request is the canonical full-layout product.

tree

Planner-only grade tree metadata.

The tree here is not a runtime backend. It groups declared grade routes before they are lowered into flat Torch executor buffers.

GradePathNode dataclass

One homogeneous left-grade/right-grade route in a product plan.

estimated_pairs property

Upper-bound number of basis pairs before metric zero pruning.

GradePlanTree dataclass

Planner-side grouping for a grade-restricted product.

path_count property

Number of selected homogeneous product routes.

estimated_pairs property

Upper-bound number of basis pairs across all paths.

estimated_chunks property

Number of planner chunks implied by chunk_pair_limit.

path_for_grades(left_grade, right_grade)

Return the selected path for a homogeneous grade pair.

build_grade_plan_tree(spec, *, left_grades, right_grades, output_grades=None, op='gp', chunk_pair_limit=None)

Build planner metadata for grade route grouping.

unary

Static unary requests and plans.

UnaryRequest dataclass

Fully resolved request for one unary planned operation.

input_layout property

Return the resolved input layout.

output_layout property

Return the resolved output layout.

input_uses_compact_storage property

Return whether the input tensor is already compact.

input_grades property

Return the grades accepted by the unary operation.

output_grades property

Return the grades emitted by the unary operation.

cache_key property

Return a stable key for executor caching.

GradeUnaryPlan

Static gather/sign plan for one unary operation.

dim property

Return the full algebra lane dimension.

output_dim property

Return the compact output lane count.

build_unary_request(spec, values, *, op, input_grades=None, output_grades=None, input_layout=None, output_layout=None, input_storage=None, output_storage=LaneStorage.COMPACT)

Resolve caller input into a static unary request.

build_unary_plan_from_request(request)

Lower a unary request into static gather/sign buffers.

normalize_unary_op(op)

Validate and normalize a unary operation name.

resolve_unary_output_layout(spec, *, op, input_layout, output_grades=None, output_layout=None)

Resolve output layout for a planned unary operation.

Execution

action

Compile-friendly executors for planned linear and versor actions.

GradedLinearActionExecutor

Bases: Module

Apply a vector-space map lifted to declared multivector grades.

forward(values, matrix)

Return output lanes in output_layout.

execute(values, matrix)

Validation-free grade-lift action for prepared tensors.

multi(values, matrices)

Apply multiple vector-space maps to declared grade lanes.

multi_execute(values, matrices)

Validation-free multi-action for prepared tensors.

coefficients(matrices)

Return lifted action coefficients for vector-space matrices.

coefficients_unchecked(matrices)

Validation-free lifted action coefficients for prepared matrices.

BivectorVectorGeneratorExecutor

Bases: Module

Build vector-space generators induced by grade-2 bivectors.

forward(bivectors)

Return vector-space generator matrices for bivectors.

execute(bivectors)

Validation-free vector generator construction for prepared bivectors.

VersorVectorMatrixExecutor

Bases: Module

Return vector-space matrices for compact grade-1 or grade-2 actions.

forward(weights)

Return one vector-space action matrix per input weight row.

execute(weights)

Validation-free vector-space action matrices for prepared weights.

FullSandwichActionExecutor

Bases: Module

Apply full-layout sandwich action matrices from static Cayley buffers.

from_layout(layout, *, device=None, dtype=torch.float32) classmethod

Build full-layout sandwich action buffers from algebra metadata.

action_matrices(left, right)

Return matrices M[..., k, j] such that output[..., k] = M @ x.

action_matrices_unchecked(left, right)

Validation-free action matrices for prepared full-layout factors.

per_channel(left, values, right)

Apply one sandwich action per channel in values.

per_channel_unchecked(left, values, right)

Validation-free per-channel action for prepared tensors.

batched(left, values, right)

Apply one full-layout sandwich action per leading batch item.

batched_unchecked(left, values, right)

Validation-free batched action for prepared tensors.

multi(left, values, right)

Apply every full-layout action to every input channel.

multi_unchecked(left, values, right)

Validation-free multi-action for prepared tensors.

routed(left, values, right, channel_to_pair)

Apply pair actions selected by channel index.

routed_unchecked(left, values, right, channel_to_pair)

Validation-free routed action for prepared tensors.

VersorActionExecutor

Bases: _VersorFactorPlanMixin, Module

Apply one planned grade-1 or grade-2 versor action.

forward(values, weights)

Return transformed values in output_layout lanes.

execute(values, weights)

Validation-free versor action for prepared tensors.

MultiVersorActionExecutor

Bases: _VersorFactorPlanMixin, Module

Apply a weighted superposition of planned grade-1 or grade-2 actions.

forward(values, weights, mix)

Return transformed values in output_layout lanes.

execute(values, weights, mix)

Validation-free multi-versor action for prepared tensors.

PairedBivectorActionExecutor

Bases: Module

Apply independent left/right bivector rotor pairs to channel values.

forward(values, left_weights, right_weights, channel_to_pair)

Return R_left x R_right_reverse for each routed input channel.

execute(values, left_weights, right_weights, channel_to_pair)

Validation-free paired-bivector action for prepared tensors.

apply_graded_linear_action(values, matrix, *, input_layout, output_layout)

Apply the outermorphism induced by a vector-space linear action.

apply_multi_graded_linear_action(values, matrices, *, input_layout, output_layout)

Apply multiple outermorphisms to declared grade lanes.

versor_vector_matrix(algebra, weights, *, grade, parameter_layout)

Return the vector-space matrix represented by grade-1 or grade-2 weights.

bivector_vector_generator(bivectors, *, bivector_layout)

Return the vector-space generator induced by bivectors.

reflection_vector_matrix(normals, *, vector_layout, eps)

Return the vector-space reflection matrix for normal vectors.

full_versor_factors(algebra, weights, *, grade, parameter_layout)

Return full-lane left/right factors for a grade-1 or grade-2 versor action.

full_paired_bivector_factors(algebra, left_weights, right_weights, *, parameter_layout)

Return full-lane (R_left, reverse(R_right)) for independent bivectors.

paired_bivector_factors(algebra, left_weights, right_weights, *, parameter_layout, rotor_layout)

Return compact (R_left, reverse(R_right)) for paired bivector actions.

attention

Attention score executor assembled from planned pairwise products.

GeometricAttentionScoreExecutor

Bases: Module

Compute geometric attention scores from a declared pairwise product plan.

forward(q_head, k_head)

Return attention scores for heads shaped [B, H, L, Hc, D].

exp

Bivector exponential executors for static bivector-exponential plans.

BivectorExpExecutor

Bases: Module

Compile-friendly bivector exponential exp(B) executor for grade-2 inputs.

Dimensions up to five use closed formulas. Eligible high-dimensional Euclidean plans use exact matrix exponentials up to the configured transition point, then spectral-local. MPS mixed-signature plans use a CPU matrix-exponential fallback because MPS matrix exponential is not available.

forward(values)

Return exp(values) in output_layout lanes.

handles

Public hot-path handles for preplanned executor calls.

ProductPlanHandle

Bases: Module

Active-lane product handle returned by algebra planning APIs.

forward(left, right)

Execute the product for tensors already stored in the declared layouts.

pairwise(left, right)

Execute pairwise item-axis product for compact-lane tensors.

UnaryPlanHandle

Bases: Module

Active-lane unary handle returned by algebra planning APIs.

forward(values)

Execute the unary operation for values already stored in input_layout.

full_input(values)

Execute the same plan for full-lane input values.

full_output(values)

Execute the same plan and materialize the output into full lanes.

FullSandwichActionHandle

Bases: Module

Full-layout sandwich action handle returned by algebra planning APIs.

forward(left, values, right)

Apply one sandwich action per channel in values.

action_matrices(left, right)

Return full-layout action matrices for the supplied left/right factors.

checked_action_matrices(left, right)

Return action matrices with eager validation.

per_channel(left, values, right)

Apply one sandwich action per channel in values.

checked_per_channel(left, values, right)

Apply one sandwich action per channel with eager validation.

batched(left, values, right)

Apply one sandwich action per leading batch item.

checked_batched(left, values, right)

Apply one sandwich action per leading batch item with eager validation.

multi(left, values, right)

Apply every sandwich action to every channel.

checked_multi(left, values, right)

Apply every sandwich action to every channel with eager validation.

routed(left, values, right, channel_to_pair)

Apply actions selected by channel index.

checked_routed(left, values, right, channel_to_pair)

Apply actions selected by channel index with eager validation.

VersorActionHandle

Bases: Module

Grade-1 or grade-2 versor action handle for compact-lane values.

forward(values, weights)

Apply one grade-1 or grade-2 versor per channel.

checked(values, weights)

Apply one grade-1 or grade-2 versor per channel with eager validation.

MultiVersorActionHandle

Bases: Module

Weighted multi-versor action handle for compact-lane values.

forward(values, weights, mix)

Apply a weighted superposition of grade-1 or grade-2 versor actions.

checked(values, weights, mix)

Apply a weighted superposition with eager validation.

PairedBivectorActionHandle

Bases: Module

Independent left/right bivector action handle for compact-lane values.

forward(values, left_weights, right_weights, channel_to_pair)

Apply independent left/right bivector rotor pairs routed by channel.

checked(values, left_weights, right_weights, channel_to_pair)

Apply routed paired-bivector actions with eager validation.

metric

Metric executors for static Clifford metric plans.

SignatureNormSquaredExecutor

Bases: Module

Compile-friendly diagonal executor for signed signature norm squared.

forward(values)

Return <values reverse(values)>_0 as [..., 1].

permutation

Permutation executors for static Clifford lane-map plans.

PseudoscalarProductExecutor

Bases: Module

Compile-friendly right-pseudoscalar product permutation executor.

forward(values)

Return right-pseudoscalar product values in output_layout lanes.

product

Product executors for static Clifford product plans.

GradeProductExecutor

Bases: Module

Compile-friendly grade-restricted product using a static interaction plan.

forward returns compact output lanes ordered by output_basis_indices. forward_full materializes into the canonical all-grades layout.

output_dim property

Return the compact output lane count.

pair_count property

Return the number of planned basis interactions.

forward(left, right)

Return compact grade-lane output for full-layout input tensors.

forward_compact(left, right)

Return compact output for inputs already stored in this plan's compact layouts.

forward_pairwise_compact(left, right)

Pairwise compact product for sequence-style bilinear scoring.

left is [..., left_items, left_layout.dim] and right is [..., right_items, right_layout.dim]. The result is [..., left_items, right_items, output_layout.dim].

forward_pairwise_compact_right_signed(left, right, right_signs)

Pairwise compact product with a diagonal sign applied to right lanes.

forward_full(left, right)

Return a full [..., 2**n] lane tensor.

FullTableProductExecutor

Bases: Module

Planner-owned full-layout Cayley-table product executor.

The public protocol matches :class:GradeProductExecutor where possible so hosts and layers can call executor handles without caring which family the planner selected.

output_dim property

Return the full output lane count.

pair_count property

Return the number of nonzero full-table interactions.

forward(left, right)

Return full-layout product lanes.

forward_compact(left, right)

Return full-layout product lanes for full-layout compact values.

forward_pairwise_compact(left, right)

Pairwise full-layout product for item-axis operands.

forward_full(left, right)

Return full-layout product lanes.

unary

Unary executors for static Clifford unary plans.

GradeUnaryExecutor

Bases: Module

Torch module for planned unary gather/sign execution.

output_dim property

Return the compact output lane count.

forward(values)

Return compact output lanes for full-layout input coefficients.

forward_compact(values)

Return compact output lanes for compact input coefficients.

forward_full(values)

Return full-layout output coefficients for full-layout input coefficients.

Functional Operations and Criteria

activation

Pure activation formulas for multivector tensors.

The final axis is the Clifford lane axis. Full-lane multivectors are [..., D] and compact layout values are [..., L]. Per-channel activations use [..., C, D] or [..., C, L] with parameter vectors shaped [C].

geometric_gelu(values, bias=None)

Scale multivectors by GELU(norm + bias) / norm while preserving direction.

Parameters:

Name Type Description Default
values Tensor

Multivectors with shape [..., D] or [..., L]. With a channel axis, use [..., C, D] or [..., C, L].

required
bias Tensor | None

Optional per-channel bias with shape [C].

None

Returns:

Type Description
Tensor

Activated multivectors with the same shape as values.

geometric_square(algebra, values, gate=None, *, layout=None)

Return values + gate * (values * values) using the algebra's geometric product.

Parameters:

Name Type Description Default
algebra

Algebra host.

required
values Tensor

Full-lane multivectors with shape [..., D] or compact layout values with shape [..., L] when layout is provided.

required
gate Tensor | None

Optional per-channel gate with shape [C].

None
layout

Compact layout describing the L final lanes.

None

Returns:

Type Description
Tensor

Values with the same shape as values.

grade_swish(values, *, grade_index, grade_weights, grade_biases, n_grades=None)

Apply per-grade sigmoid gates computed from per-grade coefficient norms.

Parameters:

Name Type Description Default
values Tensor

Multivectors with shape [..., D] or [..., L].

required
grade_index Tensor

Integer grade id for each lane, shaped [D] or [L].

required
grade_weights Tensor

Per-grade scale parameters with shape [G].

required
grade_biases Tensor

Per-grade bias parameters with shape [G].

required
n_grades int | None

Optional number of grades G. Defaults to grade_weights.shape[0].

None

Returns:

Type Description
Tensor

Gated multivectors with the same shape as values.

loss

Pure loss and regularization formulas.

Multivector losses use the final axis as the Clifford lane axis. Full-lane multivectors are [..., D] and compact layout values are [..., L]. Lane masks and metric vectors are shaped [D] or [L]. Non-Clifford task tensors document their ordinary axes locally.

geometric_mse(pred, target)

Return coefficient-wise mean squared error.

pred and target must have the same shape, usually [..., D] or [..., L] for multivectors.

subspace_penalty(values, penalty_mask)

Return mean squared energy in masked coefficient lanes.

Parameters:

Name Type Description Default
values Tensor

Multivectors with shape [..., D] or [..., L].

required
penalty_mask Tensor

Boolean lane mask with shape [D] or [L].

required

isometry_loss(pred, target, metric_diag)

Return MSE between metric norms of pred and target.

pred and target use shape [..., D] or [..., L]; metric_diag uses the corresponding [D] or [L] shape.

bivector_regularization(algebra, values, *, grade=2)

Penalize energy outside one target grade in full-lane [..., D] multivectors.

grade_energy_regularization(algebra, features, target)

Return MSE between actual and target positive grade-energy distributions.

features are full-lane multivectors with shape [..., D] and target is a grade distribution with shape [G].

chamfer_distance(pred, target)

Return symmetric squared Chamfer distance between point clouds.

Point clouds use ordinary coordinate axes: pred has shape [B, N, P] and target has shape [B, M, P].

conservative_force_loss(energy, force_pred, pos)

Return MSE between predicted forces and -grad(energy, pos).

force_pred and pos share an ordinary coordinate shape such as [B, N, P]; energy has matching leading batch axes.

physics_informed_loss(forecast, target, *, lat_weights=None, physics_weight=0.1)

Return forecast MSE plus a weighted global-conservation penalty.

forecast and target have the same ordinary task shape. When lat_weights is provided for a 4-D forecast, it has shape [Lat] and weights axis 1.

asymmetry_penalty(logits_fwd, logits_rev, *, margin=0.1)

Return penalty for correlation above margin between matching logit tensors.

involution_consistency_loss(features, features_neg, algebra)

Return MSE between full-lane [..., D] features and their grade-involuted counterpart.

orthogonality

Pure orthogonality formulas for multivector grade lanes.

The final axis is the Clifford lane axis. Full-lane values are [..., D] and compact layout values are [..., L]. Grade masks are [G, D] or [G, L]; boolean lane masks are [D] or [L].

grade_masks(n_grades, dim, *, device=None)

Return [G, D] or [G, L] boolean masks keyed by basis-blade grade.

target_mask_from_grades(masks, target_grades)

Return a [D] or [L] boolean lane mask for the requested grades.

parasitic_energy(values, parasitic_mask)

Return mean squared energy in non-target lanes of [..., D] or [..., L] values.

project_to_target_grades(values, target_mask)

Return [..., D] or [..., L] values with non-target lanes zeroed.

grade_energies(values, masks)

Return mean squared energy per grade for [..., D] or [..., L] values.

parasitic_ratio(values, masks, target_grades)

Return the fraction of total grade energy outside target_grades.

cross_grade_coupling(values, masks)

Return the [G, G] correlation matrix of grade energies across batch axis 0.

diagnostics(values, masks, *, target_grades, tolerance)

Return grade-energy, parasitic-ratio, and coupling diagnostics for multivectors.

products

Stateless geometric algebra product helpers.

Functional helpers use the final axis as the Clifford lane axis. Full-lane multivectors are [..., D], where D = 2 ** algebra.n. Active layout values are [..., L], where L is the compact lane count for the declared layout. Leading axes ... are ordinary PyTorch batch, item, or channel axes.

These wrappers keep model code concise while preserving the algebra host as the single execution authority. Full-lane, compact-lane, and pairwise planned executors all flow through the same public calls.

canonical_product_op(op)

Return a supported public product operation name.

product(algebra, left, right, *, op='gp', **kwargs)

Apply a binary geometric algebra product.

Parameters:

Name Type Description Default
algebra

Algebra host.

required
left Tensor

Left operand with full-lane shape [..., D] or active declared shape [..., L_left].

required
right Tensor

Right operand with leading axes broadcast-compatible with left and lane shape [..., D] or [..., L_right].

required
op str

"gp", "wedge", "symmetric_product", "commutator_product", "anti_commutator_product", "left_contraction", or "right_contraction".

'gp'
**kwargs Any

Optional grade/layout declarations accepted by algebra.projected_product.

{}

Returns:

Type Description
Tensor

Product values with full-lane shape [..., D] or declared compact shape

Tensor

[..., L_out].

projected_product(algebra, left, right, *, op='gp', **kwargs)

Apply a declared grade-restricted product through the planner.

Operands use compact lane shapes [..., L_left] and [..., L_right] when compact layouts are declared; the output uses [..., L_out].

geometric_product(algebra, left, right, **kwargs)

Apply the geometric product to full [..., D] or declared compact lanes.

wedge(algebra, left, right, **kwargs)

Apply the exterior product to full [..., D] or declared compact lanes.

symmetric_product(algebra, left, right, **kwargs)

Apply the normalized anti-commutator (A B + B A) / 2.

commutator_product(algebra, left, right, **kwargs)

Apply the commutator A B - B A.

anti_commutator_product(algebra, left, right, **kwargs)

Apply the unnormalized anti-commutator A B + B A.

left_contraction(algebra, left, right, **kwargs)

Apply left contraction to full [..., D] or declared compact lanes.

right_contraction(algebra, left, right, **kwargs)

Apply right contraction to full [..., D] or declared compact lanes.

grade_projection(algebra, values, grade, **kwargs)

Project multivectors with shape [..., D] or [..., L] to one grade.

reverse(algebra, values, **kwargs)

Apply reversion to values with shape [..., D] or [..., L].

grade_involution(algebra, values, **kwargs)

Apply grade involution to values with shape [..., D] or [..., L].

clifford_conjugation(algebra, values, **kwargs)

Apply Clifford conjugation to values with shape [..., D] or [..., L].

pseudoscalar_product(algebra, values, **kwargs)

Apply right multiplication by the unit pseudoscalar.

signature_norm_squared(algebra, values, **kwargs)

Return the signed Clifford signature norm squared.

bivector_exp(algebra, values, **kwargs)

Exponentiate a declared bivector.

embed_vector(algebra, vectors)

Embed coordinate vectors with shape [..., algebra.n] into full-lane multivectors.

blade_inverse(algebra, blade, **kwargs)

Return the regularized inverse of a declared blade.

blade_project(algebra, values, blade, **kwargs)

Project values onto a declared blade subspace.

blade_reject(algebra, values, blade, **kwargs)

Reject values from a declared blade subspace.

reflect(algebra, values, normal, **kwargs)

Reflect values through a declared vector normal.

versor_product(algebra, versor, values, **kwargs)

Apply grade_involution(versor) * values * inverse(versor).

planned_linear_action(algebra, values, matrix, **kwargs)

Apply a declared vector-space linear action.

sandwich_action_matrices(algebra, left, right=None, **kwargs)

Return full-layout sandwich action matrices.

sandwich_product(algebra, left, values, right=None, **kwargs)

Apply one full-layout sandwich action per leading batch item.

per_channel_sandwich(algebra, left, values, right=None, **kwargs)

Apply one full-layout sandwich action per channel.

multi_rotor_sandwich(algebra, left, values, right=None, **kwargs)

Apply every full-layout sandwich action to every input channel.

versor_action(algebra, values, weights, **kwargs)

Execute a planned grade-1 or grade-2 versor action.

multi_versor_action(algebra, values, weights, mix, **kwargs)

Execute a planned weighted grade-1 or grade-2 versor action.

paired_bivector_action(algebra, values, left_weights, right_weights, channel_to_pair, **kwargs)

Execute a planned independent left/right bivector rotor action.

grade_norms(algebra, values, **kwargs)

Return per-grade coefficient norms for declared-layout values.

loss

Loss modules built from pure functional formulas.

GeometricMSELoss

Bases: CliffordModule

Geometric MSE: standard MSE on multivector coefficients.

__init__(algebra)

Initialize the geometric MSE loss.

forward(pred, target)

Return coefficient MSE.

SubspaceLoss

Bases: CliffordModule

Penalty for energy in forbidden basis lanes.

__init__(algebra, target_indices=None, exclude_indices=None)

Initialize grade constraint penalties.

forward(x)

Return forbidden-lane energy.

IsometryLoss

Bases: CliffordModule

Metric norm preservation loss.

__init__(algebra)

Initialize isometry loss with metric diagonal.

forward(pred, target)

Compare metric norms.

BivectorRegularization

Bases: CliffordModule

Regularize multivectors toward one target grade.

__init__(algebra, grade=2)

Initialize grade regularization.

forward(x)

Penalize energy outside grade.

GradeEnergyRegularization

Bases: CliffordModule

Regularize positive lane grade energy toward a target distribution.

__init__(algebra, target_spectrum=None)

Initialize grade regularization.

forward(features)

Compute grade-energy distribution regularization.

ChamferDistance

Bases: Module

Symmetric Chamfer distance between two point clouds.

forward(pred, target)

Compute Chamfer distance.

ConservativeLoss

Bases: Module

Enforce F = -grad(E) conservative force consistency.

forward(energy, force_pred, pos)

Compute conservative force loss.

PhysicsInformedLoss

Bases: Module

MSE plus a simple conservation penalty.

forward(forecast, target, lat_weights=None)

Compute physics-informed loss.

AsymmetryLoss

Bases: Module

Penalize symmetric behavior in asymmetric predictions.

__init__(margin=0.1)

Initialize asymmetry loss.

forward(logits_fwd, logits_rev)

Compute asymmetry penalty.

InvolutionConsistencyLoss

Bases: Module

Enforce consistency between grade involution and negation.

forward(features, features_neg, algebra)

Compute involution consistency loss.

orthogonality

Orthogonality criteria for grade-constrained training.

OrthogonalitySettings dataclass

Configuration for target-grade confinement.

StrictOrthogonality

Bases: CliffordModule

Enforce grade confinement by loss penalty or hard projection.

__init__(algebra, settings=None)

Initialize target-grade confinement.

parasitic_energy(x)

Return mean squared energy in non-target grade components.

project(x)

Return x with non-target grade lanes zeroed.

forward(x)

Return either a non-target-grade penalty or projected values.

anneal_weight(epoch, warmup_epochs, total_epochs)

Return the linearly warmed confinement weight.

diagnostics(x)

Return grade-energy and cross-grade coupling diagnostics.

format_diagnostics(x)

Return a compact text report for grade-confinement diagnostics.

Layers

conformal

Layout-first conformal embedding example.

ConformalEmbedding

Bases: CliffordModule

Example conformal embedding over a declared compact-lane layout.

Maps Euclidean R^d vectors to grade-1 conformal points in Cl(d+1, 1) and back. The output lane width is layout.dim rather than always algebra.dim.

The standard conformal embedding is

P(x) = x + 0.5 * ||x||^2 * e_inf + e_o

where e_inf = e_- + e_+ (point at infinity) and e_o = 0.5*(e_- - e_+) (origin). Basis vectors e_inf and e_o are precomputed as buffers.

Requires an algebra with signature Cl(d+1, 1, ...).

Attributes:

Name Type Description
euclidean_dim int

Physical dimension d.

__init__(algebra, euclidean_dim, *, grades=None, layout=None)

Sets up the conformal embedding.

Parameters:

Name Type Description Default
algebra AlgebraLike

Clifford algebra instance with signature Cl(d+1, 1, ...).

required
euclidean_dim int

Physical dimension d.

required
grades

Optional compact output/input grades.

None
layout GradeLayout

Optional compact output/input layout.

None

embed(x)

Embed Euclidean points into the conformal null cone.

Parameters:

Name Type Description Default
x Tensor

Euclidean points [..., d].

required

Returns:

Type Description
Tensor

Conformal multivectors [..., layout.dim].

extract(P)

Project conformal points back to Euclidean space.

Normalizes so that P . e_inf = -1, then extracts vector part.

Parameters:

Name Type Description Default
P Tensor

Conformal multivectors [..., layout.dim].

required

Returns:

Type Description
Tensor

Euclidean coordinates [..., d].

forward(x)

Default forward: embed Euclidean points.

Parameters:

Name Type Description Default
x Tensor

Euclidean points [..., d].

required

Returns:

Type Description
Tensor

Conformal multivectors [..., layout.dim].

projective

Layout-first projective embedding example.

ProjectiveEmbedding

Bases: CliffordModule

Example projective embedding over a declared compact-lane layout.

Maps Euclidean R^d points to grade-1 elements of Cl(d, 0, 1) and back. The output lane width is layout.dim rather than always algebra.dim.

In PGA, the degenerate basis vector e_0 (where e_0^2 = 0) represents the origin. A Euclidean point x is embedded as the 1-vector:

P(x) = x_1 e_1 + x_2 e_2 + ... + x_d e_d + e_0

The e_0 component acts as a homogeneous coordinate. Directions (ideal points) have e_0 = 0, while finite points have e_0 != 0.

Extraction normalizes so that the e_0 coefficient equals 1, then reads the Euclidean basis coefficients.

Requires an algebra with signature Cl(d, 0, >=1).

Attributes:

Name Type Description
euclidean_dim int

Physical dimension d.

__init__(algebra, euclidean_dim, *, grades=None, layout=None)

Sets up the projective embedding.

Parameters:

Name Type Description Default
algebra AlgebraLike

Clifford algebra instance with signature Cl(d, 0, >=1).

required
euclidean_dim int

Physical dimension d.

required
grades

Optional compact output/input grades.

None
layout GradeLayout

Optional compact output/input layout.

None

embed(x)

Embed Euclidean points into PGA as grade-1 elements.

Parameters:

Name Type Description Default
x Tensor

Euclidean points [..., d].

required

Returns:

Type Description
Tensor

PGA multivectors [..., layout.dim].

embed_direction(v)

Embed Euclidean directions (ideal points) into PGA.

Directions have e_0 = 0, representing points at infinity.

Parameters:

Name Type Description Default
v Tensor

Direction vectors [..., d].

required

Returns:

Type Description
Tensor

PGA multivectors [..., layout.dim] with zero e_0 component.

extract(P)

Project PGA points back to Euclidean space.

Normalizes by the e_0 coefficient, then extracts the Euclidean basis components.

Parameters:

Name Type Description Default
P Tensor

PGA multivectors [..., layout.dim].

required

Returns:

Type Description
Tensor

Euclidean coordinates [..., d].

forward(x)

Default forward: embed Euclidean points.

Parameters:

Name Type Description Default
x Tensor

Euclidean points [..., d].

required

Returns:

Type Description
Tensor

PGA multivectors [..., layout.dim].

attention

Attention blocks driven by planned Clifford products.

GeometricProductAttention

Bases: CliffordModule

Multi-head attention using geometric product scoring.

Standard attention uses a scalar query-key score.

This layer forms a geometric product per head-channel and combines its grade-0 component with the coefficient norm of its grade-2 component.

The grade-0 (scalar) part measures alignment (like dot product). The grade-2 contribution records oriented-plane content in the product.

Attributes:

Name Type Description
num_heads int

Number of attention heads.

head_channels int

Channels per head.

causal bool

If True, apply autoregressive causal mask.

bivector_weight float

Weight of the bivector score component.

__init__(algebra, channels, num_heads, causal=True, bivector_weight=0.5, dropout=0.0, grades=None, layout=None)

Sets up geometric product attention.

Parameters:

Name Type Description Default
algebra AlgebraLike

Clifford algebra instance.

required
channels int

Total number of multivector channels.

required
num_heads int

Number of attention heads.

required
causal bool

Apply causal mask for autoregressive generation.

True
bivector_weight float

Weight on the bivector score component.

0.5
dropout float

Dropout rate on attention weights.

0.0
grades

Optional compact input/output grades.

None
layout GradeLayout

Optional compact input/output layout.

None

reset_parameters()

Initialize the fused QKV channel projections.

forward(x, key_padding_mask=None)

Computes geometric product attention.

Parameters:

Name Type Description Default
x Tensor

Input multivectors [B, L, C, D].

required
key_padding_mask Tensor

Optional [B, L] bool mask where True = padded (ignored).

None

Returns:

Type Description
Tensor

Output multivectors [B, L, C, D].

EntropyGatedAttention

Bases: CliffordModule

Geometric attention with an example bivector-entropy gate.

This is intentionally implemented as a layout-first block: inputs and outputs use the compact lanes declared by layout or grades.

__init__(algebra, channels, num_heads, eta=1.0, H_base=0.5, *, grades=None, layout=None)

Initializes entropy-gated attention.

forward(x, key_padding_mask=None, return_gating=False)

Applies entropy-gated geometric attention to [B, L, C, D] inputs.

activation

Geometric activation layers.

GeometricGELU

Bases: CliffordModule

Magnitude-gated GELU that preserves multivector direction.

__init__(algebra, channels=1, *, grades=None, layout=None)

Initialize Geometric GELU.

forward(x)

Apply geometric GELU activation.

GeometricSquare

Bases: CliffordModule

Gated geometric self-product: x + gate * (x * x).

__init__(algebra, channels=1, *, grades=None, layout=None)

Initialize gated geometric self-product.

forward(x)

Apply the gated geometric square.

GradeSwish

Bases: CliffordModule

Per-grade sigmoid gate based on grade norms.

__init__(algebra, channels=1, *, grades=None, layout=None)

Initialize grade-wise Swish activation.

forward(x)

Apply per-grade gating.

linear

Clifford-valued channel-mixing layers.

CliffordLinear

Bases: CliffordModule

Fully connected layer with optional rotor-based backend.

The traditional backend uses a scalar channel-mixing matrix and a multivector bias. The rotor backend delegates to :class:RotorGadget, whose total parameter count depends on the rotor-pair count, aggregation mode, and bias.

Attributes:

Name Type Description
in_channels int

Input features.

out_channels int

Output features.

backend str

'traditional' or 'rotor'

weight Parameter | None

Weights [Out, In] (traditional backend only).

bias Parameter | None

Bias multivector [Out, Dim] (traditional backend only).

gadget Module | None

Rotor transformation (rotor backend only).

__init__(algebra, in_channels, out_channels, backend='traditional', num_rotor_pairs=4, aggregation='mean', shuffle='none', grades=None, layout=None)

Initialize Clifford Linear.

Parameters:

Name Type Description Default
algebra AlgebraLike

Planner-capable algebra host.

required
in_channels int

Input size.

required
out_channels int

Output size.

required
backend str

'traditional' for standard linear layer, 'rotor' for rotor-based transformation

'traditional'
num_rotor_pairs int

Number of rotor pairs (rotor backend only)

4
aggregation str

Aggregation method (rotor backend only)

'mean'
shuffle str

Input channel shuffle strategy (rotor backend only): - 'none': No shuffle (default) - 'fixed': Fixed random permutation - 'random': Random permutation each forward pass

'none'

reset_parameters()

Initialize weights with Xavier uniform and zero bias.

forward(x)

Apply channel-mixing linear transformation.

Parameters:

Name Type Description Default
x Tensor

Input [Batch, In, Dim].

required

Returns:

Type Description
Tensor

torch.Tensor: Output [Batch, Out, Dim].

extra_repr()

String representation for debugging.

Returns:

Name Type Description
str str

Layer parameters description

multi_versor

Multi-versor superposition layers for grade-1 and grade-2 parameters.

Implements versor-based transformations using weighted sums of sandwich products.

MultiVersorLayer

Bases: CliffordModule

Weighted superposition of planned reflection or rotor actions.

With grade=2 (default), each parameter is exponentiated to a rotor. With grade=1, each parameter defines a reflection. These are the currently supported parameter grades.

Bivector exponentials are planned by the core exp executor family: closed formulas, matrix exp, or spectral-local execution for eligible high-dimensional signatures.

Attributes:

Name Type Description
channels int

Input features.

num_versors int

Number of overlapping versors.

grade int

Grade of the learnable parameters. Default 2 (rotors).

grade_weights Parameter

Parameter coefficients with shape [num_versors, num_grade_elements].

weights Parameter

Mixing weights [channels, num_versors].

__init__(algebra, channels, num_versors=8, grade=2, *, input_grades=None, output_grades=None, input_layout=None, output_layout=None)

Initialize a multi-versor layer.

Parameters:

Name Type Description Default
algebra AlgebraLike

Planner-capable algebra host.

required
channels int

Input features.

required
num_versors int

Number of parallel versor heads.

8
grade int

Grade of the learnable parameter. The supported values are 1 for vector reflections and 2 for bivector rotor actions. Defaults to 2.

2

reset_parameters()

Initialize with small transforms and uniform mixing weights.

forward(x, return_invariants=False)

Apply weighted multi-versor superposition.

Parameters:

Name Type Description Default
x Tensor

Input [Batch, Channels, Dim].

required
return_invariants bool

If True, returns per-grade norms instead of output.

False

Returns:

Type Description
Tensor

torch.Tensor: Transformed output [Batch, Channels, Dim].

sparsity_loss()

Compute L1 sparsity loss for versor weights and mixing weights.

normalization

Normalization primitives for Clifford-valued tensors.

CliffordLayerNorm

Bases: CliffordModule

Normalize coefficient magnitude and optionally encode it in grade 0.

The input is divided by its Euclidean coefficient norm and multiplied by a learned per-channel scale. A scalar bias is then added. When recover is enabled, log1p(norm) is also added to the scalar lane through a learned gate. The scalar additions can change the direction of the final multivector; they encode magnitude information rather than reconstructing the original input scale.

Attributes:

Name Type Description
weight Parameter

Per-channel direction scale [C].

bias Parameter

Per-channel scalar bias [C].

norm_scale Parameter

Per-channel gate for log-magnitude injection into grade-0. Initialized to zero so the layer starts identical to the old (scale-discarding) behaviour.

__init__(algebra, channels, eps=1e-06, recover=True, *, grades=None, layout=None)

Sets up normalization.

Parameters:

Name Type Description Default
algebra AlgebraLike

Planner-capable algebra host.

required
channels int

Features.

required
eps float

Stability term.

1e-06
recover bool

Whether to inject original scale into the scalar part.

True

forward(x)

Normalize coefficient magnitude and apply scalar-lane terms.

Parameters:

Name Type Description Default
x Tensor

Input [Batch, Channels, Dim].

required

Returns:

Type Description
Tensor

torch.Tensor: Normalized input.

product

Module wrappers around declared geometric algebra products.

ProductLayer

Bases: CliffordModule

Apply a geometric algebra product inside nn.Module graphs.

Grade and layout declarations define the tensor lane contract. If a caller declares any input or output layout, the layer returns the planned output layout lanes. If no layout is declared, it uses the algebra's direct full multivector product.

__init__(algebra, *, op='gp', left_grades=None, right_grades=None, output_grades=None, left_layout=None, right_layout=None, output_layout=None, pairwise=False)

Initialize a product layer.

Parameters:

Name Type Description Default
algebra

Algebra host.

required
op str

Product route: "gp", "wedge", "symmetric_product", "commutator_product", "anti_commutator_product", "left_contraction", or "right_contraction".

'gp'
left_grades Optional[Iterable[int]]

Declared input grades for the left operand.

None
right_grades Optional[Iterable[int]]

Declared input grades for the right operand.

None
output_grades Optional[Iterable[int]]

Optional output grade projection.

None
left_layout GradeLayout

Optional explicit left operand layout.

None
right_layout GradeLayout

Optional explicit right operand layout.

None
output_layout GradeLayout

Optional explicit output layout.

None
pairwise bool

Treat the penultimate dimension of each declared-layout operand as independent left/right item axes.

False

forward(left, right)

Apply the configured product to left and right.

extra_repr()

Return constructor fields shown by nn.Module repr.

GeometricProductLayer

Bases: ProductLayer

Layer form of the geometric product.

WedgeLayer

Bases: ProductLayer

Layer form of the exterior product.

SymmetricProductLayer

Bases: ProductLayer

Layer form of the normalized anti-commutator (A B + B A) / 2.

CommutatorProductLayer

Bases: ProductLayer

Layer form of the commutator A B - B A.

AntiCommutatorProductLayer

Bases: ProductLayer

Layer form of the unnormalized anti-commutator A B + B A.

LeftContractionLayer

Bases: ProductLayer

Layer form of the left contraction.

RightContractionLayer

Bases: ProductLayer

Layer form of the right contraction.

projection

Projection and neutralization primitives for multivector channels.

BladeSelector

Bases: CliffordModule

Apply a learned gate to each coefficient lane.

Gates are learned independently for every channel and lane. Lanes from the same grade do not share a gate.

Attributes:

Name Type Description
weights Parameter

Gate logits [Channels, Dim].

__init__(algebra, channels, *, grades=None, layout=None)

Sets up the selector.

Parameters:

Name Type Description Default
algebra AlgebraLike

Planner-capable algebra host.

required
channels int

Input features.

required

reset_parameters()

Initialize logits so the selector starts as pass-through.

forward(x)

Gate coefficient lanes.

The gate is 2 * sigmoid(weights) so zero logits preserve the input.

Parameters:

Name Type Description Default
x Tensor

Input [Batch, Channels, Dim].

required

Returns:

Type Description
Tensor

torch.Tensor: Filtered input.

GeometricNeutralizer

Bases: CliffordModule

Residualize grade-0 coefficients against grade-2 coefficients.

Fits a regularized linear projection from centered grade-2 coefficients to grade-0 coefficients and subtracts that projection from grade 0.

Uses Exponential Moving Average (EMA) to maintain stable covariance statistics across batches, ensuring batch-independent behavior during inference.

Attributes:

Name Type Description
algebra AlgebraLike

Planner-capable algebra host.

momentum float

EMA momentum.

__init__(algebra, channels, momentum=0.1, *, grades=None, layout=None)

Initialize the neutralizer.

Parameters:

Name Type Description Default
algebra AlgebraLike

Planner-capable algebra host.

required
channels int

Number of multivector channels.

required
momentum float

EMA momentum for covariance tracking.

0.1

forward(x)

Residualize grade 0 using batch or EMA covariance statistics.

Parameters:

Name Type Description Default
x Tensor

Input [Batch, Channels, Dim].

required

Returns:

Type Description
Tensor

torch.Tensor: Neutralized multivector.

reflection

Reflection layers for Pin-style geometric actions.

ReflectionLayer

Bases: CliffordModule

Learnable reflection layer via unit vectors.

Each channel learns a unit vector n_c and applies the reflection x'_c = -n_c x_c n_c^{-1}. This is the fundamental odd versor transformation - rotors (even versors) are compositions of two reflections.

The learned vectors are projected to unit norm before each reflection. For Euclidean signature, the projection is simple L2 normalization. For mixed signature, the projection normalizes by |_0|.

Attributes:

Name Type Description
channels int

Number of reflection vectors.

vector_weights Parameter

Learnable grade-1 coefficients [C, n].

__init__(algebra, channels, *, input_grades=None, output_grades=None, input_layout=None, output_layout=None)

Initialize the reflection layer.

Parameters:

Name Type Description Default
algebra AlgebraLike

Planner-capable algebra host.

required
channels int

Number of features.

required

reset_parameters()

Initialize with random unit-ish vectors.

forward(x)

Apply per-channel reflections: x'_c = -n_c x_c n_c^{-1}.

Parameters:

Name Type Description Default
x Tensor

Input [Batch, Channels, Dim].

required

Returns:

Type Description
Tensor

torch.Tensor: Reflected input [Batch, Channels, Dim].

sparsity_loss()

Compute L1 sparsity regularization on vector weights.

rotor_gadget

Rotor-based channel transformation layer.

Background reference

Pence, T., Yamada, D., & Singh, V. (2025). "Composing Linear Layers from Irreducibles." arXiv:2507.11688v1, Section 4.2, Equation 6

RotorGadget

Bases: CliffordModule

Rotor-based linear transformation (Generalized Rotor Gadget).

Applies paired rotor-sandwich transformations and then aggregates their channel outputs. Its bivector-coordinate term has 2 * num_rotor_pairs * n * (n - 1) / 2 parameters. Learned aggregation and optional bias add parameters when enabled.

Architecture

Partition input channels into blocks, apply rotor sandwiches to each pair, then aggregate the results to output channels.

Attributes:

Name Type Description
algebra AlgebraLike

Planner-capable algebra host

in_channels

Number of input channels

out_channels

Number of output channels

num_rotor_pairs

Number of rotor pairs to use

aggregation

Aggregation method ('mean', 'sum', or 'learned')

__init__(algebra, in_channels, out_channels, num_rotor_pairs=4, aggregation='mean', shuffle='none', bias=False, *, grades=None, layout=None, input_grades=None, output_grades=None, input_layout=None, output_layout=None)

Initialize rotor gadget layer.

Parameters:

Name Type Description Default
algebra AlgebraLike

Planner-capable algebra host

required
in_channels int

Number of input channels

required
out_channels int

Number of output channels

required
num_rotor_pairs int

Number of rotor pairs (higher = more expressive)

4
aggregation Literal['mean', 'sum', 'learned']

How to pool rotor outputs ('mean', 'sum', 'learned')

'mean'
shuffle Literal['none', 'fixed', 'random']

Input channel shuffle strategy: - 'none': No shuffle, sequential block assignment (default) - 'fixed': Random permutation at initialization (fixed during training) - 'random': Random permutation each forward pass (regularization)

'none'
bias bool

Whether to include bias term (applied after transformation)

False

reset_parameters()

Initialize paired bivector parameters near the identity action.

forward(x)

Apply rotor-based transformation.

Uses batched geometric products - all rotor pairs are applied in parallel via a single pair of GP calls.

Parameters:

Name Type Description Default
x Tensor

Input tensor of shape [Batch, In_Channels, Dim]

required

Returns:

Type Description
Tensor

Output tensor of shape [Batch, Out_Channels, Dim]

extra_repr()

String representation for debugging.

versor

Versor layers that act through learned grade-1 or grade-2 parameters.

VersorLayer

Bases: CliffordModule

Learnable versor layer for reflection or rotor actions.

grade=2 (default) learns R = exp(-B/2) and applies the rotor action x' = R x reverse(R). grade=1 learns a vector and applies the corresponding reflection action. These are the currently supported parameter grades.

Preserves origin. For grade=2, also preserves lengths and angles (isometry).

Bivector exponentials are planned by the core exp executor family: closed formulas for low dimensions, matrix exp by default in higher dimensions, and spectral-local execution for eligible high-dimensional signatures.

Attributes:

Name Type Description
channels int

Number of versors.

grade int

Grade of the learnable parameter. Default 2 (bivector → rotor).

grade_weights Parameter

Learnable coefficients with shape [channels, num_grade_elements].

__init__(algebra, channels, grade=2, *, input_grades=None, output_grades=None, input_layout=None, output_layout=None)

Initialize the versor layer.

Parameters:

Name Type Description Default
algebra AlgebraLike

Planner-capable algebra host.

required
channels int

Number of features.

required
grade int

Grade of the learnable parameter. The supported values are 1 for vector reflections and 2 for bivector rotor actions. Defaults to 2.

2

reset_parameters()

Initialize with near-identity transform (small weights).

forward(x)

Apply the planned reflection or rotor action.

Parameters:

Name Type Description Default
x Tensor

Input [Batch, Channels, Dim].

required

Returns:

Type Description
Tensor

torch.Tensor: Transformed input [Batch, Channels, Dim].

prune_weights(threshold=0.0001)

Zero out grade weights below threshold.

Parameters:

Name Type Description Default
threshold float

Cutoff magnitude.

0.0001

Returns:

Name Type Description
int int

Number of pruned parameters.

sparsity_loss()

Compute L1 sparsity regularization on grade weights.

Optimization

riemannian

Coordinate optimizers and tangent maps for geometric parameters.

The from_model() constructors recognize three parameter tags via p._manifold: - 'spin': bivector coordinates, optionally clipped by coefficient norm - 'sphere': vectors normalized after each update - 'euclidean' (or untagged): standard unconstrained parameters

The tags become ordinary PyTorch parameter groups, keeping optimizer dynamics separate from the layer that realizes each geometric action. Parameters without a tag are treated as Euclidean. The tangent projection and exponential map at the bottom of this module provide building blocks for optimizers that store rotors directly instead of bivector coordinates.

Background references
  • Absil et al. "Optimization Algorithms on Matrix Manifolds" (2008)
  • Boumal "An Introduction to Optimization on Smooth Manifolds" (2023)

ExponentialSGD

Bases: Optimizer

SGD followed by tag-specific post-update handling.

The optimizer applies an ordinary SGD update to each stored parameter. According to each parameter group's manifold value, it then clips spin parameters by coefficient norm, normalizes sphere parameters, and leaves euclidean parameters unchanged. For layers parameterized by bivectors, the layer—not this optimizer—uses the updated coordinates to construct a rotor during its forward pass.

Parameters:

Name Type Description Default
params Iterable

Iterable of parameters to optimize

required
lr float

Learning rate

0.01
momentum float

Momentum factor (default: 0)

0
algebra

Algebra context used for signature-aware sphere normalization.

None
max_bivector_norm Optional[float]

Maximum Euclidean coefficient norm for spin coordinate groups. None disables this numerical guard. Defaults to 10.0.

10.0
Example

algebra = AlgebraContext(p=3, q=0, device='cpu') model = VersorLayer(algebra, channels=4) optimizer = ExponentialSGD.from_model( ... model, lr=0.01, algebra=algebra ... )

from_model(model, lr=0.01, momentum=0, algebra=None, max_bivector_norm=10.0) classmethod

Create optimizer with auto-detected manifold parameter groups.

Inspects p._manifold tags on each parameter and creates separate groups for spin, sphere, and euclidean parameters so that each group receives its configured post-update rule in :meth:step.

Parameters:

Name Type Description Default
model Module

The model to optimize.

required
lr float

Learning rate.

0.01
momentum float

Momentum factor.

0
algebra

Layout-first algebra context (required).

None
max_bivector_norm Optional[float]

Coefficient-norm guard for spin coordinates.

10.0

Returns:

Type Description

ExponentialSGD instance with per-manifold parameter groups.

step(closure=None)

Perform one SGD step and dispatch post-update handling by tag.

Parameters:

Name Type Description Default
closure Callable

A closure that reevaluates the model and returns the loss.

None

Returns:

Type Description
Optional[Tensor]

Optional[torch.Tensor]: The loss if closure is provided, else None.

RiemannianAdam

Bases: Optimizer

Adam followed by tag-specific post-update handling.

Adam moments and updates are computed in the stored parameter coordinates. According to each parameter group's manifold value, the optimizer then clips spin parameters by coefficient norm, normalizes sphere parameters, and leaves euclidean parameters unchanged. A layer may subsequently exponentiate updated bivector coordinates in its forward pass; that exponential is not part of :meth:step.

Parameters:

Name Type Description Default
params Iterable

Iterable of parameters to optimize

required
lr float

Learning rate (default: 1e-3)

0.001
betas tuple

Coefficients for computing running averages (default: (0.9, 0.999))

(0.9, 0.999)
eps float

Term added for numerical stability (default: 1e-8)

1e-08
algebra

Algebra context used for signature-aware sphere normalization.

None
max_bivector_norm Optional[float]

Maximum Euclidean coefficient norm for spin coordinate groups. None disables this numerical guard. Defaults to 10.0.

10.0

from_model(model, lr=0.001, betas=(0.9, 0.999), eps=1e-08, algebra=None, max_bivector_norm=10.0) classmethod

Create optimizer with auto-detected manifold parameter groups.

Inspects p._manifold tags on each parameter and creates separate groups for spin, sphere, and euclidean parameters so that each group receives its configured post-update rule in :meth:step.

Parameters:

Name Type Description Default
model Module

The model to optimize.

required
lr float

Learning rate.

0.001
betas tuple

Coefficients for running averages.

(0.9, 0.999)
eps float

Numerical stability term.

1e-08
algebra

Layout-first algebra context (required).

None
max_bivector_norm Optional[float]

Coefficient-norm guard for spin coordinates.

10.0

Returns:

Type Description

RiemannianAdam instance with per-manifold parameter groups.

step(closure=None)

Perform one Adam step and dispatch post-update handling by tag.

Adam moments and coordinate updates are followed by these rules:

  • spin: optional bivector coefficient-norm clipping
  • sphere: signature-aware normalization with a near-null fallback
  • euclidean: no post-update transformation

Parameters:

Name Type Description Default
closure Callable

A closure that reevaluates the model and returns the loss.

None

Returns:

Type Description
Optional[Tensor]

Optional[torch.Tensor]: The loss if closure is provided, else None.

tag_manifold(param, manifold)

Tag a parameter for optimizer retraction dispatch and return it.

group_parameters_by_manifold(model)

Group a model's parameters by their _manifold tag.

Parameters without a _manifold attribute are placed in the 'euclidean' group.

Parameters:

Name Type Description Default
model Module

The model whose parameters to group.

required

Returns:

Type Description
Dict[str, List[Parameter]]

A mapping from each supported parameter tag to its parameters. Empty

Dict[str, List[Parameter]]

groups are retained so callers can build optimizer groups consistently.

make_riemannian_optimizer(model, algebra, *, optimizer='adam', **kwargs)

Create a built-in tag-aware optimizer from a model.

Parameters:

Name Type Description Default
model Module

Model whose parameters may be tagged with _manifold.

required
algebra

Clifford algebra instance used by the optimizer.

required
optimizer str

"adam"/"riemannian_adam" or "sgd"/"exponential_sgd".

'adam'
**kwargs

Optimizer-specific keyword arguments.

{}

Returns:

Type Description
Optimizer

RiemannianAdam or ExponentialSGD with per-manifold groups.

project_to_tangent_space(point, vector, algebra)

Project a full-lane ambient vector onto a rotor's tangent space.

For a unit rotor R, the left-trivialized tangent space is T_R Spin(p, q) = {R B | B is a bivector}. The projection computes R <reverse(R) V>_2. Inputs and outputs use canonical full-lane storage; the intermediate bivector uses the algebra's compact grade-2 layout.

Parameters:

Name Type Description Default
point Tensor

Unit rotor with shape [..., algebra.dim].

required
vector Tensor

Ambient vector with the same shape as point.

required
algebra

Layout-first algebra context.

required

Returns:

Type Description
Tensor

A canonical full-lane tangent vector with the same shape as point.

exponential_retraction(point, tangent_vector, algebra)

Apply a left-trivialized exponential update to a unit rotor.

For T = R B with bivector B, this computes Exp_R(T) = R exp(B). Projecting reverse(R) T to grade 2 also makes the function useful when a numerical optimizer supplies an ambient update. Inputs and outputs use canonical full-lane storage.

Parameters:

Name Type Description Default
point Tensor

Unit rotor with shape [..., algebra.dim].

required
tangent_vector Tensor

Tangent or ambient update with the same shape.

required
algebra

Layout-first algebra context.

required

Returns:

Type Description
Tensor

The updated rotor in canonical full-lane storage.

Analysis

These interfaces provide experimental geometric diagnostics. Their outputs describe implemented tensor and coefficient-space calculations. Statistical inference and causal, metric, or symmetry conclusions require separate methods and evidence.

analysis

Descriptive and geometric-representation diagnostics.

The package measures coefficient-space and operator structure. Its rotor-probe signature result ranks candidate algebras as a learned heuristic.

AnalysisConstants dataclass

Central registry of tuneable constants for the analysis toolkit.

Fixed thresholds and budgets that affect analytical decisions are grouped here so they can be adjusted in one place. Numerical guards belong in :mod:clifra.core.foundation.numerics.

Attributes:

Name Type Description
alignment_report_max_dissimilarity float

Maximum neighborhood-connection dissimilarity accepted by the alignment report. See :meth:NeighborhoodBivectorFlow.alignment_threshold_report and :meth:CoordinateLiftAnalyzer.compare_lifts.

bv_sq_elliptic_bound float

Bivector square value below which the bivector is classified as elliptic (negative definite) in signature analysis.

bv_sq_hyperbolic_bound float

Bivector square value above which the bivector is classified as hyperbolic (positive definite) in signature analysis.

near_commuting_mode_threshold float

Normalized commutator norm below which a mode is counted as near-commuting.

basis_reflection_score_threshold float

Maximum basis-reflection distribution score counted in the report summary.

gp_spectrum_matrix_entries int

Maximum square-matrix entries for the full geometric-product operator spectrum.

adjoint_matrix_entries int

Maximum square-matrix entries for the adjoint-operator eigensolver.

analysis_product_pairs int

Maximum planned product interactions for optional full-layout analysis subroutines.

gp_spectrum_n_samples int

Number of data samples used when building the GP left-multiplication matrix.

SamplingConfig dataclass

Controls how raw data is sampled before analysis.

Attributes:

Name Type Description
strategy str

One of "random", "stratified", "bootstrap", "passthrough".

max_samples int

Maximum number of samples to draw (ignored for "passthrough").

seed int

Random seed for reproducibility.

n_bootstrap int

Number of bootstrap resamples (only for "bootstrap").

n_strata Optional[int]

Number of clusters for "stratified" sampling. Auto-determined when None.

AnalysisConfig dataclass

Master configuration for the full analysis pipeline.

Attributes:

Name Type Description
device str

Torch device string.

sampling SamplingConfig

Sampling configuration.

run_dimension bool

Enable covariance-dimension diagnostics.

run_signature_estimation bool

Enable rotor-probe signature estimation.

run_spectral bool

Enable spectral analysis.

run_transformation_diagnostics bool

Enable operational transformation diagnostics.

run_commutator bool

Enable commutator analysis.

energy_threshold float

Cutoff for "active" components (shared across analyzers).

k_neighbors int

Number of nearest neighbors for local analyses.

verbose bool

Print progress messages.

DimensionResult dataclass

Output of :class:CovarianceDimensionAnalyzer.

Attributes:

Name Type Description
broken_stick_dimension int

Broken-stick component count, clamped to at least one for downstream algebra construction.

participation_ratio float

Covariance-spectrum participation ratio (Sum_lam)^2 / Sum_lam^2.

eigenvalues Tensor

Covariance eigenvalues sorted descending.

broken_stick_count int

Number of components exceeding the broken-stick null model.

explained_variance_ratio Tensor

Per-component explained variance ratio.

local_participation_ratios Optional[Tensor]

Per-point neighborhood covariance participation ratios (optional).

SignatureEstimate dataclass

Output of :class:SignatureProbeAnalyzer.

Attributes:

Name Type Description
estimated_signature Tuple[int, int, int]

Probe-selected (p, q, r) candidate from the learned ranking heuristic.

connection_alignment float

Best probe's mean absolute connection alignment.

connection_dissimilarity float

Best probe's neighboring-connection dissimilarity.

energy_breakdown Dict

Per-bivector energy dict from RotorProbeSignatureEstimator._analyze_bivector_energy.

input_dimension_used Optional[int]

Reduced input dimension actually searched (None if no reduction was applied).

SpectralResult dataclass

Output of :class:SpectralAnalyzer.

Attributes:

Name Type Description
grade_energy Tensor

Mean positive lane grade energy [n+1].

mean_bivector_norm Tensor

Norm summary of the mean bivector field.

mean_bivector_components List[Tensor]

Representative full-layout bivector tensors.

gp_action_eigenvalue_magnitudes Optional[Tensor]

Eigenvalues of the geometric-product left-action operator (None if the algebra was too large).

skipped Dict[str, Dict]

Optional analysis subreports skipped by feasibility policy.

TransformationDiagnosticsResult dataclass

Operational output of :class:TransformationDiagnosticsAnalyzer.

Attributes:

Name Type Description
low_energy_vector_directions List[int]

Indices whose normalized observed grade-1 coefficient energy is below the configured threshold.

normalized_vector_energy Tensor

Per-basis-vector normalized energy [n].

odd_grade_energy_fraction float

Fraction of energy in odd-grade components, in [0, 1]. 0 = data lives entirely in the even sub-algebra; 1 = entirely odd grades.

basis_reflection_scores List[Dict]

List of dicts, each with direction index and coefficient-distribution distance score (lower is closer).

near_commuting_mode_count int

Number of modes below the configured normalized commutator threshold.

skipped Dict[str, Dict]

Optional subreports skipped by feasibility policy.

CommutatorResult dataclass

Output of :class:CommutatorAnalyzer.

Attributes:

Name Type Description
pairwise_commutator_norms Tensor

[D, D] mean pairwise commutator norms.

adjoint_eigenvalue_magnitudes Tensor

Magnitudes of eigenvalues of ad_mu.

mean_commutator_norm float

Scalar summary E[||[x_i, mu]||_2].

bivector_bracket_closure Dict

Dict with structure_constants [k, k, k] tensor, closure_error scalar, and basis_indices list.

skipped Dict[str, Dict]

Optional commutator subreports skipped by feasibility policy.

AnalysisReport dataclass

Full analysis report combining all sub-analyzers.

Attributes:

Name Type Description
dimension Optional[DimensionResult]

Covariance-spectrum dimension diagnostics.

signature_estimate Optional[SignatureEstimate]

Rotor-probe signature estimate.

spectral Optional[SpectralResult]

Spectral analysis results.

transformation Optional[TransformationDiagnosticsResult]

Operational transformation diagnostics.

commutator Optional[CommutatorResult]

Commutator analysis results.

metadata Dict

Timing, configuration, and data-shape information.

summary()

Return a human-readable multi-line summary.

commutator

Operational commutator diagnostics for multivector data.

Computes pairwise commutator norms, adjoint eigenvalue magnitudes, and a selected coordinate-bivector closure residual.

CommutatorAnalyzer

Analyze algebraic exchange properties via commutators.

The commutator [A, B] = AB - BA measures non-commutativity. In Clifford algebras, commutators of grade-1 elements yield grade-2 elements (bivectors), directly related to rotation planes.

Parameters:

Name Type Description Default
algebra AlgebraLike

Layout-first algebra host.

required
max_bivectors int

Maximum number of bivectors for Lie-bracket closure analysis (guards combinatorial cost).

commutator_max_bivectors

analyze(mv_data)

Full commutator analysis.

Parameters:

Name Type Description Default
mv_data Tensor

Multivector data. Accepted shapes:

  • [N, dim] -- single-channel batch.
  • [N, C, dim] -- multi-channel batch (channels averaged).
required

Returns:

Type Description
CommutatorResult

class:CommutatorResult.

pairwise_commutator_norms(mv_data)

Return mean commutator norms for pairs of vector coordinates.

For each pair (i, j) of the n basis-vector directions, computes E[||[x_i, x_j]||] where x_i is the data projected onto e_i.

Parameters:

Name Type Description Default
mv_data Tensor

[N, dim] multivector data.

required

Returns:

Type Description
Tensor

[n, n] symmetric matrix of mean commutator norms.

adjoint_eigenvalue_magnitudes(mv_data)

Eigenvalue magnitudes of the adjoint operator ad_mu.

Constructs the explicit matrix for ad_mu(x) = [mu, x] where mu = E[x] and diagonalizes it.

Parameters:

Name Type Description Default
mv_data Tensor

[N, dim] multivector data.

required

Returns:

Type Description
Tensor

Eigenvalue magnitudes sorted descending. Returns an

Tensor

empty tensor if the algebra is too large.

mean_commutator_norm(mv_data)

E[||[x_i, mu]||_2] -- scalar non-commutativity summary.

Parameters:

Name Type Description Default
mv_data Tensor

[N, dim] multivector data.

required

Returns:

Type Description
float

Mean commutator norm (float).

bivector_bracket_closure(mv_data)

Measure bracket closure for selected coordinate basis bivectors.

Selects coordinate bivector lanes by mean observed magnitude, builds the corresponding basis bivectors, and measures the residual after projecting their pairwise brackets back into that selected span.

Parameters:

Name Type Description Default
mv_data Tensor

[N, dim] multivector data.

required

Returns:

Type Description
Dict

Dict with "structure_constants" ([k, k, k]),

Dict

"closure_error" (scalar), and "basis_indices" (list

Dict

of multivector-coefficient indices of the chosen bivectors).

compute_mean_commutator_and_procrustes_alignment(algebra, data_tensor)

Compute a mean commutator norm and an SVD Procrustes alignment.

Parameters:

Name Type Description Default
algebra AlgebraLike

Layout-first algebra host.

required
data_tensor Tensor

[N, D] tensor of raw features.

required

Returns:

Type Description

Tuple (mean_commutator_norm, alignment_matrix). These descriptive

calculations contain no uncertainty estimate.

dimension

Effective-dimension analysis and dimension lifting.

Implements participation ratio, broken-stick null model, local-dimension estimation, and algebraic dimension lifting to determine how many dimensions the data actually occupies and whether lifting reveals latent structure.

CovarianceDimensionAnalyzer

Compute covariance-spectrum dimension diagnostics.

The reported dimension is the number of normalized covariance eigenvalues above a broken-stick reference, clamped to at least one. This is a descriptive heuristic; establishing intrinsic dimension requires separate analysis.

Parameters:

Name Type Description Default
device str

Torch device string.

'cpu'
dtype dtype

Floating-point dtype used for covariance computations. Defaults to torch.float32. Pass torch.float64 for higher-precision analyses.

default_dtype
k_local int

Number of neighbors for local-dimension estimation.

dimension_k_local
energy_threshold float

Minimum normalized eigenvalue to count as active.

default_energy_threshold

analyze(data)

Compute covariance eigenvalue and broken-stick diagnostics.

Parameters:

Name Type Description Default
data Tensor

[N, D] raw data tensor.

required

Returns:

Type Description
DimensionResult

class:DimensionResult with eigenvalues, participation

DimensionResult

ratio, broken-stick count, and optional local participation ratios.

reduce(data, target_dim)

PCA projection to target_dim dimensions.

Parameters:

Name Type Description Default
data Tensor

[N, D] tensor.

required
target_dim int

Target dimensionality.

required

Returns:

Type Description
Tensor

[N, target_dim] projected tensor.

CoordinateLiftAnalyzer

Compare connection scores after coordinate lifting.

The comparison measures how appending a fixed coordinate changes neighborhood-bivector alignment scores.

Lifting appends extra coordinates to the grade-1 embedding:

  • Positive lift Cl(p, q) -> Cl(p+1, q): adds a spacelike dimension. The extra coordinate is set to 1 (projective / homogeneous lift).
  • Negative-square lift Cl(p, q) -> Cl(p, q+1): adds a negative generator and initializes its input coordinate to 0.

The comparison reports operational scores only.

lift(data, target_algebra, fill=CONSTANTS.dimension_lift_positive_fill)

Lifts data into the grade-1 subspace of a higher-dimensional algebra.

Pads each data vector with fill values in the new dimensions, then embeds as a grade-1 multivector.

Parameters:

Name Type Description Default
data Tensor

[N, d] source data.

required
target_algebra AlgebraLike

Target algebra with n >= d.

required
fill float

Coordinate value for the new dimensions. Use 1.0 for a projective (homogeneous) lift, 0.0 for a zero-initialized added coordinate.

dimension_lift_positive_fill

Returns:

Type Description
Tensor

[N, target_algebra.dim] grade-1 multivectors.

compare_lifts(data, p, q, k=CONSTANTS.default_k_neighbors)

Compare neighborhood-connection scores across lifts.

Tests three algebras:

  1. Original Cl(p, q): baseline connection_alignment and connection_dissimilarity.
  2. Positive lift Cl(p+1, q): spacelike extra dimension, fill=1.
  3. Negative-square lift Cl(p, q+1): one additional negative generator, with its input coordinate initialized to zero. The added generator is not signature-null.

Parameters:

Name Type Description Default
data Tensor

[N, d] data where d = p + q.

required
p int

Original positive signature.

required
q int

Original negative signature.

required
k int

Number of coefficient-space nearest neighbors.

default_k_neighbors

Returns:

Type Description
Dict

Operational scores for the original and two lifted embeddings,

Dict

plus the key with the highest connection alignment.

format_report(results)

Render the coordinate-lift comparison.

geodesic

Nearest-neighbor bivector-flow diagnostics.

NeighborhoodBivectorFlow

Compute bivector statistics over coefficient-space neighbors.

Data points are interpreted as grade-1 multivectors. Neighbors are selected by Euclidean distance in coefficient space, and each point-neighbor pair is represented by the normalized grade-2 part of their geometric product.

The flow is computed as the mean of connection bivectors:

B_ij = <x_i . ~x_j>_2   (grade-2 part of the geometric product)

The two scalar summaries are operationally defined as:

  • connection_alignment: mean absolute cosine between connection bivectors within each neighborhood;
  • connection_dissimilarity: one minus the mean cross-neighborhood absolute cosine used by this implementation.

They characterize exploratory coefficient-space behavior; manifold curvature, causality, and exact geodesic connections lie beyond what these scores measure.

__init__(algebra, k=CONSTANTS.default_k_neighbors)

Initialize the neighborhood-bivector diagnostic.

Parameters:

Name Type Description Default
algebra AlgebraLike

Layout-first algebra context.

required
k int

Number of nearest neighbors for the flow field.

default_k_neighbors

flow_bivectors(mv)

Computes the mean flow bivector at each data point.

For each point x_i, aggregates the unit connection bivectors to its k-nearest neighbours:

B_i = mean_j { unit( <x_i . ~x_j>_2 ) }

.. note:: For perfectly symmetric data (e.g. a closed circle) the mean cancels to zero -- which is geometrically correct since there is no preferred mean direction. Use :meth:connection_alignment to measure pairwise alignment without this cancellation.

Parameters:

Name Type Description Default
mv Tensor

[N, dim] grade-1 multivectors.

required

Returns:

Type Description
Tensor

torch.Tensor: [N, dim] mean flow bivectors.

connection_alignment(mv)

Measures concentration of connection bivectors within each neighborhood.

For each point, computes the mean absolute cosine similarity between all pairs of its k connection bivectors. This captures how consistently the neighborhood connections lie on the same rotation plane.

  • 1.0: all connections at every point are parallel or anti-parallel (maximally structured).
  • 1/num_bivectors (~= baseline): connections point in random directions.

.. note:: In Cl(2,0) the grade-2 space is 1-dimensional (only e_12), so connection_alignment is trivially 1.0 for any data -- use at least Cl(3,0) for meaningful discrimination.

Parameters:

Name Type Description Default
mv Tensor

[N, dim] multivectors.

required

Returns:

Name Type Description
float float

Connection-alignment score in [0, 1].

connection_dissimilarity(mv)

Measures how much connection structure changes across the manifold.

Computes the mean dissimilarity of connection bivectors between neighboring pairs of points:

dissimilarity(i, j) = 1 - mean_abs_cos( {B_ia}, {B_jb} )

where {B_ia} is the set of k unit connection bivectors at point i and {B_jb} at point j, and mean_abs_cos is the cross-set absolute cosine similarity.

  • 0.0: all neighboring points have the same connection structure under this coefficient-space statistic.
  • High: the connection direction changes rapidly between neighbors under this coefficient-space statistic.

Parameters:

Name Type Description Default
mv Tensor

[N, dim] multivectors.

required

Returns:

Name Type Description
float float

Connection-dissimilarity score in [0, 1].

approximate_bivector_interpolation(a, b, steps=CONSTANTS.bivector_interpolation_steps)

Return a first-order bivector-log interpolation.

Uses the Lie group exponential map on the transition element:

T = a_inv . b
log(T) ~= <T - 1>_2     (grade-2 approximation for small angles)
gamma(t) = a . exp(t . log(T))

This local construction uses the regularized blade inverse and a grade-2 first-order logarithm.

Parameters:

Name Type Description Default
a Tensor

Start multivector [dim].

required
b Tensor

End multivector [dim].

required
steps int

Number of interpolation steps (including endpoints).

bivector_interpolation_steps

Returns:

Type Description
Tensor

torch.Tensor: [steps, dim] sequence of multivectors.

alignment_threshold_report(data)

Apply configured thresholds to the two connection statistics.

Alignment must exceed the midpoint between the random-vector baseline and 1.0; dissimilarity must remain below the configured maximum. The boolean reports only these inequalities.

Parameters:

Name Type Description Default
data Tensor

[N, d] raw data.

required

Returns:

Name Type Description
Dict Dict

report with keys connection_alignment, connection_dissimilarity,

Dict

passes_alignment_thresholds, baseline, threshold, and

Dict

label.

per_point_connection_alignment(mv)

Return per-point within-neighborhood absolute-cosine alignment.

Returns a scalar connection_alignment value per data point, measuring how well-aligned that point's neighborhood connections are.

Parameters:

Name Type Description Default
mv Tensor

[N, dim] multivectors.

required

Returns:

Type Description
Tensor

torch.Tensor: [N] connection_alignment scores in [0, 1].

pipeline

Orchestrate geometric diagnostics in one pipeline.

GeometricAnalyzer

Top-level orchestrator for the geometric analysis toolkit.

Runs a configurable subset of analyzers in the correct dependency order and returns an :class:AnalysisReport.

Input modes:

  • data.ndim == 2 and algebra is None -- raw mode: full pipeline from sampling through signature estimation to GA diagnostics.
  • data.ndim == 3 and algebra is not None -- pre-embedded mode: skip sampling, dimension, and signature estimation; run spectral, transformation, and commutator diagnostics directly.
  • data.ndim == 2 and algebra is not None -- raw + known algebra: embed data, then run GA analyses.

Parameters:

Name Type Description Default
config Optional[AnalysisConfig]

Master analysis configuration.

None

analyze(data, algebra=None)

Run the full geometric analysis pipeline.

Parameters:

Name Type Description Default
data Tensor

Raw [N, D] or pre-embedded [N, C, 2^n] tensor.

required
algebra Optional[AlgebraLike]

Required when data is pre-embedded. Optional when raw -- will be created from the signature estimate.

None

Returns:

Type Description
AnalysisReport

class:AnalysisReport.

policy

Static analysis policy.

Analysis routines sometimes need optional full-lane matrices or broad products that are not part of normal model forward paths. This module keeps those decisions equation-based and separate from benchmark observations while using the same static metadata style as planner policy.

AnalysisCostPolicy dataclass

Equation weights for optional analysis materialization decisions.

AnalysisFeasibility dataclass

Static cost verdict for optional analysis materialization.

__bool__()

Allow direct use in guards.

MatrixAnalysisCost dataclass

Static cost summary for an explicit analysis matrix.

matrix_entries property

Return square matrix element count.

estimated_bytes property

Return estimated matrix storage bytes.

score property

Return the weighted analysis score.

limit_score property

Return the weighted score limit.

details()

Return JSON-like metadata for diagnostics.

ProductAnalysisCost dataclass

Static cost summary for an optional analysis product.

score property

Return the weighted analysis score.

limit_score property

Return the weighted score limit.

details()

Return JSON-like metadata for diagnostics.

feasibility_record(feasibility)

Return JSON-like metadata for a feasibility verdict.

analysis_cost_policy_for(algebra, policy=None)

Return an analysis cost policy for an algebra-like object.

evaluate_matrix_cost(cost)

Return a feasibility verdict for a matrix cost.

build_product_analysis_cost(algebra, *, role, op, left_layout, right_layout, output_layout, max_pairs, dtype=None, device=None, policy=None)

Build static product cost metadata using planner policy estimates.

evaluate_product_cost(cost)

Return a feasibility verdict for a product cost.

sampler

Sampling strategies for geometric diagnostics.

The stratified strategy bins an operational neighborhood-connection alignment score in a capped Euclidean algebra.

StatisticalSampler

Stateless sampler supporting multiple strategies.

Supports "random", "stratified", "bootstrap", and "passthrough" strategies. All methods are deterministic when a seed is provided.

The "stratified" strategy partitions per-point connection-alignment scores into quantile strata in a capped Euclidean algebra.

sample(data, config) staticmethod

Sample from data according to config.

Parameters:

Name Type Description Default
data Tensor

[N, D] tensor of observations.

required
config SamplingConfig

Sampling configuration.

required

Returns:

Type Description
Union[Tensor, List[Tensor]]

(sampled, metadata) where sampled is a tensor (or list

Dict

of tensors for "bootstrap") and metadata is a dict with

Tuple[Union[Tensor, List[Tensor]], Dict]

at least "strategy".

recommend_size(n_features, n_total) staticmethod

Heuristic recommendation for adequate sample size.

Returns min(n_total, max(CONSTANTS.sampling_recommended_min_samples, CONSTANTS.sampling_recommended_feature_multiplier * n_features)).

signature

Rotor-probe metric-signature estimation.

Provides :class:RotorProbeSignatureEstimator (a learned heuristic) and :class:SignatureProbeAnalyzer (higher-level wrapper with dimension reduction and bootstrap agreement estimates).

These routines rank candidate signatures from trained probe energy and report the selected candidate with bootstrap agreement statistics.

RotorProbeSignatureEstimator

Select a (p, q, r) candidate from rotor probes.

Trains small single-rotor probes on conformally-lifted data using connection_alignment + connection_dissimilarity as the loss. After training, reads the learned bivector energy distribution to select a signature estimate.

Multiple biased initializations reduce sensitivity to local minima and the learned energy ranking selects the returned candidate.

estimate(data)

Return the selected (p, q, r) signature estimate.

Parameters:

Name Type Description Default
data Tensor

Input data [N, D].

required

Returns:

Type Description
Tuple[int, int, int]

Tuple[int, int, int]: Selected signature estimate.

estimate_detailed(data)

Return the candidate tuple and probe diagnostics.

Parameters:

Name Type Description Default
data Tensor

Input data [N, D].

required

Returns:

Type Description
Dict

Diagnostics with estimated_signature, operational connection

Dict

scores, energy breakdown, and per-probe results.

SignatureProbeAnalyzer

Signature-candidate analysis with optional PCA reduction.

Wraps :class:RotorProbeSignatureEstimator and adds:

  • Automatic PCA reduction when the input exceeds the algebra tractability threshold.
  • Bootstrap vote distribution and majority agreement.

Parameters:

Name Type Description Default
device str

Torch device string.

'cpu'
max_search_dim int

Maximum data dimension before PCA reduction. CGA lift adds 2, so max_search_dim=10 -> Cl(11,1) with 2^12 = 4096-dim multivectors (the algebra ceiling). Defaults to 10.

signature_search_max_dim
signature_probe_kwargs Optional[Dict]

Extra keyword arguments forwarded to :class:RotorProbeSignatureEstimator.

None

analyze(data, dim_result=None)

Run the rotor-probe heuristic, optionally reducing dimensions.

Parameters:

Name Type Description Default
data Tensor

[N, D] raw data.

required
dim_result Optional[DimensionResult]

Pre-computed dimension analysis. When provided and dim_result.broken_stick_dimension < D, the data is PCA-reduced before searching.

None

Returns:

Type Description
SignatureEstimate

class:SignatureEstimate.

analyze_with_confidence(data, n_bootstrap=CONSTANTS.signature_bootstrap_resamples, dim_result=None)

Run the signature heuristic on bootstrap resamples.

Runs the search on n_bootstrap resampled datasets and reports the majority-vote signature plus the full distribution.

Returns:

Type Description
SignatureEstimate

(best_result, confidence) where confidence contains

Dict

"distribution" (Counter) and "agreement" (float).

spectral

Spectral analysis of multivector data in a Clifford algebra.

Computes grade-energy spectrum, mean-bivector magnitude, and optionally the eigenvalue spectrum of the geometric-product operator.

SpectralAnalyzer

Compute descriptive spectra and mean-coefficient diagnostics.

Three independent analyses are combined:

  1. Grade energy spectrum -- population-level distribution of positive coefficient lane energy across all grades.
  2. Mean bivector summary -- norm and coefficients of the sample mean's grade-2 component, reported separately from spectral decomposition.
  3. GP action eigenvalue magnitudes -- magnitudes of eigenvalues of the left-multiplication operator :math:L_x(y) = x \cdot y (only for small algebras).

analyze(mv_data)

Full spectral analysis.

Parameters:

Name Type Description Default
mv_data Tensor

Multivector data. Accepted shapes:

  • [N, dim] -- single-channel batch.
  • [N, C, dim] -- multi-channel batch (channels are averaged before bivector / GP analysis).
required

Returns:

Type Description
SpectralResult

class:SpectralResult.

grade_energy_spectrum(mv_data)

Mean positive lane grade energy across the batch.

Parameters:

Name Type Description Default
mv_data Tensor

[N, C, dim] multivector data.

required

Returns:

Type Description
Tensor

[n+1] tensor of mean grade energies.

mean_bivector_summary(mv_data)

Return the mean-bivector magnitude and representative component.

Parameters:

Name Type Description Default
mv_data Tensor

[N, C, dim] multivector data.

required

Returns:

Type Description
tuple

(norm, components) where norm is a one-element tensor

tuple

containing the mean-bivector norm and components contains the

tuple

corresponding full-layout mean bivector.

gp_action_eigenvalue_magnitudes(mv_data, n_samples=None)

Eigenvalue magnitudes of the left-multiplication operator.

For a subsample of data points, constructs the explicit matrix representation of :math:L_x(y) = x \cdot y and computes eigenvalues.

Parameters:

Name Type Description Default
mv_data Tensor

[N, C, dim] multivector data.

required
n_samples Optional[int]

Number of data points to sample.

None

Returns:

Type Description
Tensor

Sorted (descending) eigenvalue magnitudes.

symmetry

Operational transformation diagnostics for multivector data.

Computes low-energy grade-1 directions, odd-grade energy fraction, reflection scores, and near-zero commutator modes.

TransformationDiagnosticsAnalyzer

Compute coefficient and transformation diagnostics.

The methods report explicitly defined energy, distribution-distance, and commutator statistics for the implemented transformations.

Parameters:

Name Type Description Default
algebra AlgebraLike

Layout-first algebra host.

required
low_energy_threshold float

Normalized grade-1 coefficient-energy threshold below which a basis direction is reported.

low_energy_vector_threshold

analyze(mv_data, commutator_result=None)

Compute the complete operational transformation report.

Parameters:

Name Type Description Default
mv_data Tensor

Multivector data. Accepted shapes:

  • [N, dim] -- single-channel batch.
  • [N, C, dim] -- multi-channel batch (channels averaged for scalar-valued analyses).
required
commutator_result Optional[CommutatorResult]

Pre-computed commutator results for optional adjoint-mode counting.

None

Returns:

Type Description
TransformationDiagnosticsResult

class:TransformationDiagnosticsResult.

low_energy_vector_directions(mv_data)

Return low-energy grade-1 coordinate directions and their energies.

For each basis vector e_i, computes the mean squared projection energy of the data onto that direction. Directions below :attr:low_energy_threshold are reported. This is an observed-data diagnostic and is unrelated to null generators in the algebra's signature.

Parameters:

Name Type Description Default
mv_data Tensor

[N, dim] multivector data.

required

Returns:

Type Description
Tuple[List[int], Tensor]

(indices, normalized_energy) with one energy per vector lane.

odd_grade_energy_fraction(mv_data)

Measure the fraction of coefficient energy in odd grades.

Computes the fraction of total energy in odd-grade components:

score = E[ ||x_odd||^2 / ||x||^2 ]

where x_odd = (x - alpha(x)) / 2 and alpha is the grade involution (flips odd-grade components).

Returns:

Type Description
float

Score in [0, 1]. 0 means the data lives entirely in

float

the even sub-algebra; 1 means entirely odd grades.

basis_reflection_scores(mv_data)

Compute coefficient-distribution distance after each basis reflection.

For each basis vector e_i, reflects the data x' = -e_i x e_i^{-1} and compares the reflected distribution to the original.

Returns:

Type Description
List[Dict]

List of dicts {"direction": i, "score": float} sorted

List[Dict]

by score ascending. Lower means the independently sorted

List[Dict]

coefficient distributions are closer under this statistic.

near_commuting_mode_count(mv_data, commutator_result=None, threshold=None)

Count modes below a normalized commutator threshold.

Without a precomputed commutator result, the method counts basis bivectors whose mean normalized commutator norm is below threshold.

If a :class:CommutatorResult is provided, the method instead counts near-zero values in its full adjoint eigenvalue magnitudes. The two branches do not necessarily count modes in spaces of the same dimension.

Parameters:

Name Type Description Default
mv_data Tensor

[N, dim] multivector data.

required
commutator_result Optional[CommutatorResult]

Pre-computed commutator analysis.

None
threshold Optional[float]

Normalized commutator norm below which a bivector is counted as near-commuting.

None

Returns:

Type Description
int

Number of modes below the selected threshold.

Utilities

mps

MPS-specific operator fallbacks.

safe_linalg_solve(A, B)

Solve on CPU when the input lives on MPS.