Skip to content

API Reference

The reference is generated from public source modules. Layouts and tensor contracts declare coefficient meaning; planned operations retain those declarations for repeated execution.

Algebra and representation

config

Stable algebra construction, independent of kernel tuning.

algebra

Concrete mathematical API over private planning and execution.

AlgebraContext

Clifford signature and operations with explicit coefficient contracts.

Omitted input declarations mean full-basis tensors. Layouts declare compact storage; TensorContract explicitly selects compact or canonical storage. Semantic layouts are never inferred from tensor widths.

spec = AlgebraSpec(p, q, r) instance-attribute

num_grades = self.n + 1 instance-attribute

resource_limits property

Immutable static allocation budget used when planning operations.

registry property

Immutable provider collection used for planning this algebra's operations.

device property

dtype property

__init__(p, q=0, r=0, *, device='cpu', dtype=torch.float32, registry=None, resource_limits=None)

layout(grades=None)

Declare whole grades, or the full basis when omitted.

to(device=None, dtype=None)

Set defaults for future plans; existing plans move independently.

plan_product(*, op='geometric_product', left=None, right=None, output=None, pairwise=False)

Plan a binary product for fixed contracts and item-axis behavior.

product(a, b, *, op='geometric_product', left=None, right=None, output=None, pairwise=False)

Execute a declared binary Clifford product.

geometric_product(a, b, *, left=None, right=None, output=None, pairwise=False)

Geometric product AB.

wedge(a, b, *, left=None, right=None, output=None, pairwise=False)

left_contraction(a, b, *, left=None, right=None, output=None, pairwise=False)

right_contraction(a, b, *, left=None, right=None, output=None, pairwise=False)

symmetric_product(a, b, *, left=None, right=None, output=None, pairwise=False)

Normalized anticommutator (AB + BA) / 2.

commutator_product(a, b, *, left=None, right=None, output=None, pairwise=False)

Unnormalized commutator AB - BA.

anti_commutator_product(a, b, *, left=None, right=None, output=None, pairwise=False)

Unnormalized anticommutator AB + BA.

plan_unary(*, op, input=None, output=None)

unary(values, *, op, input=None, output=None)

reverse(values, *, input=None, output=None)

grade_involution(values, *, input=None, output=None)

clifford_conjugation(values, *, input=None, output=None)

grade_projection(values, *, output, input=None)

plan_signature_norm_squared(*, input=None, output=None)

signature_norm_squared(values, *, input=None, output=None)

Signed scalar form _0.

pseudoscalar_product(values, *, input=None, output=None)

plan_bivector_exp(*, input=None, output=None)

bivector_exp(values, *, input=None, output=None)

Exponentiate grade 2; full-basis input is projected to grade 2.

plan_versor_action(*, grade, input=None, parameter=None, output=None)

Plan reflection (grade 1) or exp(-B/2) rotor action (grade 2).

versor_action(values, weights, *, grade, input=None, parameter=None, output=None)

plan_blade_inverse(*, input=None, output=None)

blade_inverse(a, *, input=None, output=None)

Return the epsilon-stabilized blade inverse.

plan_strict_blade_inverse(*, input=None, output=None)

strict_blade_inverse(a, *, input=None, output=None)

blade_project(values, a, *, input=None, blade=None, output=None)

plan_strict_blade_project(*, input=None, blade=None, output=None)

strict_blade_project(values, a, *, input=None, blade=None, output=None)

Project using an exact blade inverse, raising for a zero denominator.

plan_blade_reject(*, input=None, blade=None, output=None)

blade_reject(values, a, *, input=None, blade=None, output=None)

plan_strict_blade_reject(*, input=None, blade=None, output=None)

strict_blade_reject(values, a, *, input=None, blade=None, output=None)

Reject using an exact blade inverse, raising for a zero denominator.

plan_reflect(*, input=None, normal=None, output=None)

Plan reflection in a declared grade-one normal.

reflect(values, a, *, input=None, normal=None, output=None)

Reflect a multivector in a declared grade-one normal.

plan_strict_reflect(*, input=None, normal=None, output=None)

Plan exact-denominator reflection in a declared grade-one normal.

strict_reflect(values, a, *, input=None, normal=None, output=None)

Reflect using an exact normal inverse, raising for a zero denominator.

plan_versor_product(*, input=None, versor=None, output=None)

versor_product(a, values, *, input=None, versor=None, output=None)

plan_strict_versor_product(*, input=None, versor=None, output=None)

strict_versor_product(a, values, *, input=None, versor=None, output=None)

Apply a versor with its exact inverse, raising for a zero denominator.

