ml: gemma4 sampling draws from 64 native candidates, not 1 MB of logits
- Commit
4337300a6a7b8f3452087ffb8668dc8c9ebf9a6a- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 00:46 UTC (1 month ago)
- Parents
a52c520
Diff
library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.ktindex 63cfad38b4..d749993f6b 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt@@ -340,13 +340,19 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose return decode(produced.toIntArray()) } - /** One generation step: greedy native step, or a sampled draw from fresh logits. */+ /** One generation step: greedy native step, or a sampled draw from native candidates. */ private fun nextToken(next: Int, sampling: Sampling?, step: Int): Int? {- val token = if (sampling == null) {- MlNative.stepGemma4(handle, next)- } else {- val logits = MlNative.logitsGemma4(handle, next) ?: return null- sampleGemma4Logits(logits, sampling, step)+ val token = when {+ sampling == null -> MlNative.stepGemma4(handle, next)+ sampling.topK in 1..GEMMA4_TOP_K_CANDIDATES -> {+ val candidates =+ MlNative.topKGemma4(handle, next, GEMMA4_TOP_K_CANDIDATES) ?: return null+ sampleGemma4Candidates(candidates, sampling, step)+ }+ else -> {+ val logits = MlNative.logitsGemma4(handle, next) ?: return null+ sampleGemma4Logits(logits, sampling, step)+ } } return if (token < 0) null else token }
library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Sampling.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Sampling.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Sampling.ktindex 795f3ccebb..e58ee21ff0 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Sampling.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Sampling.kt@@ -74,19 +74,41 @@ private fun softmaxWeights( logits: FloatArray, pool: List<Int>, temperature: Float-): DoubleArray {+): DoubleArray = softmaxOver(pool.map { logits[it] }, temperature)++/** Candidates [MlNative.topKGemma4] returns per step; covers [Sampling.Chat]'s top_k. */+const val GEMMA4_TOP_K_CANDIDATES = 64++/**+ * [sampleGemma4Logits] over [MlNative.topKGemma4]'s `[logit, id, ...]` candidates, highest+ * first. Draws exactly the token [sampleGemma4Logits] would from the full logits whenever+ * `config.topK` is at most the candidate count: the pool, its weights and the draw are the same.+ */+fun sampleGemma4Candidates(candidates: FloatArray, config: Sampling, step: Int): Int {+ if (candidates.size < 2) return EMPTY_LOGITS_TOKEN+ val count = candidates.size / 2+ val ids = List(count) { candidates[it * 2 + 1].toInt() }+ if (config.temperature <= 0f || (config.topK <= 1 && config.topP >= 1f)) return ids[0]+ val take = if (config.topK in 1 until count) config.topK else count+ val pool = ids.subList(0, take)+ val weights = softmaxOver(List(take) { candidates[it * 2] }, config.temperature)+ val kept = topPKept(weights, config.topP)+ return drawFromPool(pool, weights, kept, config.seed + step)+}++private fun softmaxOver(values: List<Float>, temperature: Float): DoubleArray { val invTemp = 1f / temperature var peak = Float.NEGATIVE_INFINITY- for (index in pool) {- val scaled = logits[index] * invTemp+ for (value in values) {+ val scaled = value * invTemp if (scaled > peak) peak = scaled } // `exp(top - peak)`: shifting by the peak keeps the largest term at 1 rather than // overflowing, and monotonicity means the ordering is unchanged.- val mass = DoubleArray(pool.size)+ val mass = DoubleArray(values.size) var total = 0.0- for (at in pool.indices) {- val weight = exp((logits[pool[at]] * invTemp - peak).toDouble())+ for (at in values.indices) {+ val weight = exp((values[at] * invTemp - peak).toDouble()) mass[at] = weight total += weight }
library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.ktindex 16744c086b..1d5912310e 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt@@ -677,6 +677,14 @@ internal object MlNative { */ external fun logitsGemma4(handle: Long, token: Int): FloatArray? + /**+ * Feed one token and return its [k] most likely next tokens as `[logit, id, logit, id, ...]`,+ * highest first, ties by lower id - the order [sampleGemma4Logits] sorts the full logits into,+ * so [sampleGemma4Candidates] draws the same token whenever `topK <= k`. 2k floats instead of+ * [logitsGemma4]'s 1 MB. Null on failure.+ */+ external fun topKGemma4(handle: Long, token: Int, k: Int): FloatArray?+ /** Positions currently in the KV cache, or -1. */ external fun positionGemma4(handle: Long): Int
library/ml/src/main/rust/src/bridge_part9.rs
diff --git a/library/ml/src/main/rust/src/bridge_part9.rs b/library/ml/src/main/rust/src/bridge_part9.rsindex 19961bfb5c..c5a6511d60 100644--- a/library/ml/src/main/rust/src/bridge_part9.rs+++ b/library/ml/src/main/rust/src/bridge_part9.rs@@ -175,3 +175,78 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyGe // SAFETY: the caller guarantees this runs once, after every other call on the handle. drop(unsafe { Box::from_raw(handle as *mut Gemma4AudioHandle) }); }++/// Feed one token and return its `k` most likely next tokens as `[logit, id, logit, id, ...]`,+/// highest first, ties by lower id - the order a stable descending sort of the full logits gives,+/// so sampling from these candidates draws exactly what sampling the full array would whenever+/// `top_k <= k`. 2k floats cross the boundary instead of 262,144. Null on failure.+///+/// # Safety+///+/// Called only by the JVM, with a live handle from `createGemma4`.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_topKGemma4<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ handle: jlong,+ token: jint,+ k: jint,+) -> jfloatArray {+ env.with_env(|env| -> jni::errors::Result<jfloatArray> {+ if handle == 0 {+ return Ok(std::ptr::null_mut());+ }+ // SAFETY: the caller guarantees the handle came from `createGemma4` and is still live.+ let handle = unsafe { &mut *(handle as *mut Gemma4Handle) };+ let (Ok(token), Ok(k)) = (u32::try_from(token), usize::try_from(k)) else {+ log(&format!("gemma4 top-k was given token {token}, k {k}"));+ return Ok(std::ptr::null_mut());+ };+ if token >= gemma4::VOCAB || k == 0 {+ log(&format!("gemma4 top-k was given token {token}, k {k}"));+ return Ok(std::ptr::null_mut());+ }+ let picked = handle+ .step(token, true)+ .and_then(|logits| logits.ok_or_else(|| "a decode step returned no logits".to_string()))+ .map(|logits| top_k_pairs(&logits, k));+ Ok(match picked {+ Ok(pairs) => match new_float_array(env, &pairs) {+ Ok(array) => array,+ Err(e) => {+ log(&format!("gemma4 cannot return its candidates: {e}"));+ std::ptr::null_mut()+ }+ },+ Err(e) => {+ log(&format!("gemma4 top-k step failed: {e}"));+ std::ptr::null_mut()+ }+ })+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++/// The `k` largest of `logits` as `[logit, id, ...]`, descending, ties by lower id. Ids are below+/// 2^24, so they are exact as `f32`.+fn top_k_pairs(logits: &[f32], k: usize) -> Vec<f32> {+ let order = |a: &u32, b: &u32| logits[*b as usize].total_cmp(&logits[*a as usize]).then(a.cmp(b));+ let mut ids: Vec<u32> = (0..logits.len() as u32).collect();+ let k = k.min(ids.len());+ if k < ids.len() {+ ids.select_nth_unstable_by(k - 1, order);+ ids.truncate(k);+ }+ ids.sort_unstable_by(order);+ ids.iter().flat_map(|&id| [logits[id as usize], id as f32]).collect()+}++#[cfg(test)]+mod top_k_tests {+ #[test]+ fn candidates_come_highest_first_with_ties_by_lower_id() {+ let logits = [0.5, 2.0, -1.0, 2.0, 1.5, 0.5];+ assert_eq!(super::top_k_pairs(&logits, 4), vec![2.0, 1.0, 2.0, 3.0, 1.5, 4.0, 0.5, 0.0]);+ assert_eq!(super::top_k_pairs(&logits, 9).len(), 12, "k past the vocabulary keeps all");+ }+}\ No newline at end of file
library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4SamplingTest.kt
diff --git a/library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4SamplingTest.kt b/library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4SamplingTest.ktindex 77ff3d62ca..16bf30f53c 100644--- a/library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4SamplingTest.kt+++ b/library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4SamplingTest.kt@@ -95,4 +95,32 @@ class Gemma4SamplingTest { assertTrue(token == 0 || token == 1, "draw outside the vocabulary: $token") }++ /** `[logit, id, ...]` for the [k] largest, ties by lower id, as `topKGemma4` returns them. */+ private fun candidates(logits: FloatArray, k: Int): FloatArray {+ val order = logits.indices.sortedByDescending { logits[it] }.take(k)+ return FloatArray(order.size * 2) { if (it % 2 == 0) logits[order[it / 2]] else order[it / 2].toFloat() }+ }++ @Test+ fun `sampling the native candidates draws what sampling the full logits draws`() {+ val random = kotlin.random.Random(11)+ val logits = FloatArray(4096) { (random.nextFloat() * 8f).let { v -> if (it % 97 == 0) 7.5f else v } }+ val configs = listOf(+ Sampling.Chat,+ Sampling(topK = 64, topP = 1.0f, temperature = 0.7f, seed = 3L),+ Sampling(topK = 10, topP = 0.5f, temperature = 1.3f, seed = 8L),+ Sampling.Greedy,+ )+ val native = candidates(logits, GEMMA4_TOP_K_CANDIDATES)+ for (config in configs) {+ for (step in 0 until 50) {+ assertEquals(+ sampleGemma4Logits(logits, config, step),+ sampleGemma4Candidates(native, config, step),+ "$config step $step",+ )+ }+ }+ } }