FrankenNumPy

Docs/Architecture

How It Works: Per-Crate Deep Dive

On this page 10 sections

Dtype System (fnp-dtype)

The type system is the foundation everything else builds on. 18 dtype variants cover the full NumPy type hierarchy:

Bool  I8  I16  I32  I64  U8  U16  U32  U64
F16  F32  F64  Complex64  Complex128
Str  DateTime64  TimeDelta64  Structured

fnp-dtype defines a type-safe ArrayStorage enum with native Rust containers (I64(Vec<i64>), Complex128(Vec<(f64, f64)>), F16(Vec<half::f16>), typed StructuredField / StructuredStorage). The engine's UFuncArray in fnp-ufunc does not store that enum: it holds values: Vec<f64> plus an IntegerSidecar that keeps the exact i64/u64 bits whenever a value exceeds 2^53, and converts through ArrayStorage only at its from_storage / to_storage boundary. Ten integer binary ops (add, subtract, multiply, floor-divide, remainder, and/or/xor, both shifts) recompute exactly on the sidecar; other arithmetic on values above 2^53 rounds through f64 (see Limitations). The fnp_python fast paths do not go through UFuncArray at all: they read numpy buffers as typed zero-copy slices (i64, f32, f16, ...) and compute in the native width.

Promotion table. promote(lhs, rhs) is a deterministic const fn. All 324 dtype pairs are explicitly handled with no catch-all fallback; adding a new dtype variant causes a compile error until promotion rules are added for it. Selected rules:

LHS RHS Result Why
Bool anything RHS Bool is identity for promotion
U8 I8 I16 Smallest signed type covering 0..255 and -128..127
U16 I16 I32 Smallest signed type covering both ranges
U64 any signed F64 No NumPy integer type holds both U64::MAX and negative values
F16 I8 / U8 F16 NumPy preserves float16 for 8-bit ints
F16 I16 / U16 F32 16-bit integers exceed float16 mantissa
F32 I32 / I64 F64 float32 can't represent all 32/64-bit ints
Complex64 I32 Complex128 Mirrors the F32+I32 → F64 widening rule

The U64 + signed → F64 promotion is the most counterintuitive rule in the table, but it is exactly what NumPy does: there simply isn't a 128-bit integer type in NumPy's type system.

Cast policy. can_cast(src, dst, casting) supports all five NumPy casting modes: "no", "equiv", "safe", "same_kind", and "unsafe". A same_kind cast cannot silently demote signed to unsigned.