plan_sandwich_action(*, left=None, input=None, right=None, output=None)

Plan L X R with ordinary tensor broadcasting.

sandwich_product(a, values, b, *, left=None, input=None, right=None, output=None)

plan_linear_action(*, input=None, output=None)

Plan induced action of [..., n, n] matrices on broadcast [..., lanes] values.

linear_action(values, matrix, *, input=None, output=None)

scalar_product(a, b, *, left=None, right=None)

lane_dot_product(a, b, *, left=None, right=None)

lane_energy(values, *, input=None, grades=None)

Coefficient energy, optionally selected by grade, without batch reduction.

lane_norm(values, *, input=None)

lane_distance(a, b, *, left=None, right=None)

lane_grade_energy(values, *, input=None)

lane_grade_norms(values, *, input=None)

lane_grade_distribution(values, *, input=None, eps=1e-08)

conjugate_scalar_form(a, b, *, left=None, right=None)

format_multivector(values, **kwargs)

layout

Static algebra and compact grade-layout value objects.

Layout

Bases: Protocol

Ordered coefficient lanes, independent of a planner's representation.

GradeLayout is the supported implementation today. A future selected-blade layout can implement this contract without changing tensor declarations.

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 fixed-grade layout whose basis indices are lowered on demand.

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.

positions_for_basis(basis_indices, *, device=None)

Locate basis blades in requested order, rejecting absent blades.

grade_mask(grades, *, device=None)

Boolean mask in compact-lane order for the selected grades.

union(other)

Return the union of two grade layouts.

intersection(other)

Return shared grades, including an empty layout when disjoint.

difference(other)

Return grades present only in this layout.

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.

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.

spec property

Signature derived from the semantic layout.

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(layout) classmethod

Return a compact-lane contract for layout.

canonical(layout) classmethod

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

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

Validate that values obeys this contract.

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.

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.

Planned operations and modules

ResourceLimits dataclass

Immutable coefficient-width and static interaction budgets.

Counts cover execution structures and known fixed-shape temporaries, not caller-controlled batch dimensions or total device memory. Warnings start at the warning thresholds; requirements above a maximum are rejected.

operation

Stable callable boundary for already planned tensor operations.

PlannedOperation

Bases: Module

Execute fixed contracts without consulting the algebra or planner.

The concrete kernel and its buffers are private implementation details. Move this module with to or register it on an owning PyTorch module. Rebuild plans from declarations when loading across library versions.

inputs property

Input declarations; None denotes an ordinary non-Clifford tensor.

output property

Immutable result declaration.

module

PyTorch ownership of a shared algebra reference.

CliffordModule

Bases: Module

Own an algebra reference and move its defaults with this module.

Executors

executors

Explicit executor extensions, independent of built-in planning representations.

Providers implement one mathematical family/route and return an nn.Module whose forward accepts the declared compact coefficient tensors and returns compact output. Ordinary leading-dimension broadcasting applies to products; clifra supplies pairwise expansion. None input contracts denote ordinary tensor operands. Provider identity and behavior must remain fixed while a registry is in use.

ExecutorRequest dataclass

Resolved operation, compact lane contracts, and requested tensor placement.

No planner, algebra instance, tree, or built-in algorithm options are exposed. Providers must reject operations or contract combinations they do not implement.

Assessment dataclass

Acceptance of the declared mathematical operation and tensor contracts.

No deliberate truncation or approximation of the operation is implied by acceptance. Ordinary numerical roundoff is permitted. Providers must report conservative maximum coefficient-lane count and static pair/interaction footprint, including child plans that coexist in the constructed module and any larger known fixed-shape temporary. Caller-controlled batch dimensions are excluded. Zero declares no additional requirement; input/output widths are guarded independently. Assessment must not allocate execution buffers.

Preparation belongs exclusively to the provider. The exact assessment and request objects returned/received here are passed unchanged to build().

Rejected dataclass

An unavailable route has only a reason, with no preparation.

ExecutorProvider

Bases: Protocol

One deterministic route; build must use its successful assessment unchanged.

ExecutorRegistry dataclass

Immutable explicit provider collection, replacing the default registry.

Use default().providers when retaining built-ins alongside supplied providers. The first eligible provider establishes precedence. If it is external, it wins. If it is built-in, private policy chooses among eligible built-ins. Thus prepended external providers override built-ins and appended external providers are fallbacks when no built-in can execute the request. Rejected and over-budget providers do not establish precedence. External routes are never compared using built-in work scores. There is no global registry.

default() classmethod

Return a fresh immutable collection of the built-in route providers.

Optimization

updates

Explicit adjustments for ordinary PyTorch optimization loops.

PostUpdateSGD

