Skip to main content

TensorTrail

Numerical drift detection and tensor comparison for machine-learning inference.

TensorTrail compares a reference tensor with a candidate tensor and returns a structured, reproducible diagnostic report: fused MAE/MSE/RMSE, relative error, cosine similarity, tolerance outcomes, tensor statistics, non-finite counts, and explicit conversion provenance. The default engine is a Rust extension built with PyO3 and Rayon. A NumPy implementation is included as a readable reference backend and parity oracle.

Status: 0.2.0 alpha (source). The 0.1.0 numerical core, Python API, comparison reports, tests, and benchmarks are implemented and verified. 0.2.0 adds execution-aware inference validation on top of that engine: sessions, checkpoint metadata, deterministic alignment, validation policies, explicit missing/incompatible outcomes, and local checksummed artifacts. GPU execution, automatic activation capture, and explicit SIMD kernels are not implemented; see Scope and non-goals. 0.2.0 is not yet tagged or published; see Installation.

Why TensorTrail

  • One traversal for all binary metrics. MAE, MSE, RMSE, relative error, cosine terms, tolerance mismatches, and non-finite counts are accumulated together. Statistics can be folded into the same pass.
  • Deterministic parallel reductions. Fixed chunk boundaries and ordered merges make results independent of Rayon worker count and scheduling for a fixed chunk size. Results do not silently depend on how many cores are busy.
  • Explicit numerical policy. Empty tensors, NaN/±Inf, zero denominators, dtype conversion, non-contiguous layouts, and overflow are defined and recorded rather than hidden behind a scalar.
  • No silent backend fallback. A missing native extension raises an actionable error. backend="numpy" is an explicit choice.
  • Reports you can keep. Stable JSON schema and a self-contained HTML report with inputs, conversions, metrics, counts, tolerances, and execution metadata.
  • Execution-aware validation. Group tensor checkpoints into reference and candidate inference sessions, align them deterministically, validate each pair with the same comparison engine, and persist checksummed local artifacts. Missing, shape-incompatible, dtype-rejected, and backend-failed checkpoints are explicit outcomes, never silent passes.

Installation

TensorTrail requires Python 3.11+ (3.11–3.14 tested) and NumPy. Building the native engine from source requires a Rust toolchain (1.85+) and a C/C++ build environment supported by PyO3.

git clone https://github.com/leaderofARS/tensortrail.git
cd tensortrail
python -m pip install .

For development (editable install with the native extension):

python -m pip install "maturin>=1.16,<2.0"
maturin develop --release

Optional PyTorch input support:

python -m pip install "tensortrail[torch]"

tensortrail 0.1.0 is the current PyPI release: python -m pip install tensortrail. The published wheel targets CPython 3.13 on Linux x86_64; other platforms install from source and need a Rust toolchain. The 0.2.0 source in this repository is implemented and locally verified but has not been tagged or published. Install it from a checkout with python -m pip install . (or maturin develop --release for development).

Quick start

import numpy as np
import tensortrail as tt

reference = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32)
candidate = np.array([1.0, 4.0, 2.0, 8.0], dtype=np.float32)

report = tt.compare(reference, candidate)

print(report.summary())
print(report.metrics.mae)              # 1.75
print(report.metrics.relative_error)   # RelativeErrorValue(mean=..., maximum=...)
print(report.counts.mismatches)        # 3
print(report.status)                   # "fail"

report.save("layer12.json")
report.save("layer12.html")
TensorTrail comparison: FAIL
  reference: 'reference' shape=(4,) dtype=float32 device=cpu
  candidate: 'candidate' shape=(4,) dtype=float32 device=cpu
  mae: 1.75
  mse: 5.25
  rmse: 2.2912878
  relative_error: mean=0.58333333 max=1
  cosine_similarity: 0.93073869
  max_abs_error: 4
  elements: 4 (finite pairs: 4)
  mismatches: 3 (3 finite, 0 non-finite pattern)
  tolerance: atol=1e-06 rtol=1e-05 equal_nan=True
  backend: rust threads=1 elapsed=0.002391s

Configuration

config = tt.ComparisonConfig(
    backend="rust",          # default; "numpy" is the explicit reference backend
    metrics=("mae", "rmse", "relative_error", "cosine_similarity", "statistics"),
    atol=1e-5,
    rtol=1e-4,
    equal_nan=True,
    relative_epsilon=1e-12,
    threads=8,               # None uses the global Rayon pool; 1 is sequential
    parallel_threshold=32_768,
    chunk_size=32_768,
    release_gil=True,
)

report = tt.compare(
    reference,
    candidate,
    config=config,
    reference_id="decoder.layer_12.output",
    candidate_id="decoder.layer_12.output.optimized",
)

Tolerance is evaluated per element:

|reference - candidate| <= atol + rtol * |reference|

Metrics

