Skip to main content

TensorShape

Struct TensorShape 

Source
pub struct TensorShape { /* private fields */ }
Expand description

Tensor shape normalized to outermost-first order.

GGUF stores dims innermost-first (ne[0] is the contiguous row length). Those dims are reversed here, so a GGUF [4096, 32000] token embedding becomes [32000, 4096], which is the same order a Safetensors header uses. Self::native_dims recovers the on-disk order losslessly.

Implementations§

Source§

impl TensorShape

Source

pub fn outermost_first(dims: Vec<usize>) -> Self

Build a shape from dims that are already outermost-first.

Source

pub fn from_innermost_first(native: &[usize]) -> Self

Build a shape from native innermost-first dims (GGUF Tensor::dims).

Source

pub fn dims(&self) -> &[usize]

Dims in outermost-first order.

Examples found in repository?
examples/checkpoint_smoke/run.rs (line 294)
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 92)
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 native_order(&self) -> DimOrder

Order the source format stores dims in.

Source

pub fn native_dims(&self) -> Vec<usize>

Dims in the source format’s native order.

Source

pub fn rank(&self) -> usize

Number of dimensions.

Source

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

Product of dims, or None on overflow. A rank-0 shape has one element.

Trait Implementations§

Source§

impl Clone for TensorShape

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 TensorShape

Source§

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

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

impl Eq for TensorShape

Source§

impl Hash for TensorShape

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 TensorShape

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 TensorShape

Auto Trait Implementations§

§

impl Forget for TensorShape

§

impl Freeze for TensorShape

§

impl Move for TensorShape

§

impl RefUnwindSafe for TensorShape

§

impl Send for TensorShape
where RawVecInner: Send,

§

impl Sync for TensorShape
where RawVecInner: Sync,

§

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

§

impl UnsafeUnpin for TensorShape

§

impl UnwindSafe for TensorShape
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, 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.