Skip to main content

OpError

Enum OpError 

Source
pub enum OpError {
    OutOfVocabulary {
        id: u32,
        vocab_size: usize,
        position: usize,
    },
    ShapeMismatch {
        expected: Vec<usize>,
        got: Vec<usize>,
    },
    AllPaddingRow {
        row: usize,
    },
    LengthMismatch {
        ids: usize,
        mask: usize,
    },
    ZeroDimension {
        which: &'static str,
    },
    ShapeOverflow {
        dims: Vec<usize>,
    },
    NonBinaryMaskValue {
        value: u8,
        position: usize,
    },
    NonFiniteInput {
        position: usize,
    },
    InvalidEpsilon {
        eps_bits: u32,
    },
}
Expand description

Failure modes of the batched SetFit primitives in crate::autograd.

These ops sit on a trust boundary: ids, masks and shapes arrive from tokenizer output today and from model files from Phase 4 onward, so every argument is untrusted. Each variant therefore names the specific condition that failed rather than collapsing to a generic “bad input”.

Two known traps in this repository are exactly what this enum exists to close:

  • crates/aprender-train/src/transformer/embedding.rs silently zero-fills out-of-vocabulary ids. A zero row is indistinguishable from a legitimately zero embedding downstream, so the corruption never raises an error — it only ever surfaces as unexplained accuracy loss.
  • crates/aprender-core/src/models/bert/embeddings.rs assert!s on over-length input and then slices unchecked.

Neither is acceptable here. Every op that returns this error fails closed: it never panics, never zero-fills, and never lets a NaN into the autograd graph.

Plans 01-03 and 01-09 extend this enum with further variants. Do not rename the existing ones — they are named in contracts/setfit-encoder-conformance-v1.yaml.

Variants§

§

OutOfVocabulary

A token id was at or beyond vocab_size.

position is the index into the FLATTENED B*S id slice, so a caller can recover (batch, seq) as (position / seq, position % seq).

Fields

§id: u32

The offending token id.

§vocab_size: usize

Rows available in the embedding table.

§position: usize

Flattened b * seq + s index of the offending id.

§

ShapeMismatch

A tensor did not have the required shape.

A 0 extent inside expected means unconstrained — it encodes a rank requirement whose extents the op cannot know in advance. expected: [0, 0] therefore reads as “any 2-D shape”.

Fields

§expected: Vec<usize>

Required shape; 0 marks an unconstrained extent.

§got: Vec<usize>

Shape actually supplied.

§

AllPaddingRow

A batch row had no valid (non-padding) position.

This is the checked-denominator guard (D-03). Pooling such a row would divide by zero, and masking it would produce an all--1e9 softmax row.

Fields

§row: usize

Index of the offending batch row.

§

LengthMismatch

A mask length did not match the position count implied by the shape.

ids carries the expected element count derived from the batch and sequence dimensions; mask carries the length actually supplied.

Fields

§ids: usize

Expected number of positions (batch * seq).

§mask: usize

Length of the mask slice actually supplied.

§

ZeroDimension

A dimension was zero.

Returned instead of an empty tensor, because an empty tensor silently no-ops every downstream op and the failure then surfaces far from its cause.

Fields

§which: &'static str

Which dimension was zero ("batch", "seq", "hidden", …).

§

ShapeOverflow

A shape product would overflow usize.

Detected with checked_mul before any allocation, so a wrapping element count can never become an under-sized buffer.

Fields

§dims: Vec<usize>

The dimensions whose product overflowed.

§

NonBinaryMaskValue

An attention-mask entry was neither 0 nor 1.

A 2 must never be silently treated as “keep”: that would let a malformed mask quietly widen attention over padding.

Fields

§value: u8

The offending value.

§position: usize

Flattened index of the offending value.

§

NonFiniteInput

An input tensor contained a non-finite value (NaN or ±Inf).

Rejected at the op boundary so a corrupt weight cannot poison every downstream gradient with a NaN that is untraceable to its source.

Fields

§position: usize

Flattened index of the offending element.

§

InvalidEpsilon

The epsilon floor was not a positive, finite number (plan 01-03).

l2_normalize_rows and cosine_similarity_rows divide by max(norm, eps). A zero, negative, NaN or infinite eps therefore removes the only guard standing between a zero-norm row and a NaN (or, with a negative eps, silently flips the sign of a whole row). The floor is an explicit parameter with no hidden default precisely so that it can be validated here.

§Why the value is stored as BITS rather than as an f32

Two independent reasons, both of which bite:

  1. OpError derives Eq. An f32 field would forbid that derive for the whole enum, changing the API of seven pre-existing variants for the sake of one.
  2. NaN != NaN under PartialEq. Had the variant carried an f32, assert_eq!(err, OpError::InvalidEpsilon { eps: f32::NAN }) would be unsatisfiable against a correct implementation — for exactly the NaN input this variant exists to reject. That is the same class of self-defeating assertion the ENC-04 gradient gate was rewritten to avoid.

OpError::epsilon recovers the original value for display or inspection.

Fields

§eps_bits: u32

IEEE-754 bit pattern of the offending epsilon.

Implementations§

Source§

impl OpError

Source

pub fn epsilon(&self) -> Option<f32>

Recover the epsilon carried by OpError::InvalidEpsilon.

Returns None for every other variant.

Trait Implementations§

Source§

impl Clone for OpError

Source§

fn clone(&self) -> OpError

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for OpError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Display for OpError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Eq for OpError

Source§

impl Error for OpError

1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0:

use the Display impl or to_string()

1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl PartialEq for OpError

Source§

fn eq(&self, other: &OpError) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for OpError

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,