Skip to main content

WeightStorage

Enum WeightStorage 

Source
pub enum WeightStorage {
    F32(Arc<[f32]>),
    BF16(Arc<[bf16]>),
    Q4_0 {
        words: Arc<[u32]>,
        bytes_len: usize,
        in_features: usize,
        out_features: usize,
    },
    WithLoRA {
        base: Box<WeightStorage>,
        lora_a: Arc<[f32]>,
        lora_b: Arc<[f32]>,
        rank: usize,
        alpha: f32,
        in_features: usize,
        out_features: usize,
    },
}
Expand description

Weight tensor storage that preserves source precision.

Projection weights (Q/K/V/O for attention, gate/up/down for FFN, and the output lm_head matrix) stay in whatever dtype the source checkpoint used — f32 when that’s how it was saved, bf16 for modern HF checkpoints that ship bf16 to halve weight memory. Activations are usually f32, but LlamaModel’s cached decode path (Phase D increment A, “BF16-throughout decode”) threads the KV cache’s dtype through the whole activation stream — when that’s BF16, weights must ALSO be BF16 (matmul’s dtype gate only allows same-dtype homogeneous or (lhs=F32, rhs=BF16); a BF16-activation × F32-weight matmul is rejected, the opposite direction from the classic f32-activation-over-bf16-weight quantized-serving case). F32 activations still route the mixed (A:F32, B:BF16) → F32 precision via VulkanBackend::matmul unchanged.

Norm gains and biases are NOT covered by this enum — they’re small and precision-sensitive, so they stay Arc<[f32]>.

Cloning is cheap (Arc bump) for both variants. Use WeightStorage::const_like to emit a Tensor Const node with the right dtype.

Variants§

§

F32(Arc<[f32]>)

§

BF16(Arc<[bf16]>)

§

Q4_0

GGML Q4_0 blocks (raw byte stream), laid out as [out_features, in_features / 32] blocks (18 bytes each, llama.cpp convention). Stored as Arc<[u32]> — the byte stream reinterpreted as u32 words so subsequent forward passes just Arc-clone (cheap) rather than recopying the bytes. The graph sees this directly as a U32 tensor; matmul dispatch goes through Op::QMatMul.

bytes_len is the original byte count (u32_len * 4) so the const_like shape computation doesn’t accidentally round up.

Fields

§words: Arc<[u32]>
§bytes_len: usize
§in_features: usize
§out_features: usize
§

WithLoRA

Base weight wrapped with a trainable LoRA (Low-Rank Adaptation) update: effective weight W_eff = base + (alpha / rank) · A · B where A has shape [in_features, rank] and B has shape [rank, out_features] (both stored in the same layout convention as F32 weights — [in, out]).

Used for PEFT-style inference with frozen base weights (which can be F32, BF16, or Q4_0) plus small trainable adapter matrices. The adapter is cheap to apply — for a 2560×2560 projection at rank 8 the LoRA path is ~0.5% of the base matmul cost.

Fields

§lora_a: Arc<[f32]>

[in_features, rank] adapter A (HF’s lora_A transposed).

§lora_b: Arc<[f32]>

[rank, out_features] adapter B (HF’s lora_B transposed).

§rank: usize
§alpha: f32

LoRA scaling factor; effective scale is alpha / rank.

§in_features: usize
§out_features: usize

Implementations§

Source§

impl WeightStorage

Source

pub fn elem_count(&self) -> usize

Source

pub fn dtype(&self) -> DType

Source

pub fn const_like(&self, anchor: &Tensor, shape: Shape) -> Result<Tensor, Error>

Emit a Const node on anchor’s graph matching this storage’s dtype. Used everywhere the forward pass wraps a weight into a Tensor.

For Q4_0, the emitted tensor is a 1-D U32 const of length bytes.len() / 4 holding the raw block byte stream. Callers must pair this with Tensor::qmatmul rather than matmul.

Returns Err for WithLoRA — the base + LoRA update can only be applied via apply_linear so the right graph structure is built.

Source

pub fn apply_linear_with_bias( &self, x: &Tensor, in_features: usize, out_features: usize, bias: Arc<[f32]>, ) -> Result<Tensor, Error>

Produce X @ W + bias for this weight storage. Bias is a length-out_features Arc<f32> materialized fresh on the receiver’s graph and broadcast across the leading dims of the output.

Equivalent to the per-port apply_linear_with_bias helpers that several ports inlined — promoted here so call sites stop drifting.

Source

pub fn apply_linear( &self, x: &Tensor, in_features: usize, out_features: usize, ) -> Result<Tensor, Error>

Produce X @ W (with optional bias) for this weight storage. Dispatches to matmul for F32/BF16 weights and to qmatmul for Q4_0. x’s dtype must be compatible with this weight’s dtype per matmul’s gate: same-dtype homogeneous (e.g. BF16 activations × BF16 weights — LlamaModel’s BF16-throughout decode path, Phase D increment A) or (x=F32, weight=BF16) (f32-activation quantized-weight serving). (x=BF16, weight=F32) is NOT supported — cast the weight or the activation to match before calling.

§Errors

Returns a typed error rather than panicking on a dimension or dtype mismatch. This used to .unwrap() the inner matmul/qmatmul and assert_eq! the stored-vs-requested dimensions, which made a production path panic — a mismatched checkpoint (a GGUF whose stored shape disagrees with the model config) is a data condition, not a programming invariant, so it must surface as Err.

Source

pub fn apply_linear_dyn_m( &self, x: &Tensor, in_features: usize, out_features: usize, row_count: DynScalar, ) -> Result<Tensor, Error>

Data-determined-M variant of Self::apply_linear: computes only row_count rows of the capacity-buffer projection x @ W, the rest left zeroed — the per-expert sparse-MoE FFN path. x is a [capacity, in_features] buffer whose first row_count rows are the routed tokens; the returned [capacity, out_features] buffer’s tail (rows row_count..capacity) stays exactly zero (see Tensor::matmul_dyn_m).

F32-only (mirrors matmul_dyn_m); other weight encodings surface a typed build-time error. No bias is applied — a bias would fill the un-computed tail, which the sparse-MoE caller relies on being zero for a correct index_add scatter-back.

Source

pub fn with_lora( self, lora_a: Arc<[f32]>, lora_b: Arc<[f32]>, rank: usize, alpha: f32, in_features: usize, out_features: usize, ) -> Self

Wrap this weight storage with a LoRA adapter. Asserts that the adapter shapes match in_features/out_features. Panics if the base is already a WithLoRA (nested adapters aren’t supported; merge them explicitly if needed).

Trait Implementations§

Source§

impl Clone for WeightStorage

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 WeightStorage

Source§

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

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

impl From<Arc<[bf16]>> for WeightStorage

Source§

fn from(a: Arc<[bf16]>) -> Self

Converts to this type from the input type.
Source§

impl From<Arc<[f32]>> for WeightStorage

Source§

fn from(a: Arc<[f32]>) -> Self

Converts to this type from the input type.
Source§

impl From<Vec<bf16>> for WeightStorage

Source§

fn from(v: Vec<bf16>) -> Self

Converts to this type from the input type.
Source§

impl From<Vec<f32>> for WeightStorage

Source§

fn from(v: Vec<f32>) -> Self

Converts to this type from the input type.

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> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> 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.
Source§

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

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more