Skip to main content

oa/ml/nn/
vq.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_vq.json
3// generator_version=8; schema_sha256=efaba2ad030227824934985c55111ce34eb885c2563676888ec5e5e90dda8b1e
4
5use std::rc::Rc;
6
7use crate::{DType, Error, Matrix, Result, Runtime, matrix as core_matrix};
8
9use super::super::{Module, ModuleRegistry, NamedBuffer, NamedStateU32, matrix, random};
10
11// OA donor: oacpp/source/cpp/lib/oa/ml/nn/vq/vq.cpp
12// Adaptation: Complete donor EMA and residual quantizer composition; Rust retains checked FP32 geometry, deterministic seeded Glorot initialization, fresh semantic EMA outputs behind persistent NamedBuffer identities and checkpointed NamedStateU32 revival counter; explicit GPU seeding completion remains unchanged
13/// Configuration for one EMA-trained vector-quantization codebook.
14#[derive(Clone, Copy, Debug, PartialEq)]
15pub struct VectorQuantizerConfig {
16	/// Number of codebook entries.
17	pub num_codes: usize,
18	/// Width of each latent/code vector.
19	pub code_dim: usize,
20	/// Commitment-loss multiplier.
21	pub commitment_beta: f32,
22	/// Exponential moving-average decay.
23	pub ema_decay: f32,
24	/// Positive division and normalization floor.
25	pub ema_epsilon: f32,
26	/// Revive codes whose EMA population falls below this value.
27	pub dead_threshold: f32,
28	/// Rescale codebook rows to unit RMS after each EMA update.
29	pub normalize_codes: bool,
30}
31
32impl Default for VectorQuantizerConfig {
33	fn default() -> Self {
34		Self {
35			num_codes: 256,
36			code_dim: 64,
37			commitment_beta: 0.25,
38			ema_decay: 0.99,
39			ema_epsilon: 1e-5,
40			dead_threshold: 1.0,
41			normalize_codes: false,
42		}
43	}
44}
45
46/// Straight-through vector-quantization result.
47pub struct VqResult {
48	/// Quantized `[N,D]` value whose input adjoint is the identity.
49	pub quantized: Matrix,
50	/// I32 nearest-code indices `[N]`.
51	pub indices: Matrix,
52	/// Rank-zero scalar commitment loss.
53	pub commitment_loss: Matrix,
54}
55
56/// EMA-trained vector quantizer with persistent, non-gradient codebook state.
57pub struct VectorQuantizer {
58	config: VectorQuantizerConfig,
59	codebook: NamedBuffer,
60	embed_sum: NamedBuffer,
61	cluster_size: NamedBuffer,
62	ema_step: NamedStateU32,
63	registry: ModuleRegistry,
64}
65
66impl VectorQuantizer {
67	#[allow(clippy::too_many_arguments)]
68	pub fn new_with_seed(config: VectorQuantizerConfig, seed: u64) -> Result<Self> {
69		Self::new_with_seed_on(&Runtime::current()?, config, seed)
70	}
71
72	/// Construct a deterministically initialized quantizer.
73	///
74	/// # Errors
75	///
76	/// Returns an error for an invalid configuration, shape overflow, or failed
77	/// state allocation/upload.
78	pub fn new_with_seed_on(
79		runtime: &Runtime,
80		config: VectorQuantizerConfig,
81		seed: u64,
82	) -> Result<Self> {
83		validate_config(config)?;
84		let count = config
85			.num_codes
86			.checked_mul(config.code_dim)
87			.ok_or_else(|| Error::invalid_argument("VQ codebook size overflows usize"))?;
88		let denominator = config
89			.num_codes
90			.checked_add(config.code_dim)
91			.ok_or_else(|| Error::invalid_argument("VQ Glorot extent overflows usize"))?;
92		let limit = (6.0_f32 / denominator as f32).sqrt();
93		let values = random::symmetric_uniform(count, limit, seed);
94		let codebook = Matrix::new_from_f32_on(runtime, [config.num_codes, config.code_dim], &values)?;
95		let embed_sum = Matrix::new_from_f32_on(runtime, [config.num_codes, config.code_dim], &values)?;
96		let cluster_size =
97			Matrix::new_from_f32_on(runtime, [config.num_codes], &vec![1.0; config.num_codes])?;
98		Self::from_state(config, codebook, embed_sum, cluster_size)
99	}
100
101	pub fn new(config: VectorQuantizerConfig) -> Result<Self> {
102		Self::new_on(&Runtime::current()?, config)
103	}
104
105	/// Construct a quantizer using deterministic seed zero.
106	///
107	/// # Errors
108	///
109	/// Returns the same errors as [`Self::new_with_seed`].
110	pub fn new_on(runtime: &Runtime, config: VectorQuantizerConfig) -> Result<Self> {
111		Self::new_with_seed_on(runtime, config, 0)
112	}
113
114	fn from_state(
115		config: VectorQuantizerConfig,
116		codebook: Matrix,
117		embed_sum: Matrix,
118		cluster_size: Matrix,
119	) -> Result<Self> {
120		validate_config(config)?;
121		let state_shape = [config.num_codes, config.code_dim];
122		if codebook.shape() != state_shape
123			|| embed_sum.shape() != state_shape
124			|| cluster_size.shape() != [config.num_codes]
125			|| [codebook.dtype(), embed_sum.dtype(), cluster_size.dtype()]
126				.into_iter()
127				.any(|dtype| dtype != DType::F32)
128			|| !codebook.runtime().same_as(embed_sum.runtime())
129			|| !codebook.runtime().same_as(cluster_size.runtime())
130		{
131			return Err(Error::invalid_argument(
132				"VQ state must match the configured same-runtime FP32 codebook geometry",
133			));
134		}
135		let mut registry = ModuleRegistry::new();
136		registry.register_buffer("codebook", codebook, true)?;
137		registry.register_buffer("embed_sum", embed_sum, true)?;
138		registry.register_buffer("cluster_size", cluster_size, true)?;
139		let ema_step = registry.register_state_u32("ema_step", 0)?;
140		let codebook = registry
141			.buffer_handle("codebook")
142			.ok_or_else(|| Error::internal("VQ codebook registration was lost"))?;
143		let embed_sum = registry
144			.buffer_handle("embed_sum")
145			.ok_or_else(|| Error::internal("VQ embed-sum registration was lost"))?;
146		let cluster_size = registry
147			.buffer_handle("cluster_size")
148			.ok_or_else(|| Error::internal("VQ cluster-size registration was lost"))?;
149		Ok(Self {
150			config,
151			codebook,
152			embed_sum,
153			cluster_size,
154			ema_step,
155			registry,
156		})
157	}
158
159	/// Quantize latent rows and build the donor straight-through estimator.
160	///
161	/// This records entirely device-side work. The codebook receives no gradient;
162	/// EMA updates it explicitly through [`Self::ema_update`].
163	///
164	/// # Errors
165	///
166	/// Returns an error for an incompatible latent or failed runtime recording.
167	pub fn quantize(&self, latent: &Matrix) -> Result<VqResult> {
168		let assignment = matrix::vq_assign(latent, &self.codebook.data())?;
169		let detached_delta = matrix::detach(&core_matrix::sub(&assignment.quantized, latent)?)?;
170		let quantized = core_matrix::add(latent, &detached_delta)?;
171		let difference = core_matrix::sub(latent, &assignment.quantized)?;
172		let squared = core_matrix::mul(&difference, &difference)?;
173		let total = core_matrix::reshape(&core_matrix::sum(&squared, -1)?, [])?;
174		let mean = core_matrix::scale(&total, 1.0 / squared.num_elements() as f32)?;
175		let commitment_loss = core_matrix::scale(&mean, self.config.commitment_beta)?;
176		Ok(VqResult {
177			quantized,
178			indices: assignment.indices,
179			commitment_loss,
180		})
181	}
182
183	/// Advance codebook EMA state once from the current latent assignment.
184	///
185	/// # Errors
186	///
187	/// Returns an error for incompatible inputs or failed runtime recording.
188	pub fn ema_update(&self, latent: &Matrix, indices: &Matrix) -> Result<()> {
189		let step = self.ema_step.value();
190		let state = matrix::vq_ema_update(
191			latent,
192			indices,
193			&self.embed_sum.data(),
194			&self.cluster_size.data(),
195			&self.codebook.data(),
196			self.config.ema_decay,
197			self.config.ema_epsilon,
198			self.config.dead_threshold,
199			step,
200			self.config.normalize_codes,
201		)?;
202		self.embed_sum.replace_data(state.embed_sum)?;
203		self.cluster_size.replace_data(state.cluster_size)?;
204		self.codebook.replace_data(state.codebook)?;
205		self.ema_step.replace_value(step.wrapping_add(1));
206		Ok(())
207	}
208
209	/// Decode I32 token ids into code vectors.
210	///
211	/// # Errors
212	///
213	/// Returns an error for incompatible indices or failed runtime recording.
214	pub fn lookup(&self, indices: &Matrix) -> Result<Matrix> {
215		matrix::vq_lookup(&self.codebook.data(), indices)
216	}
217
218	/// Seed codes from the highest-L2-norm latent rows.
219	///
220	/// Equal norms select lower source-row indices. Selection stays on the GPU;
221	/// the final checkpoint is the donor-compatible explicit initialization
222	/// completion boundary.
223	///
224	/// # Errors
225	///
226	/// Returns an error unless `latents` is FP32 `[N,D]`, `N >= K`, and its code
227	/// dimension and runtime match this quantizer, or readback/upload fails.
228	pub fn seed(&self, latents: &Matrix) -> Result<()> {
229		let [rows, code_dim] = latents.shape() else {
230			return Err(Error::invalid_argument(
231				"VQ seed latents must have shape [N,D]",
232			));
233		};
234		let codebook = self.codebook.data();
235		if latents.dtype() != DType::F32
236			|| *rows < self.config.num_codes
237			|| self.config.num_codes > 512
238			|| *code_dim != self.config.code_dim
239			|| !latents.runtime().same_as(codebook.runtime())
240		{
241			return Err(Error::invalid_argument(
242				"VQ seed requires same-runtime FP32 [N,D] latents with N >= K",
243			));
244		}
245		let squared = core_matrix::mul(latents, latents)?;
246		let norms = core_matrix::sum(&squared, 1)?.reshape([*rows])?;
247		let selected = core_matrix::top_k(
248			&norms,
249			i32::try_from(self.config.num_codes)
250				.map_err(|_| Error::invalid_argument("VQ seed code count exceeds i32"))?,
251			-1,
252		)?;
253		let seeded = matrix::vq_lookup(latents, &selected.indices)?;
254		let embed_sum = core_matrix::copy(&seeded)?;
255		let cluster_size = Matrix::new_from_slice_handle(
256			latents.runtime(),
257			vec![self.config.num_codes],
258			&vec![1.0_f32; self.config.num_codes],
259		)?;
260		self.codebook.replace_data(seeded)?;
261		self.embed_sum.replace_data(embed_sum)?;
262		self.cluster_size.replace_data(cluster_size)?;
263		latents.runtime().checkpoint(false)?.wait()
264	}
265
266	/// Return a cheap handle to the current codebook value.
267	pub fn codebook(&self) -> Matrix {
268		self.codebook.data()
269	}
270
271	/// Return this quantizer's immutable configuration.
272	pub const fn config(&self) -> &VectorQuantizerConfig {
273		&self.config
274	}
275
276	/// Return the number of completed EMA transitions modulo `u32`.
277	pub fn ema_step(&self) -> u32 {
278		self.ema_step.value()
279	}
280}
281
282impl Module for VectorQuantizer {
283	fn forward(&self, input: &Matrix) -> Result<Matrix> {
284		Ok(self.quantize(input)?.quantized)
285	}
286
287	fn registry(&self) -> &ModuleRegistry {
288		&self.registry
289	}
290}
291
292/// Multi-level residual vector-quantization result.
293pub struct ResidualVqResult {
294	/// Straight-through sum of all selected code vectors.
295	pub quantized: Matrix,
296	/// One I32 `[N]` token Matrix per level.
297	pub indices: Vec<Matrix>,
298	/// Input residual used by each level's EMA update.
299	pub residuals: Vec<Matrix>,
300	/// Rank-zero scalar commitment loss against the summed code vectors.
301	pub commitment_loss: Matrix,
302}
303
304/// Stack of independently EMA-trained residual vector quantizers.
305pub struct ResidualVectorQuantizer {
306	config: VectorQuantizerConfig,
307	levels: Vec<Rc<VectorQuantizer>>,
308	registry: ModuleRegistry,
309}
310
311impl ResidualVectorQuantizer {
312	#[allow(clippy::too_many_arguments)]
313	pub fn new_with_seed(
314		config: VectorQuantizerConfig,
315		num_levels: usize,
316		seed: u64,
317	) -> Result<Self> {
318		Self::new_with_seed_on(&Runtime::current()?, config, num_levels, seed)
319	}
320
321	/// Construct `num_levels` deterministically initialized quantizers.
322	///
323	/// # Errors
324	///
325	/// Returns an error when the level count or configuration is invalid, child
326	/// state allocation fails, or module registration fails.
327	pub fn new_with_seed_on(
328		runtime: &Runtime,
329		config: VectorQuantizerConfig,
330		num_levels: usize,
331		seed: u64,
332	) -> Result<Self> {
333		if num_levels == 0 {
334			return Err(Error::invalid_argument(
335				"residual VQ requires at least one level",
336			));
337		}
338		let mut registry = ModuleRegistry::new();
339		let mut levels = Vec::with_capacity(num_levels);
340		for level in 0..num_levels {
341			let quantizer = Rc::new(VectorQuantizer::new_with_seed_on(
342				runtime,
343				config,
344				seed.wrapping_add(level as u64),
345			)?);
346			registry.register_module(format!("level{level}"), quantizer.clone())?;
347			levels.push(quantizer);
348		}
349		Ok(Self {
350			config,
351			levels,
352			registry,
353		})
354	}
355
356	pub fn new(config: VectorQuantizerConfig, num_levels: usize) -> Result<Self> {
357		Self::new_on(&Runtime::current()?, config, num_levels)
358	}
359
360	/// Construct a residual quantizer using deterministic seed zero.
361	///
362	/// # Errors
363	///
364	/// Returns the same errors as [`Self::new_with_seed`].
365	pub fn new_on(
366		runtime: &Runtime,
367		config: VectorQuantizerConfig,
368		num_levels: usize,
369	) -> Result<Self> {
370		Self::new_with_seed_on(runtime, config, num_levels, 0)
371	}
372
373	/// Quantize successive residuals and apply one straight-through estimator.
374	///
375	/// # Errors
376	///
377	/// Returns an error for an incompatible latent or failed runtime recording.
378	pub fn quantize(&self, latent: &Matrix) -> Result<ResidualVqResult> {
379		let mut residual = latent.clone();
380		let mut total = None;
381		let mut indices = Vec::with_capacity(self.levels.len());
382		let mut residuals = Vec::with_capacity(self.levels.len());
383		for level in &self.levels {
384			let assignment = matrix::vq_assign(&residual, &level.codebook())?;
385			residuals.push(residual.clone());
386			indices.push(assignment.indices);
387			total = Some(match total {
388				Some(previous) => core_matrix::add(&previous, &assignment.quantized)?,
389				None => assignment.quantized.clone(),
390			});
391			residual = core_matrix::sub(&residual, &assignment.quantized)?;
392		}
393		let total = total.ok_or_else(|| Error::internal("residual VQ lost all levels"))?;
394		let quantized = core_matrix::add(latent, &matrix::detach(&core_matrix::sub(&total, latent)?)?)?;
395		let difference = core_matrix::sub(latent, &total)?;
396		let squared = core_matrix::mul(&difference, &difference)?;
397		let total = core_matrix::reshape(&core_matrix::sum(&squared, -1)?, [])?;
398		let commitment_loss = core_matrix::scale(
399			&total,
400			self.config.commitment_beta / squared.num_elements() as f32,
401		)?;
402		Ok(ResidualVqResult {
403			quantized,
404			indices,
405			residuals,
406			commitment_loss,
407		})
408	}
409
410	/// Advance every level's EMA state using a matching quantization result.
411	///
412	/// # Errors
413	///
414	/// Returns an error when the result has the wrong level count or an update fails.
415	pub fn ema_update(&self, result: &ResidualVqResult) -> Result<()> {
416		if result.indices.len() != self.levels.len() || result.residuals.len() != self.levels.len() {
417			return Err(Error::invalid_argument(
418				"residual VQ result level count does not match module",
419			));
420		}
421		for ((level, residual), indices) in self
422			.levels
423			.iter()
424			.zip(&result.residuals)
425			.zip(&result.indices)
426		{
427			level.ema_update(residual, indices)?;
428		}
429		Ok(())
430	}
431
432	/// Decode one or more shallow-to-deep token levels and sum their codes.
433	///
434	/// # Errors
435	///
436	/// Returns an error when no indices are supplied, too many levels are supplied,
437	/// index shapes differ, or a level lookup/runtime operation fails.
438	pub fn lookup(&self, indices: &[Matrix]) -> Result<Matrix> {
439		if indices.is_empty() || indices.len() > self.levels.len() {
440			return Err(Error::invalid_argument(
441				"residual VQ lookup requires one through num_levels token matrices",
442			));
443		}
444		let mut total = self.levels[0].lookup(&indices[0])?;
445		for (level, level_indices) in self.levels.iter().zip(indices).skip(1) {
446			let codes = level.lookup(level_indices)?;
447			if codes.shape() != total.shape() {
448				return Err(Error::invalid_argument(
449					"residual VQ token shapes must match",
450				));
451			}
452			total = core_matrix::add(&total, &codes)?;
453		}
454		Ok(total)
455	}
456
457	/// Greedily seed each codebook from the residual left by preceding levels.
458	///
459	/// # Errors
460	///
461	/// Returns an error when a level cannot be seeded or residual recording fails.
462	pub fn seed(&self, latents: &Matrix) -> Result<()> {
463		let mut residual = latents.clone();
464		for level in &self.levels {
465			level.seed(&residual)?;
466			let assignment = matrix::vq_assign(&residual, &level.codebook())?;
467			residual = core_matrix::sub(&residual, &assignment.quantized)?;
468		}
469		Ok(())
470	}
471
472	/// Return the number of quantization levels.
473	pub fn num_levels(&self) -> usize {
474		self.levels.len()
475	}
476
477	/// Return one level by index.
478	pub fn level(&self, index: usize) -> Option<&VectorQuantizer> {
479		self.levels.get(index).map(Rc::as_ref)
480	}
481}
482
483impl Module for ResidualVectorQuantizer {
484	fn forward(&self, input: &Matrix) -> Result<Matrix> {
485		Ok(self.quantize(input)?.quantized)
486	}
487
488	fn registry(&self) -> &ModuleRegistry {
489		&self.registry
490	}
491}
492
493fn validate_config(config: VectorQuantizerConfig) -> Result<()> {
494	if config.num_codes == 0
495		|| config.code_dim == 0
496		|| !config.commitment_beta.is_finite()
497		|| config.commitment_beta < 0.0
498		|| !config.ema_decay.is_finite()
499		|| !(0.0..=1.0).contains(&config.ema_decay)
500		|| !config.ema_epsilon.is_finite()
501		|| config.ema_epsilon <= 0.0
502		|| !config.dead_threshold.is_finite()
503		|| config.dead_threshold < 0.0
504	{
505		return Err(Error::invalid_argument(
506			"invalid vector-quantizer configuration",
507		));
508	}
509	Ok(())
510}