Skip to main content

TensorDType

Enum TensorDType 

Source
#[non_exhaustive]
pub enum TensorDType {
Show 19 variants F64, F32, F16, BF16, F8E4M3, F8E5M2, I64, I32, I16, I8, U64, U32, U16, U8, Bool, I4, U4, GgufPacked { ggml_type: u32, }, Other(String),
}
Expand description

Normalized tensor element type.

Scalar variants are shared by both formats. Packed GGML quantized layouts keep their exact wire code in TensorDType::GgufPacked, so they are never conflated with a Safetensors label. Unrecognized labels are preserved in TensorDType::Other.

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

F64

64-bit float.

§

F32

32-bit float.

§

F16

IEEE-754 half float.

§

BF16

bfloat16.

§

F8E4M3

8-bit float, E4M3.

§

F8E5M2

8-bit float, E5M2.

§

I64

Signed 64-bit integer.

§

I32

Signed 32-bit integer.

§

I16

Signed 16-bit integer.

§

I8

Signed 8-bit integer.

§

U64

Unsigned 64-bit integer.

§

U32

Unsigned 32-bit integer.

§

U16

Unsigned 16-bit integer.

§

U8

Unsigned 8-bit integer.

§

Bool

One-byte boolean.

§

I4

Signed 4-bit integer, two elements per byte (Safetensors I4/INT4).

§

U4

Unsigned 4-bit integer, two elements per byte (Safetensors U4).

§

GgufPacked

A packed GGML quantized block layout (Q4_K, Q8_0, IQ*, …). The raw on-wire ggml_type code is preserved; payload bytes keep the native block layout.

Fields

§ggml_type: u32

GGUF on-wire ggml_type code.

§

Other(String)

A dtype label this crate does not normalize (e.g. C64, F8_E8M0).

Implementations§

Source§

impl TensorDType

Source

pub fn label(&self) -> &str

Short label ("F32", "Q4_K", or the preserved Self::Other label).

Examples found in repository?
examples/checkpoint_smoke/run.rs (line 293)
289fn verify_tensor_metadata(t: &engram_parser::TensorInfo, e: &Expected) -> Result<()> {
290    require(
291        t.name == e.name
292            && t.native_dtype == e.dtype
293            && t.dtype.label() == expected_dtype_label(&e.dtype)
294            && t.shape.dims() == e.shape
295            && t.byte_len == e.bytes
296            && t.location.source == e.shard
297            && t.location.file_offset == Some(e.offset),
298        format!(
299            "metadata mismatch for {:?}: actual={t:?}, expected={e:?}",
300            e.name
301        ),
302    )
303}
More examples
Hide additional examples
examples/inspect_checkpoint.rs (line 90)
66fn report(ckpt: &dyn Checkpoint, rows: usize) -> Result<()> {
67    let source = ckpt.source();
68    let tensors = ckpt.tensors();
69    let total_bytes: usize = tensors.iter().map(|t| t.byte_len).sum();
70    println!("format:        {} ({})", ckpt.format(), source.kind);
71    println!("path:          {}", source.path.display());
72    println!("root:          {}", source.root.display());
73    if let Some(index) = &source.index_file {
74        println!("index:         {index}");
75    }
76    println!("files:         {}", source.files.len());
77    println!("metadata keys: {}", ckpt.metadata().len());
78    println!("tensors:       {}", tensors.len());
79    println!("payload bytes: {total_bytes}");
80    println!();
81
82    println!(
83        "{:<48} {:<10} {:<10} {:<22} {:>12}  location",
84        "name", "dtype", "native", "shape (outer-first)", "bytes"
85    );
86    for t in tensors.iter().take(rows) {
87        println!(
88            "{:<48} {:<10} {:<10} {:<22} {:>12}  {}@{}",
89            t.name,
90            t.dtype.label(),
91            t.native_dtype,
92            format!("{:?}", t.shape.dims()),
93            t.byte_len,
94            t.location.source,
95            t.location.data_offset,
96        );
97    }
98    if tensors.len() > rows {
99        println!("… {} more (use --all)", tensors.len() - rows);
100    }
101    println!();
102
103    let mut histogram: BTreeMap<String, (usize, usize)> = BTreeMap::new();
104    for t in tensors {
105        let entry = histogram.entry(t.native_dtype.clone()).or_default();
106        entry.0 += 1;
107        entry.1 += t.byte_len;
108    }
109    println!("dtype histogram (native label: count, bytes):");
110    for (dtype, (count, bytes)) in &histogram {
111        println!("  {dtype:<12} {count:>6}  {bytes:>14}");
112    }
113
114    // Probe the smallest non-empty tensor, and skip it past a size cap so
115    // owned (non-mmap) backends never allocate a huge buffer here.
116    let probe = tensors
117        .iter()
118        .filter(|t| t.byte_len > 0)
119        .min_by_key(|t| t.byte_len);
120    if let Some(big) = probe.filter(|t| t.byte_len > PROBE_CAP_BYTES) {
121        println!();
122        println!(
123            "payload probe skipped: smallest tensor '{}' is {} bytes (> {PROBE_CAP_BYTES})",
124            big.name, big.byte_len
125        );
126    } else if let Some(probe) = probe {
127        let bytes = ckpt.tensor_bytes(&probe.name)?;
128        assert_eq!(bytes.len(), probe.byte_len, "payload length mismatch");
129        println!();
130        println!(
131            "payload probe: '{}' -> {} bytes (matches byte_len)",
132            probe.name,
133            bytes.len()
134        );
135    }
136    Ok(())
137}
Source

pub fn is_packed(&self) -> bool

true for sub-byte or block layouts where bytes ≠ elements × width.

Source

pub fn element_size(&self) -> Option<usize>

Byte width of one element for plain scalar dtypes; None for packed and unknown dtypes.

Trait Implementations§

Source§

impl Clone for TensorDType

Source§

fn clone(&self) -> Self

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 TensorDType

Source§

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

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

impl Display for TensorDType

Source§

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

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

impl Eq for TensorDType

Source§

impl Hash for TensorDType

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for TensorDType

Source§

fn eq(&self, other: &Self) -> 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 TensorDType

Auto Trait Implementations§

§

impl Forget for TensorDType

§

impl Freeze for TensorDType
where *const u8 is !null: Freeze, PhantomData<u8>: Freeze,

§

impl Move for TensorDType

§

impl RefUnwindSafe for TensorDType

§

impl Send for TensorDType
where RawVecInner: Send,

§

impl Sync for TensorDType
where RawVecInner: Sync,

§

impl Unpin for TensorDType
where *const u8 is !null: Unpin,

§

impl UnsafeUnpin for TensorDType

§

impl UnwindSafe for TensorDType
where RawVecInner: UnwindSafe,

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<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> 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> 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.