Bases: SGD

PyTorch SGD followed by one optional zero-argument adjustment callback.

The callback runs once under no_grad after each successful step, outside the loss closure, including steps with no gradients. Select parameters explicitly in that callback. Other options are passed to torch.optim.SGD; differentiable=True is unsupported because adjustments are not recorded.

Momentum is unchanged by adjustments. The callback is not optimizer state: supply it again when constructing an optimizer to load a state_dict.

clip_coefficients_(values, max_norm, *, dim=-1)

Bound Euclidean coefficient length along dim, preserving tensor identity.

Values must be finite real coefficients. max_norm must be finite and positive. No algebra, grade, or parameter meaning is inferred. Zero vectors and vectors within the bound are unchanged; optimizer state is untouched.

normalize_coefficients_(values, *, dim=-1)

Normalize finite real coefficient vectors in place along dim.

Every nonzero vector receives unit Euclidean coefficient length; zero vectors remain zero. This does not enforce a Clifford signature norm or rotor membership. Tensor identity and optimizer state are preserved.

post_update(*adjustments)

Run explicit zero-argument adjustments in order, without recording grads.

Call after optimizer.step(), outside its closure. Callbacks select their own tensors and should mutate them in place. No parameters are discovered or filtered by gradient presence, and optimizer moments are not transported. A callback exception propagates; earlier adjustments are not rolled back.

project_to_rotor_tangent_space(rotor, vector, algebra)

Return R _2 for a unit rotor R and ambient coefficients V.

Both inputs must have identical shape and canonical full-lane storage, with dtype and device matching the algebra. The caller must supply a rotor with reverse(R) R = 1; membership is not checked or repaired. Under that assumption this is an idempotent map onto tangents R B. It is not claimed to be a Euclidean orthogonal projection in mixed or degenerate signatures. The operation is differentiable.

exponential_update(rotor, tangent_vector, algebra)

Return R exp(_2), with the step size already included in T.

Inputs have identical shape and canonical full-lane storage, with dtype and device matching the algebra. R must already be a unit rotor; this function does not normalize arbitrary coefficients. For T = R B the update is R exp(B); ambient T is first mapped to a tangent. There is no implicit minus sign or half-angle factor: callers supply the complete signed and scaled update, including any parameterization convention. This differentiable group update is not a general Riemannian exponential for a chosen metric, and does not transport optimizer moments. Numerical support and rounding follow the core Clifford product and bivector_exp.

Analysis

commutator

Commutator measurements in an explicitly declared algebra.

CommutatorResult dataclass

Measurements of canonical observations; None denotes a skipped measurement.

Pairwise norms have shape [n,n] for vector-coordinate pairs. Adjoint eigenvalue magnitudes describe x -> [mean(data), x]. The mean norm uses full data. Normalized basis-bivector norms follow the core grade-2 layout order and divide mean bracket norms by max(mean data coefficient norm, epsilon).

CommutatorAnalyzer

Measure nonempty canonical [N, dim] floating-point observations.

vector_pair_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)

Sorted full sample-mean adjoint eigenvalue magnitudes, or None at resource limits.

mean_commutator_norm(mv_data)

Mean full-multivector ||[x, mean(x)]||, or None at resource limits.

basis_bivector_commutator_norm_ratios(mv_data)

Return normalized norms in canonical grade-2 order, or None when skipped.

bivector_bracket_closure(blade_indices)

Measure closure of explicitly supplied coordinate bivectors.

Indices are unique canonical blade indices of grade 2 (at most 15). Returns projected bracket coefficients, mean relative residual over nonzero brackets, and the supplied index order. No data selects the span.

spectral

Grade measurements and sample-mean multiplication spectra.

SpectralResult dataclass

Measurements of canonical observations.

grade_coefficient_energy is the mean positive coefficient energy per grade. mean_bivector is the canonical grade-2 projection of the sample mean. The optional eigenvalue magnitudes describe left multiplication by that same mean, sorted descending. Unavailable measurements have skip records.

SpectralAnalyzer

Measure nonempty canonical [N, dim] floating-point observations in a declared algebra.

grade_coefficient_energy(mv_data)

Return [n+1] mean positive coefficient energies.

mean_bivector(mv_data)

Return the canonical [dim] grade-2 sample mean, without thresholding.

left_multiplication_eigenvalue_magnitudes(mv_data)

Return sorted sample-mean left-multiplication eigenvalue magnitudes, or None.

transformation

Declared-grade energies and basis-reflection distribution measurements.

TransformationDiagnosticsResult dataclass

Measurements of canonical observations, without inferred labels.

