Skip to main content

oa/ml/matrix/
quant.rs

1//! Native symmetric Q4/Q8 block-plane weight operations.
2//!
3//! [`QuantMatrix`] is deliberately not a [`crate::DType`]: one logical value
4//! owns a packed integer payload and a separate Float32 scale plane, so matrix
5//! byte sizes, strides, views, and element access of a dense dtype would be
6//! incorrect. The physical planes remain private and travel as one weight
7//! value.
8//!
9//! Donor: `oacpp/source/cpp/lib/oa/ml/fnmatrix/quant/fnMatrixQuant.cpp`.
10
11use crate::{
12	DType, Error, Matrix, OpAttribute, Result,
13	ml::validation::shader_u32,
14	runtime::{BufferBinding, ComputeDispatch, KernelId, PushConstant, SemanticDispatch},
15};
16
17use crate::runtime::{QuantSemanticDispatch, QuantSemanticInput, QuantSemanticOutput};
18
19/// Number of logical values in one quantization block.
20const BLOCK_SIZE: usize = 32;
21/// Q4 payload bytes per block: 16 packed bytes (4 words).
22const Q4_BYTES_PER_BLOCK: usize = 16;
23/// Q8 payload bytes per block: 32 signed bytes (8 words).
24const Q8_BYTES_PER_BLOCK: usize = 32;
25/// Q4 packed 32-bit words per block.
26const Q4_WORDS_PER_BLOCK: usize = 4;
27/// Q8 packed 32-bit words per block.
28const Q8_WORDS_PER_BLOCK: usize = 8;
29/// Float32 kernels address element offsets as `u32`; the byte offset must fit.
30const MAX_F32_ELEMENT_COUNT: usize = u32::MAX as usize / 4;
31
32/// OA native block quantization selector.
33///
34/// Both formats share one 32-value block layout and one Float32 scale per
35/// block. `Q4` stores a biased 4-bit index per value (16 bytes per block);
36/// `Q8` stores one signed byte per value (32 bytes per block).
37#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
38pub enum Quantization {
39	/// Symmetric 4-bit quantization, range `[-7, 7]` biased by +7.
40	Q4,
41	/// Symmetric 8-bit quantization, range `[-127, 127]`.
42	Q8,
43}
44
45impl Quantization {
46	const fn payload_bytes_per_block(self) -> usize {
47		match self {
48			Self::Q4 => Q4_BYTES_PER_BLOCK,
49			Self::Q8 => Q8_BYTES_PER_BLOCK,
50		}
51	}
52
53	const fn as_str(self) -> &'static str {
54		match self {
55			Self::Q4 => "Q4",
56			Self::Q8 => "Q8",
57		}
58	}
59}
60
61/// A GPU-resident weight stored in OA's native Q4 or Q8 block encoding.
62///
63/// Constructed by [`quantize`]; the packed payload and scale planes are
64/// private implementation detail and never exposed as public matrix values.
65#[derive(Clone)]
66pub struct QuantMatrix {
67	payload: Matrix,
68	scale: Matrix,
69	shape: Vec<usize>,
70	quantization: Quantization,
71}
72
73impl QuantMatrix {
74	/// Return the logical (dequantized) weight shape.
75	pub fn shape(&self) -> &[usize] {
76		&self.shape
77	}
78
79	/// Return the number of logical weight elements.
80	pub fn num_elements(&self) -> usize {
81		self.shape.iter().product()
82	}
83
84	/// Return the block quantization format.
85	pub const fn quantization(&self) -> Quantization {
86		self.quantization
87	}
88
89	/// Construct one weight value from checked private planes.
90	///
91	/// The payload plane stores `blocks * bytes_per_block` `U8` bytes and the
92	/// scale plane stores one Float32 per 32-value block. `Quantization::Q8`
93	/// uses `U8` storage because packed planes never expose element semantics;
94	/// the signed byte interpretation lives inside the kernels. This is the
95	/// private construction bridge used by lowering and exact-plane tests, not
96	/// a public construction contract — use [`quantize`].
97	#[doc(hidden)]
98	pub fn from_planes(
99		payload: Matrix,
100		scale: Matrix,
101		shape: Vec<usize>,
102		quantization: Quantization,
103	) -> Result<Self> {
104		if payload.dtype() != DType::U8 || scale.dtype() != DType::F32 {
105			return Err(Error::invalid_argument(
106				"quantized planes must use U8 payload and Float32 scale storage",
107			));
108		}
109		if payload.shape().len() != 1 || scale.shape().len() != 1 {
110			return Err(Error::invalid_argument(
111				"payload and scale planes must both be one-dimensional",
112			));
113		}
114		if !payload.runtime().same_as(scale.runtime()) {
115			return Err(Error::invalid_argument(
116				"quantized planes must belong to one runtime",
117			));
118		}
119		let elements = shape
120			.iter()
121			.try_fold(1_usize, |total, extent| total.checked_mul(*extent))
122			.ok_or_else(|| Error::invalid_argument("quantized logical shape overflows usize"))?;
123		let blocks = elements.div_ceil(BLOCK_SIZE);
124		let payload_bytes = blocks
125			.checked_mul(quantization.payload_bytes_per_block())
126			.ok_or_else(|| Error::invalid_argument("quantized payload size overflows usize"))?;
127		if payload.num_elements() != payload_bytes || scale.num_elements() != blocks {
128			return Err(Error::invalid_argument(
129				"payload/scale planes do not match the logical shape",
130			));
131		}
132		Ok(Self {
133			payload,
134			scale,
135			shape,
136			quantization,
137		})
138	}
139
140	/// Private test/lowering bridge to the packed payload plane.
141	///
142	/// The payload is `U8` storage whose packed bit layout is private; lowering
143	/// code and exact-plane oracles read bytes only. This is not a public value
144	/// accessor — the planes travel inside one [`QuantMatrix`].
145	#[doc(hidden)]
146	pub const fn payload(&self) -> &Matrix {
147		&self.payload
148	}
149
150	/// Private test/lowering bridge to the Float32 scale plane.
151	#[doc(hidden)]
152	pub const fn scale(&self) -> &Matrix {
153		&self.scale
154	}
155
156	pub(crate) fn value_id(&self) -> u64 {
157		self.payload.value_id()
158	}
159
160	pub(crate) const fn runtime(&self) -> &crate::runtime::RuntimeHandle {
161		self.payload.runtime()
162	}
163}
164
165/// Quantize Float32 storage into one native OA Q4 or Q8 weight value.
166///
167/// The returned value retains the source shape; its physical planes remain
168/// private.
169///
170/// # Errors
171///
172/// Returns an error unless the input is a non-empty Float32 matrix whose
173/// element byte offsets fit the `u32` kernel ABI, or allocation/recording
174/// fails.
175pub fn quantize(input: &Matrix, quantization: Quantization) -> Result<QuantMatrix> {
176	let operation = "oa::FnMatrix::quantize";
177	let count = input.num_elements();
178	if count == 0 {
179		return Err(Error::invalid_argument(format!(
180			"{operation} input must have non-empty Float32 storage"
181		)));
182	}
183	if input.dtype() != DType::F32 {
184		return Err(Error::invalid_argument(format!(
185			"{operation} only Float32 source storage is admitted"
186		)));
187	}
188	admit_count(count, operation)?;
189
190	let runtime = input.runtime();
191	let lowering = runtime.begin_semantic_lowering()?;
192	let scale = compute_scale(input, quantization)?;
193	let payload = quantize_planes(input, &scale, quantization)?;
194	let output = QuantMatrix::from_planes(payload, scale, input.shape().to_vec(), quantization)?;
195	lowering.commit_quant(QuantSemanticDispatch {
196		contract: crate::core::operation::ml::QUANTIZE,
197		inputs: &[QuantSemanticInput::Matrix(input)],
198		outputs: &[QuantSemanticOutput::QuantMatrix(&output)],
199		attributes: &[quantization_attribute(quantization)],
200	})?;
201	Ok(output)
202}
203
204/// Materialize a Float32 matrix with the logical shape retained by `input`.
205///
206/// # Errors
207///
208/// Returns an error for an empty weight, oversized element counts, or
209/// allocation/recording failure.
210pub fn dequantize(input: &QuantMatrix) -> Result<Matrix> {
211	let operation = "oa::FnMatrix::dequantize";
212	let count = input.num_elements();
213	if count == 0 {
214		return Err(Error::invalid_argument(format!(
215			"{operation} input must contain a non-empty quantized weight"
216		)));
217	}
218	admit_count(count, operation)?;
219
220	let runtime = input.runtime();
221	let lowering = runtime.begin_semantic_lowering()?;
222	let flat = dequantize_planes(input.payload(), input.scale(), count, input.quantization())?;
223	let output = flat.reshape_semantic_output(input.shape().to_vec())?;
224	lowering.commit_quant(QuantSemanticDispatch {
225		contract: crate::core::operation::ml::DEQUANTIZE,
226		inputs: &[QuantSemanticInput::QuantMatrix(input)],
227		outputs: &[QuantSemanticOutput::Matrix(&output)],
228		attributes: &[quantization_attribute(input.quantization())],
229	})?;
230	Ok(output)
231}
232
233/// Multiply `[..., K]` Float32 activations by a quantized `[N, K]` weight
234/// without materializing a Float32 weight matrix.
235///
236/// The result shape is `[..., N]`.
237///
238/// # Errors
239///
240/// Returns an error unless the weight has rank 2, the input has rank at least
241/// 2 with a matching last dimension, all planes are contiguous base storage on
242/// one runtime, the flattened dimensions fit the `u32` kernel ABI, or
243/// allocation/recording fails.
244pub fn matmul(input: &Matrix, weight: &QuantMatrix) -> Result<Matrix> {
245	let operation = "oa::FnMatrix::matMulNtQuantized";
246	if weight.shape().len() != 2 {
247		return Err(Error::invalid_argument(format!(
248			"{operation} quantized weight must have rank 2 [N,K]"
249		)));
250	}
251	if input.shape().len() < 2 || *input.shape().last().unwrap_or(&0) != weight.shape()[1] {
252		return Err(Error::invalid_argument(format!(
253			"{operation} input last dimension must match quantized weight K"
254		)));
255	}
256	if !input.runtime().same_as(weight.runtime()) {
257		return Err(Error::invalid_argument(format!(
258			"{operation} input and quantized weight must belong to one runtime"
259		)));
260	}
261	let output_features = weight.shape()[0];
262	let runtime = input.runtime();
263	let lowering = runtime.begin_semantic_lowering()?;
264	let output = matmul_nt_planes(
265		input,
266		weight.payload(),
267		weight.scale(),
268		output_features,
269		weight.quantization(),
270	)?;
271	lowering.commit_quant(QuantSemanticDispatch {
272		contract: crate::core::operation::ml::MATMUL_NT_QUANTIZED,
273		inputs: &[
274			QuantSemanticInput::Matrix(input),
275			QuantSemanticInput::QuantMatrix(weight),
276		],
277		outputs: &[QuantSemanticOutput::Matrix(&output)],
278		attributes: &[quantization_attribute(weight.quantization())],
279	})?;
280	Ok(output)
281}
282
283fn quantization_attribute(quantization: Quantization) -> OpAttribute {
284	OpAttribute::Enum {
285		name: "quantization".into(),
286		value: quantization.as_str().into(),
287	}
288}
289
290fn admit_count(count: usize, operation: &str) -> Result<()> {
291	if count > MAX_F32_ELEMENT_COUNT {
292		return Err(Error::invalid_argument(format!(
293			"{operation} Float32 byte offsets must fit the u32 kernel ABI"
294		)));
295	}
296	Ok(())
297}
298
299fn compute_scale(input: &Matrix, quantization: Quantization) -> Result<Matrix> {
300	let (contract, kernel) = match quantization {
301		Quantization::Q4 => (
302			crate::core::operation::ml::COMPUTE_SCALE_Q4,
303			KernelId::MlComputeScaleQ4F32,
304		),
305		Quantization::Q8 => (
306			crate::core::operation::ml::COMPUTE_SCALE_Q8,
307			KernelId::MlComputeScaleQ8F32,
308		),
309	};
310	let operation = contract.name();
311	let count = input.num_elements();
312	admit_count(count, operation)?;
313	if input.dtype() != DType::F32 {
314		return Err(Error::invalid_argument(format!(
315			"{operation} input must use Float32 storage"
316		)));
317	}
318	let count_u32 = shader_u32(count, "element count", operation)?;
319	let blocks = count.div_ceil(BLOCK_SIZE);
320	let blocks_u32 = shader_u32(blocks, "block count", operation)?;
321	let scale = Matrix::allocate(input.runtime(), vec![blocks], blocks, DType::F32)?;
322	if count_u32 == 0 {
323		return Ok(scale);
324	}
325	let buffers = [
326		BufferBinding::read(input.storage()),
327		BufferBinding::write(scale.storage()),
328	];
329	let push_constants = [PushConstant::U32(count_u32)];
330	input.runtime().record_semantic(
331		ComputeDispatch {
332			kernel,
333			buffers: &buffers,
334			push_constants: &push_constants,
335			workgroups: kernel.linear_workgroups(blocks_u32),
336			indirect: None,
337		},
338		SemanticDispatch {
339			contract,
340			inputs: &[input],
341			outputs: &[&scale],
342			attributes: &[],
343		},
344	)?;
345	Ok(scale)
346}
347
348fn quantize_planes(input: &Matrix, scale: &Matrix, quantization: Quantization) -> Result<Matrix> {
349	let (contract, kernel, bytes_per_block, words_per_block) = match quantization {
350		Quantization::Q4 => (
351			crate::core::operation::ml::QUANTIZE_Q4,
352			KernelId::MlQuantizeQ4F32,
353			Q4_BYTES_PER_BLOCK,
354			Q4_WORDS_PER_BLOCK,
355		),
356		Quantization::Q8 => (
357			crate::core::operation::ml::QUANTIZE_Q8,
358			KernelId::MlQuantizeQ8F32,
359			Q8_BYTES_PER_BLOCK,
360			Q8_WORDS_PER_BLOCK,
361		),
362	};
363	let operation = contract.name();
364	let count = input.num_elements();
365	admit_count(count, operation)?;
366	if input.dtype() != DType::F32 || scale.dtype() != DType::F32 {
367		return Err(Error::invalid_argument(format!(
368			"{operation} input and scale must use Float32 storage"
369		)));
370	}
371	let count_u32 = shader_u32(count, "element count", operation)?;
372	let blocks = count.div_ceil(BLOCK_SIZE);
373	if scale.num_elements() != blocks {
374		return Err(Error::invalid_argument(format!(
375			"{operation} expected one scale per 32-value block"
376		)));
377	}
378	let payload_bytes = blocks
379		.checked_mul(bytes_per_block)
380		.ok_or_else(|| Error::invalid_argument(format!("{operation} payload size overflows usize")))?;
381	let payload_words = blocks
382		.checked_mul(words_per_block)
383		.ok_or_else(|| Error::invalid_argument(format!("{operation} payload size overflows usize")))?;
384	let payload = Matrix::allocate(
385		input.runtime(),
386		vec![payload_bytes],
387		payload_bytes,
388		DType::U8,
389	)?;
390	if count_u32 == 0 {
391		return Ok(payload);
392	}
393	let buffers = [
394		BufferBinding::read(input.storage()),
395		BufferBinding::write(payload.storage()),
396		BufferBinding::read(scale.storage()),
397	];
398	let push_constants = [PushConstant::U32(count_u32)];
399	input.runtime().record_semantic(
400		ComputeDispatch {
401			kernel,
402			buffers: &buffers,
403			push_constants: &push_constants,
404			workgroups: kernel.linear_workgroups(shader_u32(
405				payload_words,
406				"payload word count",
407				operation,
408			)?),
409			indirect: None,
410		},
411		SemanticDispatch {
412			contract,
413			inputs: &[input, scale],
414			outputs: &[&payload],
415			attributes: &[],
416		},
417	)?;
418	Ok(payload)
419}
420
421fn dequantize_planes(
422	payload: &Matrix,
423	scale: &Matrix,
424	count: usize,
425	quantization: Quantization,
426) -> Result<Matrix> {
427	let (contract, kernel, bytes_per_block) = match quantization {
428		Quantization::Q4 => (
429			crate::core::operation::ml::DEQUANTIZE_Q4,
430			KernelId::MlDequantizeQ4F32,
431			Q4_BYTES_PER_BLOCK,
432		),
433		Quantization::Q8 => (
434			crate::core::operation::ml::DEQUANTIZE_Q8,
435			KernelId::MlDequantizeQ8F32,
436			Q8_BYTES_PER_BLOCK,
437		),
438	};
439	let operation = contract.name();
440	admit_count(count, operation)?;
441	if payload.dtype() != DType::U8 || scale.dtype() != DType::F32 {
442		return Err(Error::invalid_argument(format!(
443			"{operation} payload must be U8 and scale must be Float32"
444		)));
445	}
446	let count_u32 = shader_u32(count, "element count", operation)?;
447	let blocks = count.div_ceil(BLOCK_SIZE);
448	let payload_bytes = blocks
449		.checked_mul(bytes_per_block)
450		.ok_or_else(|| Error::invalid_argument(format!("{operation} payload size overflows usize")))?;
451	if scale.num_elements() != blocks || payload.num_elements() != payload_bytes {
452		return Err(Error::invalid_argument(format!(
453			"{operation} payload/scale shape does not match element count"
454		)));
455	}
456	let output = Matrix::allocate(payload.runtime(), vec![count], count, DType::F32)?;
457	if count_u32 == 0 {
458		return Ok(output);
459	}
460	let buffers = [
461		BufferBinding::read(payload.storage()),
462		BufferBinding::write(output.storage()),
463		BufferBinding::read(scale.storage()),
464	];
465	let push_constants = [PushConstant::U32(count_u32)];
466	payload.runtime().record_semantic(
467		ComputeDispatch {
468			kernel,
469			buffers: &buffers,
470			push_constants: &push_constants,
471			workgroups: kernel.linear_workgroups(count_u32),
472			indirect: None,
473		},
474		SemanticDispatch {
475			contract,
476			inputs: &[payload, scale],
477			outputs: &[&output],
478			attributes: &[],
479		},
480	)?;
481	Ok(output)
482}
483
484fn matmul_nt_planes(
485	input: &Matrix,
486	payload: &Matrix,
487	scale: &Matrix,
488	output_features: usize,
489	quantization: Quantization,
490) -> Result<Matrix> {
491	let (contract, kernel, bytes_per_block) = match quantization {
492		Quantization::Q4 => (
493			crate::core::operation::ml::MATMUL_NT_Q4,
494			KernelId::MlMatmulNtQ4F32,
495			Q4_BYTES_PER_BLOCK,
496		),
497		Quantization::Q8 => (
498			crate::core::operation::ml::MATMUL_NT_Q8,
499			KernelId::MlMatmulNtQ8F32,
500			Q8_BYTES_PER_BLOCK,
501		),
502	};
503	let operation = contract.name();
504	if input.shape().len() < 2 {
505		return Err(Error::invalid_argument(format!(
506			"{operation} input must have rank >= 2 with K in the last dimension"
507		)));
508	}
509	if payload.shape().len() != 1 || scale.shape().len() != 1 {
510		return Err(Error::invalid_argument(format!(
511			"{operation} payload and scale planes must both be one-dimensional"
512		)));
513	}
514	if input.dtype() != DType::F32 || payload.dtype() != DType::U8 || scale.dtype() != DType::F32 {
515		return Err(Error::invalid_argument(format!(
516			"{operation} expected Float32 input, U8 payload, and Float32 scale"
517		)));
518	}
519	if input.semantic().view_byte_offset() != 0
520		|| payload.semantic().view_byte_offset() != 0
521		|| scale.semantic().view_byte_offset() != 0
522	{
523		return Err(Error::invalid_argument(format!(
524			"{operation} input and quantization planes must be contiguous base views"
525		)));
526	}
527	let output_features_u32 = shader_u32(output_features, "output feature count", operation)?;
528	let input_features = *input.shape().last().unwrap_or(&0);
529	if input_features == 0 {
530		return Err(Error::invalid_argument(format!(
531			"{operation} the input K dimension must be positive and fit u32"
532		)));
533	}
534	let k_u32 = shader_u32(input_features, "input K dimension", operation)?;
535	let rows = input
536		.shape()
537		.iter()
538		.take(input.shape().len() - 1)
539		.try_fold(1_usize, |total, extent| total.checked_mul(*extent))
540		.ok_or_else(|| {
541			Error::invalid_argument(format!(
542				"{operation} flattened input row count overflows usize"
543			))
544		})?;
545	let rows_u32 = shader_u32(rows, "flattened input row count", operation)?;
546
547	let weight_count = output_features
548		.checked_mul(input_features)
549		.ok_or_else(|| Error::invalid_argument(format!("{operation} weight count overflows usize")))?;
550	let input_count = rows
551		.checked_mul(input_features)
552		.ok_or_else(|| Error::invalid_argument(format!("{operation} input count overflows usize")))?;
553	let output_count = rows
554		.checked_mul(output_features)
555		.ok_or_else(|| Error::invalid_argument(format!("{operation} output count overflows usize")))?;
556	if weight_count > MAX_F32_ELEMENT_COUNT
557		|| input_count > MAX_F32_ELEMENT_COUNT
558		|| output_count > MAX_F32_ELEMENT_COUNT
559	{
560		return Err(Error::invalid_argument(format!(
561			"{operation} matrix byte offsets exceed the u32 kernel ABI"
562		)));
563	}
564	let blocks = weight_count.div_ceil(BLOCK_SIZE);
565	let payload_bytes = blocks
566		.checked_mul(bytes_per_block)
567		.ok_or_else(|| Error::invalid_argument(format!("{operation} payload size overflows usize")))?;
568	if payload.num_elements() != payload_bytes || scale.num_elements() != blocks {
569		return Err(Error::invalid_argument(format!(
570			"{operation} payload/scale shape does not match [OutputFeatures,K]"
571		)));
572	}
573
574	let mut output_shape = input.shape().to_vec();
575	*output_shape.last_mut().unwrap() = output_features;
576	let output = Matrix::allocate(input.runtime(), output_shape, output_count, DType::F32)?;
577	if rows == 0 || output_features == 0 {
578		return Ok(output);
579	}
580	let buffers = [
581		BufferBinding::read(input.storage()),
582		BufferBinding::read(payload.storage()),
583		BufferBinding::read(scale.storage()),
584		BufferBinding::write(output.storage()),
585	];
586	let push_constants = [
587		PushConstant::U32(rows_u32),
588		PushConstant::U32(output_features_u32),
589		PushConstant::U32(k_u32),
590	];
591	input.runtime().record_semantic(
592		ComputeDispatch {
593			kernel,
594			buffers: &buffers,
595			push_constants: &push_constants,
596			workgroups: [output_features_u32, rows_u32, 1],
597			indirect: None,
598		},
599		SemanticDispatch {
600			contract,
601			inputs: &[input, payload, scale],
602			outputs: &[&output],
603			attributes: &[],
604		},
605	)?;
606	Ok(output)
607}