Metric Definition Empty/all-non-finite policy
mae mean(abs(r - c)) over finite pairs None
mse mean((r - c)^2) over finite pairs None
rmse sqrt(mse) None
relative_error abs(r - c) / max(abs(r), epsilon) None
cosine_similarity `dot(r, c) / sqrt(
statistics min, max, mean, population variance, std dev, finite/non-finite counts numeric fields None

Cosine policy: two all-zero vectors have similarity 1.0; exactly one all-zero vector has similarity 0.0. Extreme magnitudes use a scaled two-pass fallback so that 1e-300 and 1e308 inputs do not overflow or underflow the result.

Policies at a glance

  • Empty tensors: metrics are None, never a fabricated zero; status is pass when there are no mismatches.
  • NaN/±Inf: excluded from metric sums and statistics, counted by category on each side. Non-finite pattern differences (for example NaN vs 1.0, or +Inf vs -Inf) fail the comparison. Corresponding NaNs pass when equal_nan=True.
  • Shape mismatch: rejected before execution with both shapes in the error.
  • dtypes: float32 and float64 stay in their dtype when both sides match; float16 and bfloat16 are widened to float32; integers and bools become float64; mixed float32/float64 becomes float64. Complex, object, string, datetime, and extended-precision arrays are rejected. Every conversion is listed in report.reference.conversion_notes.
  • Layouts: non-contiguous, negative-stride, unaligned, and non-native-endian arrays are copied to contiguous native buffers and the conversion is recorded.
  • Overflow: accumulation is float64; a mathematically out-of-range result is Infinity, which fails tolerance checking. Underflowed squared differences can make MSE report 0.0; this is a documented floating-point limit.
  • No silent fallback: if backend="rust" and the extension is unavailable, BackendError is raised. TensorTrail never switches to NumPy implicitly.
  • No silent device copy: CUDA/MPS/meta PyTorch tensors are rejected rather than transferred and presented as a GPU comparison.

Full details: numerical methods.

PyTorch input

PyTorch is optional and is never imported at package import time.

import torch
import tensortrail as tt

reference = torch.randn(32, 768)             # CPU tensor
candidate = reference + torch.randn(32, 768) * 1e-5

report = tt.compare(reference, candidate)
assert report.reference.source == "torch"

CPU tensors are converted explicitly; requires_grad tensors are detached and the note is recorded. Accelerator and quantized tensors are rejected. TensorTrail does not claim GPU support and does not silently move data to the host.

Execution validation

tt.compare() compares one tensor pair. tt.validate() compares two complete inference executions checkpoint by checkpoint, using tt.compare() underneath for every matched pair.

import numpy as np
import tensortrail as tt

reference = tt.ExecutionSession.create(
    model_id="classifier",
    model_version="1.0",
    framework="pytorch",
    precision="float32",
    device_type="cpu",
)
candidate = tt.ExecutionSession.create(
    model_id="classifier",
    model_version="1.1",
    framework="pytorch",
    precision="float32",
    device_type="cpu",
)

reference.add_checkpoint(
    name="encoder.output",
    tensor=np.array([1.0, 2.0, 3.0], dtype=np.float32),
    stage_name="encoder",
)
candidate.add_checkpoint(
    name="encoder.output",
    tensor=np.array([1.0, 2.0, 3.0001], dtype=np.float32),
    stage_name="encoder",
)
reference.finalize()
candidate.finalize()

result = tt.validate(
    reference,
    candidate,
    policy=tt.ValidationPolicy(atol=1e-3, rtol=1e-3),
)
print(result.status)   # "passed"
print(result.summary)

Rules:

  • A session moves from created to recording on its first checkpoint and then to completed or failed. Validation requires two completed sessions.
  • Checkpoints are matched by an explicit mapping first, then by unique checkpoint name. List position is never used as an alignment rule.
  • Missing required checkpoints and shape mismatches produce incomplete by default. fail_on_missing_checkpoints and fail_on_shape_mismatch turn those conditions into failed.
  • A dtype change is reported and compared, unless fail_on_dtype_change=True makes it a policy failure without running the comparison.
  • Every matched pair is compared by tt.compare(). Validation does not reimplement metric or tolerance logic.
  • aggregation_strategy="all" is the default. "any" passes when at least one matched checkpoint passes, but required incomplete or policy-failed conditions still take precedence.

Persistence:

storage = tt.FilesystemStorage("tensortrail_artifacts")
storage.save_execution(reference)
storage.save_execution(candidate)
storage.save_validation(result)

loaded_reference = storage.load_execution(reference.execution_id)
reloaded_result = storage.load_validation(result.validation_id)

Artifacts use versioned JSON manifests, SHA-256 checksums, atomic directory publication, validated path segments, and np.load(..., allow_pickle=False). PyTorch payloads can be validated in memory, but must be converted explicitly before persistence; TensorTrail does not transfer or convert them implicitly. See the full execution model.

Reports

report.metrics, report.statistics, report.counts, report.reference, report.candidate, report.tolerances, and report.metadata are typed, immutable dataclasses. report.save(path) writes JSON or HTML based on the extension; format= overrides it. report.to_dict() and report.to_json() expose the same schema (schema_version: "1.0"). Strict JSON is emitted: any non-finite float that survives overflow is encoded as "NaN", "Infinity", or "-Infinity".

Validation results are separate JSON artifacts with artifact_type: "validation" and schema version "1.0". They record both execution metadata objects, the policy, the full alignment, per-checkpoint outcomes and comparison reports, derived counts, the highest observed deviation, and a human-readable summary. ValidationResult.save(path), load(path), to_dict(), to_json(), and from_dict() round-trip the document; the same non-finite sentinels apply.

Performance

Measured on the development machine (Windows 11, Intel Core i7-12700H class, 14 physical/20 logical cores, Python 3.13.5, NumPy 2.1.3, release build). These are end-to-end tt.compare medians over 7 repetitions; they are not universal claims. Full methodology and raw results are in docs/benchmarking.md.

Elements dtype Rust backend NumPy backend Ratio
100,000 float64 0.75 ms 5.58 ms 7.4×
1,000,000 float64 1.83 ms 80.3 ms 43.9×
5,000,000 float64 20.9 ms 409.7 ms 19.6×
1,000,000 float32 1.69 ms 91.5 ms 54.3×

For equivalent work, the fused native kernel measured about 1.4–1.5× faster than separate kernel calls for the binary metric set, and about 1.7–2.0× faster with statistics; it also scales with Rayon workers. Absolute parallel timings vary under sustained load; see the benchmark document for the full results and caveats. No hand-written SIMD intrinsics are present. The native build reports simd: "scalar"; explicit SIMD remains deferred.

Scope and non-goals

Implemented and verified:

  • Rust numerical engine with deterministic Rayon reductions and a sequential path.
  • NumPy reference backend and randomized cross-backend parity tests.
  • Python API, typed reports, JSON/HTML serialization, and atomic saves.
  • Optional CPU PyTorch tensors with explicit conversion and rejection of accelerator/quantized/complex layouts.
  • Execution sessions and checkpoint metadata with an explicit lifecycle.
  • Deterministic checkpoint alignment with explicit mappings and structured missing-checkpoint entries.
  • Execution validation with tt.validate(), all/any aggregation, explicit skip outcomes, and JSON reload.
  • Local execution/validation artifacts with versioned manifests, SHA-256 checksums, safe path handling, atomic publication, and pickle-free loading.
  • Unit, parity, determinism, layout, reporting, import-isolation, execution, validation, integration, and optional PyTorch tests.

Not implemented (not claimed):

  • GPU/CUDA/MPS-native metrics, multi-device comparison, or distributed runs.
  • Automatic activation capture, framework hooks, graph tracing, and model patching. Capture is manual in 0.2.0.
  • Cloud or object storage for execution artifacts.
  • Explicit AVX/NEON/SVE kernels or runtime CPU dispatch.
  • Complex-valued tensors, quantized dequantization, sparse tensors, or masked arrays.

Development

python -m pip install -e ".[dev]"
maturin develop --release

cargo test --manifest-path native/tensortrail-core/Cargo.toml --release --all-features
cargo clippy --manifest-path native/tensortrail-core/Cargo.toml --all-targets --all-features -- -D warnings
cargo fmt --manifest-path native/tensortrail-core/Cargo.toml --all -- --check

ruff check python tests
mypy
pytest

See docs/development.md for platform notes, CI, and release steps. Contribution guidelines are in CONTRIBUTING.md, and release history is in CHANGELOG.md. The execution-validation contract is in docs/execution_model.md. The verified status of this release is documented in the engineering report.

License

Apache-2.0. See LICENSE.

Metadata

Release files for tensortrail 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tensortrail 0.2.0
File Size Uploaded Provenance Actions
tensortrail-0.2.0.tar.gz 164.6 kB With provenance Details for tensortrail-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tensortrail 0.2.0
File Interpreter ABI Platform Actions
tensortrail-0.2.0-cp313-cp313-manylinux_2_34_x86_64.whl CPython 3.13 CPython 3.13 Linux glibc 2.34+ x86-64 Details for tensortrail-0.2.0-cp313-cp313-manylinux_2_34_x86_64.whl

Total release size: 563.2 kB

Release files / tensortrail-0.2.0.tar.gz

Download URL tensortrail-0.2.0.tar.gz
Size 164.6 kB
Tags Source
SHA-256 checksum
How to use checksums
c79bd2aad132dd4af5f66374b8e463cfba9b35044194983d853b3f7ecce5b069
BLAKE2b-256 checksum
How to use checksums
940d5fcc415ea8549ccacbe81607f05b993c5312b47f5bbdb779b4f977b3856e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Release files / tensortrail-0.2.0-cp313-cp313-manylinux_2_34_x86_64.whl

Download URL tensortrail-0.2.0-cp313-cp313-manylinux_2_34_x86_64.whl
Size 398.5 kB
Tags CPython 3.13 Linux glibc 2.34+ x86-64
SHA-256 checksum
How to use checksums
c7efc69646fa7bae234159e438e173d42bbbb21169729bc7c6e92aa208c17c98
BLAKE2b-256 checksum
How to use checksums
11d185de7d31b602504b2fa3bf9aebcad4274ad0e9eb3056031bb168160f4cbe
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Security for tensortrail 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for tensortrail-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page