IntegerSidecar (defined in fnp-ufunc, not fnp-dtype; it travels with UFuncArray's storage rather than with the dtype itself). For arrays whose UFuncArray storage is Vec<f64> but whose dtype is i64/u64, a sidecar preserves exact integer values through storage round-trips so values above 2^53 survive from_storage / to_storage. Arithmetic on such values still uses f64 approximation (see Limitations).

Promotion table at a glance. All 324 (dtype × dtype) pairs are individually enumerated. The two-dimensional table is roughly symmetric and follows NumPy's "smallest type that holds both ranges, prefer floats over signed-unsigned widening that would lose precision" rule:

        Bool   I8    I16   I32   I64   U8    U16   U32   U64   F16   F32   F64   C64   C128
Bool    Bool   I8    I16   I32   I64   U8    U16   U32   U64   F16   F32   F64   C64   C128
I8       I8    I8    I16   I32   I64   I16   I32   I64   F64   F16   F32   F64   C64   C128
I16     I16   I16    I16   I32   I64   I16   I32   I64   F64   F32   F32   F64   C64   C128
I32     I32   I32    I32   I32   I64   I32   I32   I64   F64   F64   F64   F64  C128   C128
I64     I64   I64    I64   I64   I64   I64   I64   I64   F64   F64   F64   F64  C128   C128
U8       U8   I16    I16   I32   I64   U8    U16   U32   U64   F16   F32   F64   C64   C128
U16     U16   I32    I32   I32   I64   U16   U16   U32   U64   F32   F32   F64   C64   C128
U32     U32   I64    I64   I64   I64   U32   U32   U32   U64   F64   F64   F64  C128   C128
U64     U64   F64    F64   F64   F64   U64   U64   U64   U64   F64   F64   F64  C128   C128
F16     F16   F16    F32   F64   F64   F16   F32   F64   F64   F16   F32   F64   C64   C128
F32     F32   F32    F32   F64   F64   F32   F32   F64   F64   F32   F32   F64   C64   C128
F64     F64   F64    F64   F64   F64   F64   F64   F64   F64   F64   F64   F64  C128   C128
C64     C64   C64    C64  C128  C128   C64   C64  C128  C128   C64   C64  C128   C64   C128
C128   C128  C128   C128  C128  C128  C128  C128  C128  C128  C128  C128  C128  C128   C128

Read across the row for the left-hand operand and down to the column for the right-hand operand. The table is symmetric (promote(a, b) == promote(b, a)). Key patterns visible in the matrix:

  • Signed × unsigned cross. The result is the smallest signed type whose range covers both operands, so U8 × I16 = I16, but U8 × I8 = I16 (no single 8-bit type holds both -128..127 and 0..255).
  • U64 × any signed = F64. No NumPy integer type holds both U64::MAX and negative values, so the result widens to float.
  • F32 × {I32, I64, U32, U64} = F64. F32's 24-bit mantissa cannot exactly represent all 32/64-bit integers; F64 has 53 bits, which covers everything up to ±2^53.
  • F16 × {I8, U8} = F16. F16's 11-bit mantissa is enough for 8-bit ints; F16 × 16-bit ints widens to F32; F16 × 32/64-bit ints jumps to F64.
  • Complex × small int = Complex64, Complex × large int = Complex128. The same mantissa-precision logic as the float rows.

(Str, DateTime64, TimeDelta64, and Structured follow same-family-only rules and are not shown in this 14×14 numeric sub-table.) The full enumeration is in crates/fnp-dtype/src/lib.rs; if a new variant is added to enum DType, the compiler refuses to build until the new row and column are filled in. There is no catch-all arm.

Stride Calculus Engine (fnp-ndarray)

SCE owns the shape transformation rules of the Rust engine: UFuncArray and the crates built on it (fnp-ufunc, fnp-linalg, fnp-random) use it. fnp-dtype, fnp-iter, fnp-io, fnp-random-core and fnp-runtime do not depend on it, and the Python kernel layer in fnp-python reads NumPy's own shape/strides rather than calling SCE (see Architecture).

  1. Shape → strides. Given a shape [d0, d1, ..., dn] and MemoryOrder::C or F, compute the contiguous strides. C-order: rightmost dimension has stride = item_size, each dimension to the left multiplies by the next dimension's size. F-order: leftmost dimension has stride = item_size.
  2. Broadcast legality. Two shapes are broadcast-compatible when, aligned from the right, each pair of dimensions is either equal or one is 1. The output shape takes the maximum at each position. Mixed-rank inputs are left-padded with 1s. broadcast_shapes(...) reduces over a slice of shapes deterministically.
  3. Reshape with -1 inference. At most one dimension can be -1, meaning "infer from the total element count and the other dimensions." fix_unknown_dimension divides the total element count by the product of known dimensions and validates that the result is exact.
  4. View safety. as_strided() and sliding_window_view() compute the required byte span from the minimum to maximum reachable offset and verify it fits within the base allocation; out-of-bounds requests are rejected instead of zero-filled. Negative strides (reverse slicing) are fully supported across multiple axes.
  5. Broadcast strides. When a dimension has size 1 but the broadcast output has size > 1, the stride for that dimension is set to 0. This creates a virtual repeat without copying data.

Transfer Semantics and Iteration (fnp-iter)

The iterator crate models NumPy's internal transfer-loop selector, the nditer state machine, and a parity bridge that lets us step through a real numpy nditer alongside ours.

Transfer classes:

Class When selected Cost
Contiguous Both src/dst have unit strides and matching alignment Fastest (memcpy-like)
Strided Arbitrary strides, lossless cast Medium (per-element stride arithmetic)
StridedCast Arbitrary strides, lossy cast Slowest (per-element cast + stride)

Overlap actions:

Action When Why
NoCopy Source and destination don't overlap No precaution needed
ForwardCopy Overlap, forward iteration safe Dst starts after src start
BackwardCopy Overlap, forward would corrupt Must iterate in reverse

Stateful Nditer. First-class state machine on top of NditerPlan: iterindex, multi_index, reset, seek_by_index, seek_by_multi_index, external_loop chunk iteration, plus a NumPy-backed nditer_python* bridge for parity checks. fnp-python re-exposes the iterator as the PyO3 class PyNditer.

FlatIter indexing supports four modes: Single(i), Slice { start, stop, step }, Fancy(Vec<usize>), and BoolMask(Vec<bool>). The count_true_mask optimization processes boolean masks in 8-element chunks for vectorizable counting.

Ufunc Dispatch (fnp-ufunc)

The largest engine crate (~85k lines in src/lib.rs and src/sort_small.rs) and the heart of the array engine.

35 binary operations: Add, Sub, Mul, Div, Power, FloorDivide, Remainder, Fmod, Minimum, Maximum, Fmax, Fmin, Copysign, Heaviside, Nextafter, Arctan2, Hypot, Logaddexp, Logaddexp2, Ldexp, FloatPower, BitwiseAnd, BitwiseOr, BitwiseXor, LeftShift, RightShift, LogicalAnd, LogicalOr, LogicalXor, and the six comparison operators.

43 unary operations: Abs, Negative, Positive, Sign, Sqrt, Square, Exp, Log, Log2, Log10, all trig and inverse trig, all hyperbolic and inverse hyperbolic, Cbrt, Expm1, Log1p, Degrees, Radians, Floor, Ceil, Round, Rint, Trunc, Reciprocal, Spacing, Signbit, Isnan, Isinf, Isfinite, LogicalNot, Invert, and more.

Every binary operation goes through the same execution skeleton: compute the output shape via SCE's broadcast_shape, map output indices to source indices using broadcast strides (0-stride for size-1 dimensions), and apply the operation elementwise. The output-to-source index map uses an incremental odometer instead of a full unravel/remap per element.

NaN semantics are explicit. A systematic correctness sweep eliminated implicit "NaN is just partial_cmp returns None" behaviors:

  • reduce_min, reduce_max propagate NaN (custom nan_min / nan_max, not f64::min / f64::max)
  • cummin, cummax propagate NaN through the accumulator
  • sort, argsort sort NaN to the end via nan_last_cmp (not partial_cmp().unwrap_or(Equal))
  • median, percentile, quantile early-return NaN before sorting
  • ptp propagates NaN in both UFuncArray and MaskedArray
  • Mode, heapsort, set operations all propagate NaN consistently

Float error state. A thread-local FloatErrorState tracks divide-by-zero, overflow, underflow, and invalid-operation events. Each mode (Ignore, Warn, Raise, Call, Print, Log) is configurable per category. seterr(), geterr(), and errstate() match NumPy's API; errstate() returns an RAII guard that restores prior state on drop.

Generalized ufuncs. GufuncSignature parses signatures like "(n?,k),(k,m?)->(n?,m?)" for sub-array operations (matmul, etc.). The parser normalizes signatures, extracts core dimensions, validates operand shapes, and applies broadcasting over the remaining "loop" dimensions.

einsum. Three entry points: einsum() for direct evaluation, einsum_path() for contraction-path optimization, and einsum_optimized() for greedy or brute-force strategy selection.

Strategy Method Best for
"greedy" At each step, contract the pair with smallest intermediate result Default, fast for any operand count
"optimal" Dynamic programming over all contraction orderings ≤ 10 operands
"auto" Selects greedy Convenience alias

Linear Algebra (fnp-linalg)

~100 public functions organized into four tiers:

2×2 fast paths. solve_2x2, det_2x2, slogdet_2x2, inv_2x2, qr_2x2, svd_2x2, eigh_2x2, cholesky_2x2 bypass the general NxN overhead for the smallest matrix size.

NxN general algorithms.

  • QR: Householder reflections with qr_nxn (reduced) and qr_mxn (rectangular)
  • SVD: Golub–Kahan bidiagonalization + implicit shifted QR; svd_full(full_matrices) for reduced or full
  • Eigenvalues: Hessenberg reduction + implicit shifted QR iteration; symmetric path uses tridiagonal reduction + implicit QL shifts (eigvalsh_nxn, eigh_nxn)
  • LU: Partial pivoting with lu_factor_nxn and lu_solve
  • Cholesky: Column-wise lower-triangular factorization
  • Least squares: lstsq_svd and lstsq_nxn; returns the full NumPy 4-tuple (x, residuals, rank, singular_values)

Spectral methods. expm_nxn (matrix exponential via Padé approximation), sqrtm_nxn, logm_nxn, funm_nxn (general matrix function via Schur decomposition), polar_nxn, schur_nxn.

Batch operations. 14 batched functions (batch_inv, batch_det, batch_solve, batch_svd, batch_qr, batch_cholesky, batch_eig, batch_eigvalsh, batch_eigh, batch_slogdet, batch_svd_full, batch_matrix_norm, batch_matrix_rank, batch_trace) operate on stacked matrices with leading batch dimensions, matching NumPy's broadcasting for linear algebra.

Complex number support. 10+ functions for complex-valued matrices: complex_solve_nxn, complex_det_nxn, complex_inv_nxn, complex_cholesky_nxn, complex_qr_mxn, complex_matmul, complex_matvec, complex_conjugate_transpose, complex_matrix_norm_frobenius, complex_trace_nxn.

Eigenvalue sort order is ascending to match NumPy. Singularity checks use exact zero (not epsilon thresholds) where NumPy does. Non-finite inputs propagate cleanly through cond_p, 2D cross_product, and rectangular NxN norms.

Random Number Generation (fnp-random)

The RNG crate achieves bit-exact parity with NumPy by porting every algorithm from NumPy's C source code. fnp-random keeps a deliberately small dependency graph: the required, dependency-free fnp-random-core (its one PCG64DXSM implementation), plus intra-workspace fnp-ndarray, getrandom for NumPy-compatible no-seed OS entropy, and rayon for data-parallel jump-ahead fills — those three optional and default-on, and default-features = false strips all of them for consumers that want only the generator + SeedSequence core.

5 production bit generators, enumerated under pub enum BitGeneratorKind:

Generator State Use
PCG64DXSM 128-bit + 128-bit increment, DXSM output Default; bit-exact NumPy parity reference
PCG64 128-bit state, classic PCG output Compatible with numpy.random.Generator(PCG64(seed))
MT19937 624-word state, Matsumoto–Nishimura twist Legacy RandomState compatibility
Philox 256-bit key + 256-bit counter, 4×64 rounds Counter-based parallel streaming
SFC64 Small Fast Counting (256-bit state) Lightweight high-throughput generator

An internal DeterministicRng (SplitMix64-based) is used in tests only.

SeedSequence. Hierarchical seeding with spawn / generate_state contracts. spawn(n) creates child SeedSequences by incorporating a monotonic spawn counter into the entropy pool; generate_state(words) cycles through the pool with hash transformations to produce initialization vectors. This exactly matches NumPy's numpy.random.SeedSequence. A SeedSequenceSnapshot allows snapshot/restore for lineage tracking.

Bounded integers. NumPy's random_bounded_uint64() dispatch is reproduced exactly:

  • Range fits in 32 bits → Lemire's method via buffered next_uint32() (each u64 is split into two u32s, low first)
  • Range exceeds 32 bits → Lemire's method with 128-bit multiplication
  • Range = 0 → return 0; range = u32::MAX → raw next_uint32(); range = u64::MAX → raw next_u64()

Shuffle / permutation. random_interval() (masked bit rejection, not Lemire), matching NumPy's _shuffle_raw code path: for each index from n-1 down to 1, generate a uniform integer in [0, i] by masking to the smallest bit-width covering i and rejecting values above i.

Algorithm correspondence:

Algorithm NumPy source Our implementation
Bounded integers random_bounded_uint64() Lemire 32/64-bit dispatch + buffered next_uint32
Binomial random_binomial_btpe() + _inversion() BTPE for large n·p, inversion for small
Hypergeometric hypergeometric_hrua() + _sample() HRUA (Stadlober 1989) + direct via random_interval
Poisson random_poisson_ptrs() + _mult() PTRS (Hörmann 1993) for λ ≥ 10, multiplicative for small
Gamma random_standard_gamma() Marsaglia–Tsang + rejection for shape < 1 + exponential for shape = 1
Zipf random_zipf() Exact rejection with Umin clamping
Shuffle _shuffle_raw() Fisher–Yates via random_interval() masked rejection
Normal rk_gauss / Ziggurat Ziggurat sampler (same as NumPy)

State serialization. Full state capture and restoration for reproducibility:

let payload  = generator.to_pickle_payload();
let restored = Generator::from_pickle_payload(payload)?;
// `restored` produces an identical sequence from this point forward.

GeneratorPicklePayload captures the bit-generator state (seed, counter, algorithm tag, schema version) and optionally the SeedSequence snapshot for spawn-lineage tracking. The RandomState wrapper provides legacy numpy.random.RandomState API parity.

Seed material accepts None (fresh OS entropy), U64(seed), U32Words(vec), SeedSequence, or direct State { seed, counter } for exact restoration. default_rng(12345), default_rng([1, 2, 3]), and default_rng(SeedSequence(42)) all work bit-exactly.

SeedMaterial::None and no-seed default_rng() source fresh OS entropy via getrandom, matching NumPy's non-reproducible default constructor behavior. Use explicit seeds when you need bit-for-bit reproducibility.

I/O Format Handling (fnp-io)

NPY format. Complete implementation of NumPy's .npy binary format:

  • Magic prefix \x93NUMPY + version (1.0 or 2.0) + header length + Python dict header + padding to 16-byte alignment + raw data payload
  • 24 supported dtype descriptors including little/big-endian variants for all integer and float types, complex types, fixed-width byte strings, Unicode strings, object type
  • Header parsing validates all three required fields (descr, fortran_order, shape) and rejects unknown keys
  • Hardened with MAX_HEADER_BYTES = 65,536 to prevent allocation bombs

NPZ format. ZIP-based container for multiple arrays:

  • savez (stored) and savez_compressed (DEFLATE) via the flate2 crate
  • MAX_ARCHIVE_MEMBERS = 4,096 and MAX_ARCHIVE_UNCOMPRESSED_BYTES = 2 GiB limits prevent archive bombs
  • Each member is a complete .npy file inside the ZIP

Text I/O. loadtxt, savetxt, genfromtxt, plus loadtxt_usecols / loadtxt_unpack / genfromtxt_full handle delimiter-separated text files with configurable dtypes, missing-value policies, and column selection. MAX_TEXT_ELEMENTS = 16,777,216 bounds parser memory.

Binary I/O. fromfile, tofile, fromstring, tobytes, tostring, plus typed variants fromfile_text / tofile_text and fromfile_complex / tofile_complex.

Structured dtype I/O. parse_structured_descr, fromfile_structured, tofile_structured, save_structured, load_structured.

Memmap. memmap(path, mode), memmap_npy(path, mode), open_memmap with bounded retry on validation failures.

Pickle policy. Object dtype arrays require allow_pickle=true, matching NumPy's security posture against arbitrary code execution from untrusted .npy files.

Dual-Mode Runtime (fnp-runtime)

The runtime decides each guarded call by the runtime mode matrix below and records the decision, with a posterior-probability audit, in an evidence ledger. Three actions:

Action When
Allow KnownCompatible input in Strict mode, or low-risk KnownCompatible in Hardened mode
FullValidate Hardened mode with elevated risk, or malformed metadata (NaN / out-of-range inputs)
FailClosed Unknown semantics or KnownIncompatible in any mode

How the action is chosen. decide_compatibility applies the runtime mode matrix: KnownIncompatible and Unknown fail closed in both modes; a KnownCompatible call is allowed in Strict mode, and in Hardened mode it is allowed below the risk threshold (0.5 at the Python surface) and sent to full_validate at or above it, or when the risk or threshold is malformed. At the Python surface each guard supplies a fixed risk score (1.0 where its check found a violation - a non-finite linalg operand, an array over the admission cap, a spawn over budget, a load outside the fnp-io bounds - and a low score at the record-only sites), and full_validate or fail_closed makes the guarded call raise.

Posterior audit. Next to each action the engine computes, and the ledger records, a posterior incompatibility probability - class-specific prior odds (1% incompatibility for KnownCompatible, 99% for KnownIncompatible, 50% for Unknown) updated by the risk score's log-likelihood ratio against the threshold - and the expected loss of each action under this loss model; fnp_python.get_runtime_decisions() exports them (posterior_incompatible, expected_loss_*, selected_expected_loss, evidence_terms). They do not choose the action: under these constants the argmin would allow a Hardened known-compatible call at risk 0.6 that the matrix sends to full_validate.

allow_if_compatible:              0.0   (correct accept: no cost)
allow_if_incompatible:          100.0   (silent corruption: catastrophic)
full_validate_if_compatible:      4.0   (unnecessary work: small cost)
full_validate_if_incompatible:    2.0   (caught by validation: acceptable)
fail_closed_if_compatible:      125.0   (false rejection: high cost)
fail_closed_if_incompatible:      1.0   (correct rejection: minimal cost)

Every decision is logged to an EvidenceLedger with timestamp, mode, class, evidence terms, and action. Override requests are tracked separately in OverrideAuditEvent records with audit references.

Runtime mode matrix:

Input class Strict mode Hardened mode
Known compatible + low risk allow allow
Known compatible + high risk allow full_validate
Unknown semantics fail_closed fail_closed
Known incompatible semantics fail_closed fail_closed

Conformance Infrastructure (fnp-conformance)

The conformance crate is the quality backbone. 48 binaries under crates/fnp-conformance/src/bin/ drive the layered system. About 20 of the 48 are the active workflow tools (oracle capture, differential runners, drift matrices, ledger gates, API coverage gate, etc.) listed below; the remaining ~27 are one-shot phase2c evidence/optimization-report generators (generate_packet001_final_evidence_pack through generate_packet009_*, plus a few historical regenerators) that ran during the FNP-P2C-001..009 packet creation and produced checked-in artifacts under artifacts/phase2c/.

  1. Differential harness. Captures NumPy's output for a fixture corpus (capture_numpy_oracle), then runs the same inputs through FrankenNumPy (run_ufunc_differential) and compares shapes, dtypes, and values with configurable tolerance. Covers ufunc, linalg, FFT, polynomial, string, masked-array, datetime, RNG, and I/O operations.
  2. Metamorphic testing. Verifies algebraic identities that must hold regardless of input: a + b = b + a, a * 1 = a, sum(a) = sum(sort(a)), FFT round-trips, etc. (13+ identities).
  3. Adversarial fuzzing and seeds. Tests behavior on hostile inputs: NaN-filled arrays, extreme shapes, denormalized floats, integer overflow, malformed NPY headers, corrupt ZIP EOCDs. 42 fuzz targets across 8 fuzz crates with 561 curated seed corpus files; see docs/FUZZING.md.
  4. Witness stability. Hard-coded expected values for every RNG distribution ensure code changes don't silently alter output sequences. When an algorithm is intentionally changed, witness values are regenerated from the new implementation.
  5. Diagnostic oracle. A structured oracle for warnings, exceptions, and printed messages: run_diagnostic_oracle, run_oracle_drift_matrix (cross-version drift), run_io_diagnostics, plus the divergence-ledger checker (run_divergence_ledger --fail-on-missing). Cross-version drift detection uses a Rust-side NumpyVersion parser (in crates/fnp-conformance/tests/numpy_reference_ops.rs) that reads numpy.__version__ at runtime, parses major/minor/patch (handling dev-version suffixes like 2.5.0.dev0+git20260503), and gates per-version conditional assertions accordingly.
  6. API coverage gate. run_fnp_python_api_coverage --fail-on-missing reports exports=633 covered=599 missing=0 against the full numpy.__all__ surface plus internal helpers.
  7. RaptorQ durability. generate_raptorq_sidecars, run_raptorq_gate, run_raptorq_stress_gate. See the RaptorQ section below.
  8. Performance baseline. generate_benchmark_baseline, run_performance_budget_gate, run_cross_engine_benchmark. See the Performance section.
  9. Security gate. run_security_gate, run_test_contract_gate, run_workflow_scenario_gate. See the Threat Model section.

Python Bindings (fnp-python)

The fnp_python PyO3 extension is the parity-oracle surface. Its native routes run mostly in fnp-python's own kernels over NumPy buffers (some call into fnp-linalg and fnp-ufunc), and it falls back to numpy wherever no native route applies. Of the 499 numpy.__all__ names, 161 are NumPy's own objects and 338 are fnp objects (live probe, 2026-10-08).

Three architectural moves drive the 100% surface coverage:

  1. Native routes with numpy fallback. Performance-relevant wrappers (sum, mean, var, sort, searchsorted, ...) run a native kernel for the dtypes, layouts and sizes it covers and call numpy for the rest, size included (a float64 flat sort is native only from 2^20 elements). fft.* except fftfreq, the 2-D linalg decompositions and solvers, and every polynomial function except the six series evaluators (polyval, chebval, legval, hermval, hermeval, lagval) and the six least-squares fits (polyfit, chebfit, …, whose solve is numpy's lstsq) call numpy.
  2. Re-export-where-safe. Submodules whose semantics are pure numpy state (numpy.rec, numpy.emath, numpy.matrixlib, numpy.typing, numpy.ctypeslib, numpy.core, numpy.f2py) and class instances (mgrid, ogrid, s_, True_, …) are re-exported via m.add(name, &numpy.getattr(name)). This keeps fnp_python identity-equal to numpy on those surfaces with zero maintenance and full upstream parity (including version-gated and deprecation behaviors). strings, char, ma, testing, exceptions, dtypes, lib, linalg, fft, random and polynomial are overlays instead: fnp modules that carry numpy's attributes and replace selected ones with fnp functions (exceptions and dtypes hold only numpy's own objects, so exception identity is preserved; polynomial's six family modules are numpy's namespaces with the series evaluator and the least-squares fit replaced, and its classes and polyutils are numpy's).
  3. Structural lock-in. fnp_python_covers_full_numpy_all in crates/fnp-python/tests/conformance_remaining_top_level_attrs.rs iterates numpy.__all__ at run time against the live numpy on the build host and fails CI if any name regresses. The guarantee holds as numpy evolves: new __all__ entries fail the test until explicitly added.

11 PyO3 classes are registered (Nditer, NditerStep, FromPyFunc, SeedSequence, Generator, RandomState, MT19937, PCG64, PCG64DXSM, Philox, SFC64). r_ and c_ are fnp singleton instances; mgrid and ogrid are NumPy's own objects. Module-level attributes include __version__, __numpy_version__, pi, e, euler_gamma, inf, nan, little_endian, the 52 dtype scalars, and all the wired submodules.

Python attribute resolution model

When Python code accesses fnp_python.some_attr or fnp_python.submodule.some_func(...), lookup follows a deterministic three-tier model. The tier picked for each name is fixed at module-init time and stable across calls:

Tier Mechanism Used for Example
1. fnp function A #[pyfunction] exposed through m.add_function(...) that runs a native kernel for the dtypes, layouts and sizes it covers and calls numpy for everything else; some have no native route and always call numpy (fft.fft, 2-D linalg.solve) Performance-relevant hot paths, plus wrappers that exist for signature, dispatch or hardened-mode reasons sum, mean, var, sort, searchsorted, digitize, where, fft.fftfreq, the polynomial series evaluators and fits (polyval, chebval, chebfit, …)
2. Native PyO3 class A #[pyclass] registered via m.add_class::<…>() or live singleton instance via m.add(name, instance) Classes that wrap Rust state (iterators, generators, seed sequences, concatenation objects) Generator, SeedSequence, Nditer, r_, c_
3. Identity-equal numpy re-export m.add(name, &numpy.getattr(name)); the actual numpy attribute is rebound under the same name Submodules and attributes whose semantics are pure numpy state and have no engine substitute numpy.rec, numpy.emath, numpy.matrixlib, numpy.typing, numpy.ctypeslib, numpy.core, numpy.f2py, mgrid, ogrid, s_, plus the various constants and dtype scalars

The overlay submodules (strings, char, ma, testing, exceptions, dtypes, lib, linalg, fft, random, polynomial) are fnp module objects, so fnp_python.linalg is numpy.linalg is False; each name inside them is tier 1, 2 or 3 on its own.

Within a tier-1 wrapper, the fast-path-vs-fallback decision is itself tiered:

fast_path_for_common_shape(arg_dtype, common_kwargs)
  └── (on success) return Rust engine result
  └── (on shape/dtype/size-gate mismatch or unsupported kwargs)
       └── call into numpy.<name>(*args, **kwargs) and return that

Two consequences:

  1. fnp_python.some_name is numpy.some_name is literally True for any name handled in tier 3. There is no wrapper, no copy, no version-skew risk.
  2. The fast-path-then-fallback gate is the natural place where the conformance shards under crates/fnp-python/tests/conformance_*.rs live. Each shard pins the exact kwargs that exercise the fast path, the exact kwargs that fall through, and the dtype combinations along both paths, so a regression on either side fails immediately.

The structural lock-in test fnp_python_covers_full_numpy_all runs against the live numpy.__all__ from the build host, so newly-added NumPy names show up immediately as CI failures rather than silently going unsupported.


This section in the README on GitHub