Vector energy is mean squared grade-1 coefficients, shape [n]. Odd-grade fraction averages each observation's energy fraction (zero contributes zero). Reflection scores compare independently sorted coefficient marginals after grade-extended basis reflection, normalized by mean input coefficient energy. A null direction has score None; a resource-skipped collection is None.

TransformationDiagnosticsAnalyzer

Measure nonempty canonical [N, dim] floating-point observations.

vector_coefficient_energy(mv_data)

Return [n] mean squared vector coefficients, without normalization.

odd_grade_energy_fraction(mv_data)

Mean odd/total coefficient energy per observation; zero contributes zero.

basis_reflection_marginal_scores(mv_data)

Return normalized squared marginal-difference scores, or None at resource limits.

Invertible directions are sorted by score; noninvertible directions follow with score None. Reflection is e_i alpha(x) e_i^{-1} on all grades.

Experimental analysis

These interfaces describe exploratory procedures rather than stable algebraic contracts. See Use experimental analysis for their assumptions and interpretation.

signature

Active signature evidence from a fixed quadratic-lift probe workflow.

Probes train in Cl(D+1,1); the selected probe's bivector parameter energies are mapped to a heuristic active (p, q) pair. Unresolved features are counted separately and are not interpreted as null directions.

SignatureProbeResult dataclass

Heuristic active (p, q) evidence, unresolved features, and probe scores.

unresolved_features is the probe feature width minus p+q, after any PCA. It includes inactive/unassigned features, not null directions. Discarded PCA coordinates are outside this count. pca_output_width is the actual PCA width, or None without reduction. bivector_parameter_summary contains channel-mean squared bivector parameters, normalized by their maximum, and counts of active coordinates dominated by elliptic or hyperbolic bivector contributions. These are weight classifications, not generator signs. Per-probe best_training_loss is the lowest recorded training objective; neighborhood scores are evaluated after restoring the selected parameters. Each probe record includes its init_mode; list order identifies repeated modes.

SignatureProbeAnalyzer

Probe signature candidates, with optional capped PCA and bootstrap voting.

max_probe_features caps the feature count through PCA before lifting. Probe counts/epochs/rate control training work; k controls neighborhoods. bivector_parameter_energy_threshold thresholds normalized bivector parameter energies.

analyze(data)

Probe nonempty raw [N,D] observations, detached from the caller's graph.

analyze_bootstrap(data, *, n_bootstrap=10, max_samples=500, seed=42)

Return a modal representative and bootstrap signature counts.

The returned result is the first replicate with the modal tuple, not a refit on the original data. The seed controls resampling indices; probe training still uses PyTorch's RNG. Ties favor the first seen tuple.

neighborhood

Exploratory coefficient-space neighborhoods and coordinate-lift comparisons.

NeighborhoodBivectorAnalyzer

Explore normalized vector wedges over Euclidean coefficient neighbors.

Accepts canonical [N, dim] tensors, normalized to the algebra's dtype/device. Wedges use their grade-1 parts; neighbor selection uses all supplied coefficients, including probe outputs. Alignment and dissimilarity are research scores in coefficient space.

neighbor_bivector_alignment(mv)

Return mean within-neighborhood absolute coefficient dot product of normalized wedges.

mean_neighbor_bivectors(mv)

Return [N, dim] mean normalized neighbor wedges at each point.

Wedges use grade-1 parts; neighbor selection uses all coefficients. Oppositely oriented wedges may cancel in the mean.

neighbor_bivector_dissimilarity(mv)

Compare each neighborhood with its first coefficient-space neighbor.

Returns one minus the mean cross-set absolute coefficient dot product of their normalized bivectors. The first-neighbor choice is part of this score.

per_point_bivector_alignment(mv)

Return per-point within-neighborhood normalized-bivector alignment.

Returns a scalar neighbor_bivector_alignment value per data point, measuring how well-aligned that point's normalized neighbor bivectors are.

Parameters:

Name Type Description Default
mv Tensor

[N, dim] multivectors.

required

Returns:

Type Description
Tensor

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

compare_coordinate_lifts(data, p, q, *, k=8, appended_value=1.0)

Compare coordinate lifts preserving the original positive/negative directions.

Input has shape [N, p+q]; its floating dtype and device are preserved. Both extensions add appended_value. The positive-count extension inserts it after the p positive coordinates and uses Cl(p+1,q); the negative-count extension appends it and uses Cl(p,q+1). Returns signatures and neighborhood scores for the three embeddings. There is no threshold verdict or automatic preferred representation.

Utilities

mps

MPS-specific operator fallbacks.

safe_linalg_solve(A, B)

Solve on CPU when the input lives on MPS.