STRA-338 size4 s10: wrap wide comments, split long tests and numeric proofs into helpers, move retained-handoff checks to a child file

This commit is contained in:
Pavlo Ratushnyi
2026-11-07 10:32:06 +01:00
parent 5b77c18213
commit 7ee092b641
34 changed files with 1117 additions and 833 deletions
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn read_layer_attention, fn prepare_layer_attention_micro, fn validate_layer_plan, fn validate_descriptors.
//! Moved out of the parent module by STRA-338: fn read_layer_attention, fn prepare_layer_attention_micro, fn
//! validate_layer_plan, fn validate_descriptors.
#[allow(unused_imports)]
use super::*;
@@ -27,33 +27,106 @@ fn topology_validation_requires_the_exact_contiguous_closed_sequence() {
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[test]
#[ignore = "requires the two exact pinned IQ3_S GGUF shards and an available NVIDIA GPU"]
fn pinned_artifact_refuses_missing_output_before_layers_without_state_commit() {
mod pinned {
use super::*;
use crate::model_binding::qwen4exp_input::ModelBinding;
use leleka_cuda_driver::Driver;
use leleka_model_format::{gguf::VerifiedGgufFile, qwen4exp::Qwen4ExpArtifact};
use std::{env, path::PathBuf, rc::Rc};
use std::{env, path::PathBuf};
const SHARD0_SHA256: &str = "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3";
const SHARD1_SHA256: &str = "sha256:316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113";
// Paths are supplied only by the operator for this ignored test; the
// artifact identities remain fixed in source and cannot be overridden.
let shard0_path = env::var_os("LELEKA_STRA169_IQ3S_SHARD0")
.map(PathBuf::from)
.unwrap_or_else(|| panic!("missing pinned shard 0 test path"));
let shard1_path = env::var_os("LELEKA_STRA169_IQ3S_SHARD1")
.map(PathBuf::from)
.unwrap_or_else(|| panic!("missing pinned shard 1 test path"));
/// Paths are supplied only by the operator for the ignored tests; the
/// artifact identities remain fixed in source and cannot be overridden.
pub(super) fn bind_refusal_binding() -> ModelBinding {
let shard0_path = env::var_os("LELEKA_STRA169_IQ3S_SHARD0")
.map(PathBuf::from)
.unwrap_or_else(|| panic!("missing pinned shard 0 test path"));
let shard1_path = env::var_os("LELEKA_STRA169_IQ3S_SHARD1")
.map(PathBuf::from)
.unwrap_or_else(|| panic!("missing pinned shard 1 test path"));
let shard0 = VerifiedGgufFile::open(&shard0_path, SHARD0_SHA256)
.unwrap_or_else(|_| panic!("pinned shard 0 verification failed"));
let shard1 = VerifiedGgufFile::open(&shard1_path, SHARD1_SHA256)
.unwrap_or_else(|_| panic!("pinned shard 1 verification failed"));
let artifact = Qwen4ExpArtifact::bind(shard0, shard1)
.unwrap_or_else(|error| panic!("pinned Qwen artifact binding failed: {error}"));
let binding = ModelBinding::from_artifact(artifact).unwrap_or_else(|_| panic!("pinned runtime binding failed"));
let shard0 = VerifiedGgufFile::open(&shard0_path, SHARD0_SHA256)
.unwrap_or_else(|_| panic!("pinned shard 0 verification failed"));
let shard1 = VerifiedGgufFile::open(&shard1_path, SHARD1_SHA256)
.unwrap_or_else(|_| panic!("pinned shard 1 verification failed"));
let artifact = Qwen4ExpArtifact::bind(shard0, shard1)
.unwrap_or_else(|error| panic!("pinned Qwen artifact binding failed: {error}"));
ModelBinding::from_artifact(artifact).unwrap_or_else(|_| panic!("pinned runtime binding failed"))
}
/// Neither the supplied path nor the test can override the model identity.
pub(super) fn bind_commit_binding() -> ModelBinding {
let path = |name| env::var_os(name).map(PathBuf::from).expect("missing pinned test path");
let shard0 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0_SHA256)
.expect("pinned shard 0 verification failed");
let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1_SHA256)
.expect("pinned shard 1 verification failed");
let artifact = Qwen4ExpArtifact::bind(shard0, shard1)
.unwrap_or_else(|error| panic!("pinned artifact binding failed: {error}"));
ModelBinding::from_artifact(artifact).expect("runtime binding failed")
}
/// Every bound layer's prior sits at `next` (the layer kind selects the state family).
pub(super) fn assert_layer_priors(txn: &mut QwenStepTxn<'_, '_>, binding: &ModelBinding, next: u64) -> Result<()> {
let layers = Dimension::new(u64::from(binding.layer_count()))?;
for descriptor in binding.ordered_layers() {
let layer = LayerId::new(u64::from(descriptor.index()), layers)?;
match descriptor.kind() {
BoundLayerKind::Gdn => assert_eq!(txn.gdn_prior(layer)?.next_position(), next),
BoundLayerKind::Qsa => assert_eq!(txn.qsa_prior(layer)?.next_position(), next),
}
}
Ok(())
}
/// Verify rollback in a no-GPU transaction at the same position. The
/// deliberate error keeps this inspection transaction unpublished.
pub(super) fn probe_fresh_state(
session: &mut QwenSession<'_>,
binding: &ModelBinding,
token: TokenId,
position: Position,
) -> Result<TokenId> {
let identity = binding.identity();
session.transact(token, position, &identity, |txn| {
assert_eq!(txn.input_predecessors()?, [-1, -1]);
assert_layer_priors(txn, binding, 0)?;
assert_eq!(txn.ple_prior()?.next_position(), 0);
Err(Error::NonFinite)
})
}
/// Inspect the state two committed tokens left behind; the inspection transaction is never published.
pub(super) fn inspect_committed_state(
session: &mut QwenSession<'_>,
binding: &ModelBinding,
vocabulary: Dimension,
context_length: Dimension,
) -> Result<TokenId> {
let identity = binding.identity();
session.transact(
TokenId::new(1, vocabulary).unwrap(),
Position::new(2, context_length).unwrap(),
&identity,
|txn| {
assert_eq!(txn.input_predecessors()?, [0, 1]);
assert_eq!(txn.ple_prior()?.next_position(), 2);
assert_layer_priors(txn, binding, 2)?;
Err(Error::NonFinite)
},
)
}
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[test]
#[ignore = "requires the two exact pinned IQ3_S GGUF shards and an available NVIDIA GPU"]
fn pinned_artifact_refuses_missing_output_before_layers_without_state_commit() {
use leleka_cuda_driver::Driver;
use std::rc::Rc;
let binding = pinned::bind_refusal_binding();
let driver = Driver::load().unwrap_or_else(|_| panic!("CUDA driver load failed"));
let device = driver.device(0).unwrap_or_else(|_| panic!("CUDA device selection failed"));
@@ -63,24 +136,9 @@ fn pinned_artifact_refuses_missing_output_before_layers_without_state_commit() {
let token = TokenId::new(0, Dimension::new(248_320).unwrap()).unwrap();
let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap();
let identity = binding.identity();
assert_eq!(QwenForward::step(&binding, token, position, &mut session), Err(Error::Unsupported(Stage::Output)));
// Verify rollback in a no-GPU transaction at the same position. The
// deliberate error keeps this inspection transaction unpublished.
let state_probe = session.transact(token, position, &identity, |txn| {
assert_eq!(txn.input_predecessors()?, [-1, -1]);
let layers = Dimension::new(u64::from(binding.layer_count()))?;
for descriptor in binding.ordered_layers() {
let layer = LayerId::new(u64::from(descriptor.index()), layers)?;
match descriptor.kind() {
BoundLayerKind::Gdn => assert_eq!(txn.gdn_prior(layer)?.next_position(), 0),
BoundLayerKind::Qsa => assert_eq!(txn.qsa_prior(layer)?.next_position(), 0),
}
}
assert_eq!(txn.ple_prior()?.next_position(), 0);
Err(Error::NonFinite)
});
let state_probe = pinned::probe_fresh_state(&mut session, &binding, token, position);
assert_eq!(state_probe, Err(Error::NonFinite));
}
@@ -88,26 +146,10 @@ fn pinned_artifact_refuses_missing_output_before_layers_without_state_commit() {
#[test]
#[ignore = "requires exact pinned shards, qualified QSA assets and an available NVIDIA GPU"]
fn pinned_artifact_two_tokens_finish_all_layers_and_commit_state() {
use crate::model_binding::qwen4exp_input::ModelBinding;
use leleka_cuda_driver::Driver;
use leleka_model_format::{gguf::VerifiedGgufFile, qwen4exp::Qwen4ExpArtifact};
use std::{env, path::PathBuf, rc::Rc};
use std::rc::Rc;
let path = |name| env::var_os(name).map(PathBuf::from).expect("missing pinned test path");
// Neither the supplied path nor the test can override the model identity.
let shard0 = VerifiedGgufFile::open(
&path("LELEKA_STRA169_IQ3S_SHARD0"),
"sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3",
)
.expect("pinned shard 0 verification failed");
let shard1 = VerifiedGgufFile::open(
&path("LELEKA_STRA169_IQ3S_SHARD1"),
"sha256:316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113",
)
.expect("pinned shard 1 verification failed");
let artifact = Qwen4ExpArtifact::bind(shard0, shard1)
.unwrap_or_else(|error| panic!("pinned artifact binding failed: {error}"));
let binding = ModelBinding::from_artifact(artifact).expect("runtime binding failed");
let binding = pinned::bind_commit_binding();
eprintln!("integration: exact artifact and all role descriptors bound");
let driver = Driver::load().expect("CUDA driver load failed");
@@ -128,24 +170,6 @@ fn pinned_artifact_two_tokens_finish_all_layers_and_commit_state() {
assert!(greedy.get() < 248_320);
eprintln!("integration: 48 layers and finite head completed at {}, greedy={}", position.get(), greedy.get());
}
let identity = binding.identity();
let inspected = session.transact(
TokenId::new(1, vocabulary).unwrap(),
Position::new(2, context_length).unwrap(),
&identity,
|txn| {
assert_eq!(txn.input_predecessors()?, [0, 1]);
assert_eq!(txn.ple_prior()?.next_position(), 2);
let layers = Dimension::new(u64::from(binding.layer_count()))?;
for descriptor in binding.ordered_layers() {
let layer = LayerId::new(u64::from(descriptor.index()), layers)?;
match descriptor.kind() {
BoundLayerKind::Gdn => assert_eq!(txn.gdn_prior(layer)?.next_position(), 2),
BoundLayerKind::Qsa => assert_eq!(txn.qsa_prior(layer)?.next_position(), 2),
}
}
Err(Error::NonFinite) // Never publish the inspection transaction.
},
);
let inspected = pinned::inspect_committed_state(&mut session, &binding, vocabulary, context_length);
assert_eq!(inspected, Err(Error::NonFinite));
}
@@ -1,4 +1,6 @@
//! Moved out of the parent module by STRA-338: impl Drop_for_OriginalPromptExecutor, impl OriginalPromptPending, impl Drop_for_OriginalPromptPending, impl OriginalPromptHooks_for_NoPromptHooks, impl crate_backend_original_prompt, fn run_original_prompt ....
//! Moved out of the parent module by STRA-338: impl Drop_for_OriginalPromptExecutor, impl OriginalPromptPending, impl
//! Drop_for_OriginalPromptPending, impl OriginalPromptHooks_for_NoPromptHooks, impl crate_backend_original_prompt, fn
//! run_original_prompt ....
#[allow(unused_imports)]
use super::*;
@@ -267,9 +267,10 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
pub(in crate::qwen_forward) fn mtp_idle(&mut self, binding: &ModelBinding) -> Result<()> {
self.mtp_actor(binding)?.idle().map_err(driver_error)
}
/// End of a request's verifier: release what the MTP drafter bound to that verifier's bank (its cached round programs read the
/// bank's final-R span and its tail keeps the last staged window), so the bank can close and the next request's first draft
/// captures against its own bank. See `OriginalMtpActor::release_verifier_bindings`.
/// End of a request's verifier: release what the MTP drafter bound to that verifier's bank (its cached round
/// programs read the bank's final-R span and its tail keeps the last staged window), so the bank can close and
/// the next request's first draft captures against its own bank. See
/// `OriginalMtpActor::release_verifier_bindings`.
pub(in crate::qwen_forward) fn mtp_release_verifier(&mut self, binding: &ModelBinding) -> Result<()> {
self.mtp_actor(binding)?.release_verifier_bindings().map_err(driver_error)
}
@@ -89,9 +89,8 @@ mod tests {
assert_eq!(driver_error(DriverError::UnsupportedQwenOperation), Error::Unsupported(Stage::Gdn));
assert_eq!(driver_error(DriverError::ContextPoisoned), Error::CudaExecution);
}
#[test]
fn branch_free_finite_check_equals_is_finite() {
let specials = [
fn finite_specials() -> [f32; 12] {
[
0.0f32,
-0.0,
1.0,
@@ -104,20 +103,27 @@ mod tests {
f32::from_bits(0x7fc0_0001),
f32::from_bits(0xffc0_0000),
f32::from_bits(0x7f80_0001),
];
for len in [0usize, 1, 3, 8191, 8192, 8193, 20000] {
let clean: Vec<f32> = (0..len).map(|i| specials[i % 6]).collect();
assert_eq!(all_finite(&clean), clean.iter().all(|v| v.is_finite()));
assert!(all_finite(&clean));
for (at, bad) in [(0usize, 6usize), (len / 2, 8), (len.saturating_sub(1), 10), (len / 3, 11)] {
if len == 0 {
continue;
}
let mut values = clean.clone();
values[at.min(len - 1)] = specials[bad];
assert_eq!(all_finite(&values), values.iter().all(|v| v.is_finite()), "len {len} at {at}");
assert!(!all_finite(&values));
]
}
fn assert_finite_scan_agrees(specials: &[f32; 12], len: usize) {
let clean: Vec<f32> = (0..len).map(|i| specials[i % 6]).collect();
assert_eq!(all_finite(&clean), clean.iter().all(|v| v.is_finite()));
assert!(all_finite(&clean));
for (at, bad) in [(0usize, 6usize), (len / 2, 8), (len.saturating_sub(1), 10), (len / 3, 11)] {
if len == 0 {
continue;
}
let mut values = clean.clone();
values[at.min(len - 1)] = specials[bad];
assert_eq!(all_finite(&values), values.iter().all(|v| v.is_finite()), "len {len} at {at}");
assert!(!all_finite(&values));
}
}
#[test]
fn branch_free_finite_check_equals_is_finite() {
let specials = finite_specials();
for len in [0usize, 1, 3, 8191, 8192, 8193, 20000] {
assert_finite_scan_agrees(&specials, len);
}
assert_eq!(validate_values(&[1.0, f32::NAN], 2), Err(Error::NonFinite));
assert_eq!(validate_values(&[1.0], 2), Err(Error::InvalidDimension));
@@ -137,40 +143,39 @@ mod tests {
}
assert_eq!(key_head(48), Err(Error::InvalidDimension));
}
#[test]
fn every_candidate_validates_before_ready_publication() {
let prior = vec![-0.0_f32; STATE_ELEMENTS];
let prior_bits: Vec<_> = prior.iter().map(|v| v.to_bits()).collect();
for target in 0..3 {
let mut state = vec![0.0; STATE_ELEMENTS];
let mut history = vec![0.0; HISTORY_ELEMENTS];
let mut output = vec![0.0; 2560];
let values = match target {
0 => &mut state,
1 => &mut history,
_ => &mut output,
};
*values.last_mut().unwrap() = f32::from_bits(0x7fc0_0000);
assert!(matches!(
validate_candidates(
identity(),
state.into_boxed_slice(),
history.into_boxed_slice(),
output.into_boxed_slice()
),
Err(Error::NonFinite)
));
assert_eq!(prior.iter().map(|v| v.to_bits()).collect::<Vec<_>>(), prior_bits);
}
fn assert_poisoned_candidate_refused(target: usize, prior: &[f32], prior_bits: &[u32]) {
let mut state = vec![0.0; STATE_ELEMENTS];
let mut history = vec![0.0; HISTORY_ELEMENTS];
let mut output = vec![0.0; 2560];
let values = match target {
0 => &mut state,
1 => &mut history,
_ => &mut output,
};
*values.last_mut().unwrap() = f32::from_bits(0x7fc0_0000);
assert!(matches!(
validate_candidates(
identity(),
prior.clone().into_boxed_slice(),
state.into_boxed_slice(),
history.into_boxed_slice(),
output.into_boxed_slice()
),
Err(Error::NonFinite)
));
assert_eq!(prior.iter().map(|v| v.to_bits()).collect::<Vec<_>>(), prior_bits);
}
fn assert_short_history_refused(prior: &[f32]) {
assert!(matches!(
validate_candidates(
identity(),
prior.to_vec().into_boxed_slice(),
vec![0.0; HISTORY_ELEMENTS - 1].into_boxed_slice(),
vec![0.0; 2560].into_boxed_slice()
),
Err(Error::InvalidDimension)
));
}
fn assert_clean_candidates_publish(prior: Vec<f32>) {
let ready = validate_candidates(
identity(),
prior.into_boxed_slice(),
@@ -182,6 +187,16 @@ mod tests {
assert!(ready.1.iter().chain(ready.2.iter()).chain(ready.3.iter()).all(|v| v.to_bits() == 0x80000000));
}
#[test]
fn every_candidate_validates_before_ready_publication() {
let prior = vec![-0.0_f32; STATE_ELEMENTS];
let prior_bits: Vec<_> = prior.iter().map(|v| v.to_bits()).collect();
for target in 0..3 {
assert_poisoned_candidate_refused(target, &prior, &prior_bits);
}
assert_short_history_refused(&prior);
assert_clean_candidates_publish(prior);
}
#[test]
fn finite_input_overflow_must_not_hide_behind_sigmoid_zero() {
// CPU failure-domain fact, not a CUDA or whole GDN qualification.
let exponential = 100.0_f32.exp();
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn gates, fn recur, fn out_norm, fn allocate, fn upload, fn pool_enabled ....
//! Moved out of the parent module by STRA-338: fn gates, fn recur, fn out_norm, fn allocate, fn upload, fn
//! pool_enabled ....
#[allow(unused_imports)]
use super::*;
@@ -191,8 +192,9 @@ pub(super) fn upload<'a>(context: &'a Context<'_>, values: &[f32]) -> Result<Dev
buffer.copy_from_owned(bytes).map_err(driver_error)?;
Ok(buffer)
}
/// `LELEKA_PREFILL_GDN_POOL` (on by default, `0` restores the allocation per layer): pooled 3.1 MB state buffers across GDN layers and chunks instead of an
/// allocation and a free per layer, and one finite scan of the downloaded state instead of two. Same values, same refusals.
/// `LELEKA_PREFILL_GDN_POOL` (on by default, `0` restores the allocation per layer): pooled 3.1 MB state buffers
/// across GDN layers and chunks instead of an allocation and a free per layer, and one finite scan of the downloaded
/// state instead of two. Same values, same refusals.
pub(in super::super) fn pool_enabled() -> bool {
match POOL_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
0 => return false,
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn project, fn dispatch_projection, fn project_retained, fn convolve, fn normalize_qk.
//! Moved out of the parent module by STRA-338: fn project, fn dispatch_projection, fn project_retained, fn convolve,
//! fn normalize_qk.
use super::gates_fn::{release_with_owned, upload_unless_resident};
#[allow(unused_imports)]
@@ -180,6 +180,134 @@ mod retained_qk_gpu {
Ok(values) => cleanup.map(|()| values),
}
}
struct Fixture<'c> {
context: &'c Context<'c>,
foreign: &'c Context<'c>,
small: &'c Context<'c>,
}
fn bits_differ(a: &[f32], b: &[f32]) -> bool {
a.iter().zip(b.iter()).any(|(a, b)| a.to_bits() != b.to_bits())
}
fn proof_inputs() -> [Vec<f32>; 3] {
let ordinary: Vec<f32> = (0..CHANNELS).map(|i| (i % 23) as f32 / 64. - 11. / 64.).collect();
let mut signed = vec![0.; CHANNELS];
for (i, value) in signed.iter_mut().enumerate() {
if i % 2 == 0 {
*value = -0.;
}
}
let mut changed = ordinary.clone();
changed[4095] = -0.75;
[ordinary, signed, changed]
}
fn repeat_pair<'c>(
context: &'c Context<'c>,
h: &DeviceBuffer<'_>,
retained: &mut Option<DeviceBuffer<'c>>,
) -> Result<usize> {
// Original per-call allocation/zero/projection/readback FIRST.
let expected = original(context, h, false)?;
if retained.is_none() {
*retained = Some(allocate_qk_slot(context)?);
}
let actual = normalize_retained_qk(context, h, retained.as_mut().ok_or(Error::IdentityMismatch)?, 1e-6)?;
if expected.len() != actual.len() || bits_differ(&expected, &actual) {
return Err(Error::IdentityMismatch);
}
Ok(actual.len())
}
fn repeat_input<'c>(
context: &'c Context<'c>,
input: &[f32],
retained: &mut Option<DeviceBuffer<'c>>,
) -> Result<usize> {
let h = raw_h(context, input)?;
let pair = repeat_pair(context, &h, retained);
let cleanup = h.release().map_err(driver_error);
let words = pair?;
cleanup?;
Ok(words)
}
fn refuse_poisoned_tail(context: &Context<'_>, h: &DeviceBuffer<'_>, slot: &mut DeviceBuffer<'_>) -> Result<()> {
// A private proof poisons the unused final tail word. The kernel
// writes only4096 words, so the full finite boundary must refuse.
slot.copy_from_range(QK_BYTES - 4, &f32::NAN.to_le_bytes()).map_err(driver_error)?;
if !matches!(normalize_retained_qk(context, h, slot, 1e-6), Err(Error::NonFinite)) {
return Err(Error::IdentityMismatch);
}
Ok(())
}
fn restore_tail<'c>(context: &'c Context<'c>, h: &DeviceBuffer<'_>, slot: &mut DeviceBuffer<'_>) -> Result<usize> {
slot.copy_from_range(QK_BYTES - 4, &0f32.to_le_bytes()).map_err(driver_error)?;
let expected = original(context, h, false)?;
let actual = normalize_retained_qk(context, h, slot, 1e-6)?;
if bits_differ(&expected, &actual) {
return Err(Error::IdentityMismatch);
}
Ok(actual.len())
}
fn refuse_short<'c>(context: &'c Context<'c>, slot: &mut DeviceBuffer<'_>) -> Result<()> {
let short = raw_h(context, &[0.; CHANNELS - 1])?;
let refused = matches!(normalize_retained_qk(context, &short, slot, 1e-6), Err(Error::InvalidDimension));
let cleanup = short.release().map_err(driver_error);
if !refused {
return Err(Error::IdentityMismatch);
}
cleanup
}
fn refuse_foreign(fixture: &Fixture<'_>, ordinary: &[f32], slot: &mut DeviceBuffer<'_>) -> Result<()> {
let other = raw_h(fixture.foreign, ordinary)?;
let refused = normalize_retained_qk(fixture.context, &other, slot, 1e-6).is_err();
let cleanup = other.release().map_err(driver_error);
if !refused {
return Err(Error::IdentityMismatch);
}
cleanup
}
fn refuse_rivals(fixture: &Fixture<'_>, ordinary: &[f32], slot: &mut DeviceBuffer<'_>) -> Result<()> {
let before = slot.copy_to_owned(QK_BYTES).map_err(driver_error)?;
refuse_short(fixture.context, slot)?;
refuse_foreign(fixture, ordinary, slot)?;
let after = slot.copy_to_owned(QK_BYTES).map_err(driver_error)?;
if before != after {
return Err(Error::IdentityMismatch);
}
Ok(())
}
fn fault_proof<'c>(
fixture: &Fixture<'c>,
ordinary: &[f32],
h: &DeviceBuffer<'_>,
retained: &mut Option<DeviceBuffer<'c>>,
) -> Result<(usize, usize)> {
if !matches!(original(fixture.context, h, true), Err(Error::NonFinite)) {
return Err(Error::IdentityMismatch);
}
let slot = retained.as_mut().ok_or(Error::IdentityMismatch)?;
refuse_poisoned_tail(fixture.context, h, slot)?;
let mut guards = 1;
let words = restore_tail(fixture.context, h, slot)?;
refuse_rivals(fixture, ordinary, slot)?;
guards += 2;
if !matches!(allocate_qk_slot(fixture.small), Err(Error::InputAllocation)) {
return Err(Error::IdentityMismatch);
}
guards += 1;
Ok((words, guards))
}
fn run_proof<'c>(fixture: &Fixture<'c>, retained: &mut Option<DeviceBuffer<'c>>) -> Result<(usize, usize)> {
let [ordinary, signed, changed] = proof_inputs();
let mut words = 0;
for input in [&ordinary, &signed, &changed, &ordinary, &changed, &signed] {
words += repeat_input(fixture.context, input, retained)?;
}
let h = raw_h(fixture.context, &ordinary)?;
let faults = fault_proof(fixture, &ordinary, &h, retained);
let cleanup = h.release().map_err(driver_error);
let (fault_words, guards) = faults?;
cleanup?;
Ok((words + fault_words, guards))
}
#[test]
#[ignore = "Root runs one changed retained QK transport boundary after current model terminal"]
fn original_first_retained_whole_qk_repeat_tail_reset_guards_cleanup() {
@@ -190,92 +318,7 @@ mod retained_qk_gpu {
let foreign = device.create_context(160 * 1024 * 1024).unwrap();
let small = device.create_context(16 * 1024 * 1024).unwrap();
let mut retained = None;
let operation = (|| -> Result<(usize, usize)> {
let ordinary: Vec<f32> = (0..CHANNELS).map(|i| (i % 23) as f32 / 64. - 11. / 64.).collect();
let mut signed = vec![0.; CHANNELS];
for (i, value) in signed.iter_mut().enumerate() {
if i % 2 == 0 {
*value = -0.;
}
}
let mut changed = ordinary.clone();
changed[4095] = -0.75;
let mut words = 0;
let mut guards = 0;
for input in [&ordinary, &signed, &changed, &ordinary, &changed, &signed] {
let h = raw_h(&context, input)?;
let pair = (|| -> Result<()> {
// Original per-call allocation/zero/projection/readback FIRST.
let expected = original(&context, &h, false)?;
if retained.is_none() {
retained = Some(allocate_qk_slot(&context)?);
}
let actual =
normalize_retained_qk(&context, &h, retained.as_mut().ok_or(Error::IdentityMismatch)?, 1e-6)?;
if expected.len() != actual.len()
|| expected.iter().zip(actual.iter()).any(|(a, b)| a.to_bits() != b.to_bits())
{
return Err(Error::IdentityMismatch);
}
words += actual.len();
Ok(())
})();
let cleanup = h.release().map_err(driver_error);
pair?;
cleanup?;
}
let h = raw_h(&context, &ordinary)?;
let faults = (|| -> Result<()> {
if !matches!(original(&context, &h, true), Err(Error::NonFinite)) {
return Err(Error::IdentityMismatch);
}
let slot = retained.as_mut().ok_or(Error::IdentityMismatch)?;
// A private proof poisons the unused final tail word. The kernel
// writes only4096 words, so the full finite boundary must refuse.
slot.copy_from_range(QK_BYTES - 4, &f32::NAN.to_le_bytes()).map_err(driver_error)?;
if !matches!(normalize_retained_qk(&context, &h, slot, 1e-6), Err(Error::NonFinite)) {
return Err(Error::IdentityMismatch);
}
guards += 1;
slot.copy_from_range(QK_BYTES - 4, &0f32.to_le_bytes()).map_err(driver_error)?;
let expected = original(&context, &h, false)?;
let actual = normalize_retained_qk(&context, &h, slot, 1e-6)?;
if expected.iter().zip(actual.iter()).any(|(a, b)| a.to_bits() != b.to_bits()) {
return Err(Error::IdentityMismatch);
}
words += actual.len();
let before = slot.copy_to_owned(QK_BYTES).map_err(driver_error)?;
let short = raw_h(&context, &[0.; CHANNELS - 1])?;
let refused =
matches!(normalize_retained_qk(&context, &short, slot, 1e-6), Err(Error::InvalidDimension));
let cleanup = short.release().map_err(driver_error);
if !refused {
return Err(Error::IdentityMismatch);
}
cleanup?;
let other = raw_h(&foreign, &ordinary)?;
let refused = normalize_retained_qk(&context, &other, slot, 1e-6).is_err();
let cleanup = other.release().map_err(driver_error);
if !refused {
return Err(Error::IdentityMismatch);
}
cleanup?;
let after = slot.copy_to_owned(QK_BYTES).map_err(driver_error)?;
if before != after {
return Err(Error::IdentityMismatch);
}
guards += 2;
if !matches!(allocate_qk_slot(&small), Err(Error::InputAllocation)) {
return Err(Error::IdentityMismatch);
}
guards += 1;
Ok(())
})();
let cleanup = h.release().map_err(driver_error);
faults?;
cleanup?;
Ok((words, guards))
})();
let operation = run_proof(&Fixture { context: &context, foreign: &foreign, small: &small }, &mut retained);
let release = retained.take().map(|buffer| buffer.release()).transpose();
drop(retained);
let allocated = [context.allocated_bytes(), foreign.allocated_bytes(), small.allocated_bytes()];
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn allocate_qk_slot, fn normalize_retained_qk, impl QkScratch, impl Role, impl Product, impl RecurrenceBorrow ....
//! Moved out of the parent module by STRA-338: fn allocate_qk_slot, fn normalize_retained_qk, impl QkScratch, impl
//! Role, impl Product, impl RecurrenceBorrow ....
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn mirror_reuse_enabled, impl ChunkEdge, fn micro_rows, impl ChunkReadout, impl Drop_for_ChunkReadout.
//! Moved out of the parent module by STRA-338: fn mirror_reuse_enabled, impl ChunkEdge, fn micro_rows, impl
//! ChunkReadout, impl Drop_for_ChunkReadout.
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn operands, fn convolution_input, fn convolution_weights, fn difference, fn require, fn reference ....
//! Moved out of the parent module by STRA-338: fn operands, fn convolution_input, fn convolution_weights, fn
//! difference, fn require, fn reference ....
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl GdnBatchResources, fn admit_batch_bytes, impl Drop_for_GdnBatchResources, fn native_format, fn batch_device_bytes, fn f32_bytes.
//! Moved out of the parent module by STRA-338: impl GdnBatchResources, fn admit_batch_bytes, impl
//! Drop_for_GdnBatchResources, fn native_format, fn batch_device_bytes, fn f32_bytes.
#[allow(unused_imports)]
use super::*;
@@ -217,6 +217,29 @@ mod tests {
use super::super::super::contract::{Dimension, TokenId};
use super::*;
fn assert_prior_bound_to_owner(
prior: &GdnPrior,
binding: &BindingIdentity,
owner: &GdnOwner,
layer: LayerId,
pos: Position,
) {
assert_eq!(prior.validate(binding, owner, layer, pos), Ok(()));
assert_eq!(prior.validate(binding, &GdnOwner::new(), layer, pos), Err(Error::IdentityMismatch));
assert_eq!(prior.validate(&BindingIdentity::test_identity(), owner, layer, pos), Err(Error::IdentityMismatch));
}
fn assert_nan_state_refused(prior: &GdnPrior, identity: TokenLayer) {
assert_eq!(
GdnPending::new(
prior,
identity,
vec![f32::NAN; STATE_ELEMENTS].into_boxed_slice(),
zeros(HISTORY_ELEMENTS).unwrap()
)
.err(),
Some(Error::NonFinite)
);
}
#[test]
fn pending_is_bound_to_exact_prior_owner_layer_and_position() {
let binding = BindingIdentity::test_identity();
@@ -225,9 +248,7 @@ mod tests {
let pos = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap();
let identity = TokenLayer::new(TokenId::new(0, Dimension::new(248320).unwrap()).unwrap(), pos, layer);
let prior = GdnPrior::zero(binding.clone(), &owner, layer).unwrap();
assert_eq!(prior.validate(&binding, &owner, layer, pos), Ok(()));
assert_eq!(prior.validate(&binding, &GdnOwner::new(), layer, pos), Err(Error::IdentityMismatch));
assert_eq!(prior.validate(&BindingIdentity::test_identity(), &owner, layer, pos), Err(Error::IdentityMismatch));
assert_prior_bound_to_owner(&prior, &binding, &owner, layer, pos);
let rival = GdnPrior::zero(binding.clone(), &owner, layer).unwrap();
let pending =
GdnPending::new(&prior, identity, zeros(STATE_ELEMENTS).unwrap(), zeros(HISTORY_ELEMENTS).unwrap())
@@ -239,15 +260,6 @@ mod tests {
assert_eq!(prior.next_position(), 0);
assert!(prior.values().iter().chain(prior.history()).all(|v| v.to_bits() == 0));
assert_eq!(next.validate(&binding, &owner, layer, pos), Err(Error::IdentityMismatch));
assert_eq!(
GdnPending::new(
&prior,
identity,
vec![f32::NAN; STATE_ELEMENTS].into_boxed_slice(),
zeros(HISTORY_ELEMENTS).unwrap()
)
.err(),
Some(Error::NonFinite)
);
assert_nan_state_refused(&prior, identity);
}
}
@@ -113,8 +113,9 @@ impl<'ctx> GdnStateMirror<'ctx> {
}
/// The device image of `prior` when this mirror holds exactly that state (identity of the producing state, never a
/// position): the buffer moves to the caller and a fresh one takes its place, so the chunk starts from the very bytes
/// it downloaded as `prior` instead of converting and uploading them again. `adopt_chunk` releases the stand-in.
/// position): the buffer moves to the caller and a fresh one takes its place, so the chunk starts from the very
/// bytes it downloaded as `prior` instead of converting and uploading them again. `adopt_chunk` releases the
/// stand-in.
pub(in super::super::super) fn take_resident_for(
&mut self,
prior: &GdnPrior,
@@ -62,304 +62,8 @@ pub(super) struct PoolRow<'ctx> {
// Numerical transport proof only. This helper owns real CUDA buffers and calls
// the same production recurrence; it does not mint Binding/Row/Prefix authority.
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
mod numeric_gpu {
use super::*;
use leleka_cuda_driver::Driver;
struct Numerical<'ctx> {
prior: Option<DeviceBuffer<'ctx>>,
rolling: [Option<DeviceBuffer<'ctx>>; 2],
operands: Vec<[Option<DeviceBuffer<'ctx>>; 4]>,
readout: Option<DeviceBuffer<'ctx>>,
guard: Option<GdnStateFiniteGuard<'ctx>>,
}
impl<'ctx> Numerical<'ctx> {
fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
let mut owner =
Self { prior: None, rolling: [None, None], operands: Vec::new(), readout: None, guard: None };
let operation = (|| -> Result<()> {
owner.operands.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
for _ in 0..3 {
owner.operands.push([None, None, None, None]);
for (buffer, count) in
owner.operands.last_mut().ok_or(Error::IdentityMismatch)?.iter_mut().zip(COUNTS)
{
*buffer = Some(allocate(context, count)?);
}
}
owner.prior = Some(allocate(context, STATE_ELEMENTS)?);
for state in &mut owner.rolling {
*state = Some(allocate(context, STATE_ELEMENTS)?);
}
owner.readout = Some(allocate(context, VALUES)?);
owner.guard = Some(context.gdn_state_finite_guard().map_err(driver_error)?);
Ok(())
})();
if let Err(primary) = operation {
let _ = owner.close();
return Err(primary);
}
Ok(owner)
}
fn row(
&mut self,
context: &Context<'_>,
index: usize,
input: Option<usize>,
output: usize,
) -> Result<Box<[f32]>> {
let mut next = self.rolling[output].take().ok_or(Error::IdentityMismatch)?;
let operation = (|| {
let state = match input {
Some(slot) => self.rolling[slot].as_ref(),
None => self.prior.as_ref(),
}
.ok_or(Error::IdentityMismatch)?;
let row = self.operands.get(index).ok_or(Error::IdentityMismatch)?;
compute_row(
context,
state,
[
row[0].as_ref().ok_or(Error::IdentityMismatch)?,
row[1].as_ref().ok_or(Error::IdentityMismatch)?,
row[2].as_ref().ok_or(Error::IdentityMismatch)?,
row[3].as_ref().ok_or(Error::IdentityMismatch)?,
],
&mut next,
self.readout.as_mut().ok_or(Error::IdentityMismatch)?,
self.guard.as_mut().ok_or(Error::IdentityMismatch)?,
)
})();
self.rolling[output] = Some(next);
operation
}
fn close(&mut self) -> Result<()> {
let mut primary = None;
if let Some(guard) = self.guard.take()
&& let Err(error) = guard.close()
{
primary.get_or_insert(driver_error(error));
}
for row in &mut self.operands {
for buffer in row {
if let Some(buffer) = buffer.take()
&& let Err(error) = buffer.release()
{
primary.get_or_insert(driver_error(error));
}
}
}
for buffer in
self.rolling.iter_mut().filter_map(Option::take).chain(self.prior.take()).chain(self.readout.take())
{
if let Err(error) = buffer.release() {
primary.get_or_insert(driver_error(error));
}
}
primary.map_or(Ok(()), Err)
}
}
impl Drop for Numerical<'_> {
fn drop(&mut self) {
let _ = self.close();
}
}
fn write(buffer: &mut DeviceBuffer<'_>, values: &[f32]) -> Result<()> {
let mut bytes = Vec::new();
bytes.try_reserve_exact(values.len() * 4).map_err(|_| Error::InputAllocation)?;
for value in values {
bytes.extend_from_slice(&value.to_le_bytes());
}
buffer.copy_from_owned(bytes).map_err(driver_error)
}
// Literal old five-input native recurrence, including its complete state
// D2H finite check BEFORE readout. Always called before candidate execution.
fn original(context: &Context<'_>, state: &[f32], row: &[Vec<f32>; 4]) -> Result<CandidatePair> {
let mut buffers = Vec::new();
buffers.try_reserve_exact(8).map_err(|_| Error::InputAllocation)?;
let operation = (|| -> Result<CandidatePair> {
for values in [state, &row[0][..2048], &row[0][2048..4096], &row[1][4096..], &row[2], &row[3]] {
buffers.push(upload(context, values)?);
}
let mut next = allocate(context, STATE_ELEMENTS)?;
let mut readout = allocate(context, VALUES)?;
let run = (|| {
context
.gdn_step_f32(
&buffers[0],
&buffers[1],
&buffers[2],
&buffers[3],
&buffers[4],
&buffers[5],
&mut next,
&mut readout,
)
.map_err(driver_error)?;
Ok((download(&next, STATE_ELEMENTS)?, download(&readout, VALUES)?))
})();
buffers.push(next);
buffers.push(readout);
run
})();
let mut cleanup = None;
for buffer in buffers {
if let Err(error) = buffer.release() {
cleanup.get_or_insert(driver_error(error));
}
}
operation.and_then(|pair| cleanup.map_or(Ok(pair), Err))
}
fn exact(actual: &[f32], expected: &[f32], words: &mut usize) -> Result<()> {
if actual.len() != expected.len() || actual.iter().zip(expected).any(|(a, b)| a.to_bits() != b.to_bits()) {
return Err(Error::IdentityMismatch);
}
*words = words.checked_add(actual.len()).ok_or(Error::Overflow)?;
Ok(())
}
fn rows(signed_zero: bool) -> [[Vec<f32>; 4]; 3] {
std::array::from_fn(|row| {
std::array::from_fn(|role| {
(0..COUNTS[role])
.map(|index| {
if signed_zero && role < 2 {
if (index + row) % 2 == 0 { -0.0 } else { 0.0 }
} else {
match role {
0 => ((index % 17) as f32 - 8.0) / 128.0 + (row as f32) / 256.0,
1 => ((index % 23) as f32 - 11.0) / 64.0 - (row as f32) / 128.0,
2 => 0.875 + (index % 2) as f32 / 16.0,
_ => 0.25 + (row as f32) / 16.0,
}
}
})
.collect()
})
})
}
#[test]
#[ignore = "Root runs only this changed exact-device journal recurrence boundary"]
fn original_first_three_rows_and_each_accepted_replay_full_state_finite_abort_cleanup() {
assert_eq!(std::env::var("LELEKA_STRA169_RUN_GDN_MTP_JOURNAL").as_deref(), Ok("yes"));
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(192 * 1024 * 1024).unwrap();
let mut owner = None;
let operation = (|| -> Result<(usize, usize)> {
let mut words = 0usize;
let mut guards = 0usize;
for signed_zero in [false, true] {
let prior: Vec<f32> = (0..STATE_ELEMENTS)
.map(|index| {
if signed_zero {
if index % 2 == 0 { -0.0 } else { 0.0 }
} else {
((index % 19) as f32 - 9.0) / 1024.0
}
})
.collect();
let inputs = rows(signed_zero);
let mut expected = Vec::new();
expected.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
// All three genuine causal old results FIRST, not fitted to candidate.
for row in &inputs {
let previous = expected.last().map(|pair: &CandidatePair| pair.0.as_ref()).unwrap_or(&prior);
expected.push(original(&context, previous, row)?);
}
if owner.is_none() {
owner = Some(Numerical::new(&context)?);
}
let workspace = owner.as_mut().ok_or(Error::IdentityMismatch)?;
write(workspace.prior.as_mut().ok_or(Error::IdentityMismatch)?, &prior)?;
for (buffers, row) in workspace.operands.iter_mut().zip(&inputs) {
for (buffer, values) in buffers.iter_mut().zip(row) {
write(buffer.as_mut().ok_or(Error::IdentityMismatch)?, values)?;
}
}
let before = workspace
.prior
.as_ref()
.ok_or(Error::IdentityMismatch)?
.copy_to_owned(STATE_ELEMENTS * 4)
.map_err(driver_error)?;
// Provisional full T3, then discard/replay each real accepted length.
for (index, pair) in expected.iter().enumerate() {
let output = index % 2;
let actual = workspace.row(&context, index, index.checked_sub(1).map(|n| n % 2), output)?;
exact(&actual, &pair.1, &mut words)?;
}
for accepted in 1..=3 {
for (index, pair) in expected.iter().take(accepted).enumerate() {
let actual = workspace.row(&context, index, index.checked_sub(1).map(|n| n % 2), index % 2)?;
exact(&actual, &pair.1, &mut words)?;
}
let actual = download(
workspace.rolling[(accepted - 1) % 2].as_ref().ok_or(Error::IdentityMismatch)?,
STATE_ELEMENTS,
)?;
exact(&actual, &expected[accepted - 1].0, &mut words)?;
}
let after = workspace
.prior
.as_ref()
.ok_or(Error::IdentityMismatch)?
.copy_to_owned(STATE_ELEMENTS * 4)
.map_err(driver_error)?;
if before != after {
return Err(Error::IdentityMismatch);
}
guards += 1; // Abort/rejected prefix scratch never mutated the actual prior.
for bad in [17usize, STATE_ELEMENTS - 17] {
let state = workspace.rolling[0].as_mut().ok_or(Error::IdentityMismatch)?;
state.copy_from_range(bad * 4, &f32::NAN.to_le_bytes()).map_err(driver_error)?;
if !matches!(download(state, STATE_ELEMENTS), Err(Error::NonFinite)) {
return Err(Error::IdentityMismatch);
}
if workspace
.guard
.as_mut()
.ok_or(Error::IdentityMismatch)?
.check_next_state(state)
.map_err(driver_error)?
{
return Err(Error::IdentityMismatch);
}
guards += 1;
write(state, &expected[0].0)?;
if !workspace
.guard
.as_mut()
.ok_or(Error::IdentityMismatch)?
.check_next_state(state)
.map_err(driver_error)?
{
return Err(Error::IdentityMismatch);
}
guards += 1;
}
// A valid row after the final late nonfinite refusal resets guard status.
let actual = workspace.row(&context, 0, None, 0)?;
exact(&actual, &expected[0].1, &mut words)?;
exact(
&download(workspace.rolling[0].as_ref().ok_or(Error::IdentityMismatch)?, STATE_ELEMENTS)?,
&expected[0].0,
&mut words,
)?;
}
Ok((words, guards))
})();
let cleanup = owner.take().map(|mut owner| owner.close()).transpose();
drop(owner);
let allocated = context.allocated_bytes();
let close = context.close();
// Cleanup and Context close precede every final quality assertion.
assert!(cleanup.is_ok());
assert_eq!(allocated, 0);
assert!(close.is_ok());
assert_eq!(operation.unwrap(), (6_414_336, 10));
println!("GDN_MTP_JOURNAL exact_words=6414336 guards=10 allocated=0 numerical_only=true");
}
}
#[path = "gdn_verification/numeric_gpu.rs"]
mod numeric_gpu;
#[path = "gdn_verification/compute_row_fn.rs"]
mod compute_row_fn;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn compute_row, impl ActiveLease, impl VerifiedRow, impl Workspace, impl Drop_for_Workspace, impl ReplaySeal ....
//! Moved out of the parent module by STRA-338: fn compute_row, impl ActiveLease, impl VerifiedRow, impl Workspace,
//! impl Drop_for_Workspace, impl ReplaySeal ....
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl Workspace (2), impl Drop_for_Workspace, impl ReplaySeal, impl PoolRow, impl Drop_for_PoolRow.
//! Moved out of the parent module by STRA-338: impl Workspace (2), impl Drop_for_Workspace, impl ReplaySeal, impl
//! PoolRow, impl Drop_for_PoolRow.
#[allow(unused_imports)]
use super::*;
@@ -0,0 +1,352 @@
//! Numerical transport proof of the MTP verification journal (test-only; moved out of the parent file by STRA-338).
use super::*;
use leleka_cuda_driver::Driver;
struct Numerical<'ctx> {
prior: Option<DeviceBuffer<'ctx>>,
rolling: [Option<DeviceBuffer<'ctx>>; 2],
operands: Vec<[Option<DeviceBuffer<'ctx>>; 4]>,
readout: Option<DeviceBuffer<'ctx>>,
guard: Option<GdnStateFiniteGuard<'ctx>>,
}
impl<'ctx> Numerical<'ctx> {
fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
let mut owner = Self { prior: None, rolling: [None, None], operands: Vec::new(), readout: None, guard: None };
if let Err(primary) = owner.allocate_all(context) {
let _ = owner.close();
return Err(primary);
}
Ok(owner)
}
fn allocate_all(&mut self, context: &'ctx Context<'ctx>) -> Result<()> {
self.allocate_operands(context)?;
self.prior = Some(allocate(context, STATE_ELEMENTS)?);
for state in &mut self.rolling {
*state = Some(allocate(context, STATE_ELEMENTS)?);
}
self.readout = Some(allocate(context, VALUES)?);
self.guard = Some(context.gdn_state_finite_guard().map_err(driver_error)?);
Ok(())
}
fn allocate_operands(&mut self, context: &'ctx Context<'ctx>) -> Result<()> {
self.operands.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
for _ in 0..3 {
self.operands.push([None, None, None, None]);
for (buffer, count) in self.operands.last_mut().ok_or(Error::IdentityMismatch)?.iter_mut().zip(COUNTS) {
*buffer = Some(allocate(context, count)?);
}
}
Ok(())
}
fn row(&mut self, context: &Context<'_>, index: usize, input: Option<usize>, output: usize) -> Result<Box<[f32]>> {
let mut next = self.rolling[output].take().ok_or(Error::IdentityMismatch)?;
let operation = self.compute(context, index, input, &mut next);
self.rolling[output] = Some(next);
operation
}
fn compute(
&mut self,
context: &Context<'_>,
index: usize,
input: Option<usize>,
next: &mut DeviceBuffer<'ctx>,
) -> Result<Box<[f32]>> {
let state = match input {
Some(slot) => self.rolling[slot].as_ref(),
None => self.prior.as_ref(),
}
.ok_or(Error::IdentityMismatch)?;
let row = self.operands.get(index).ok_or(Error::IdentityMismatch)?;
compute_row(
context,
state,
operand_refs(row)?,
next,
self.readout.as_mut().ok_or(Error::IdentityMismatch)?,
self.guard.as_mut().ok_or(Error::IdentityMismatch)?,
)
}
fn close(&mut self) -> Result<()> {
let mut primary = None;
if let Some(guard) = self.guard.take()
&& let Err(error) = guard.close()
{
primary.get_or_insert(driver_error(error));
}
for row in &mut self.operands {
for buffer in row {
if let Some(buffer) = buffer.take()
&& let Err(error) = buffer.release()
{
primary.get_or_insert(driver_error(error));
}
}
}
for buffer in
self.rolling.iter_mut().filter_map(Option::take).chain(self.prior.take()).chain(self.readout.take())
{
if let Err(error) = buffer.release() {
primary.get_or_insert(driver_error(error));
}
}
primary.map_or(Ok(()), Err)
}
}
impl Drop for Numerical<'_> {
fn drop(&mut self) {
let _ = self.close();
}
}
fn operand_refs<'a, 'ctx>(row: &'a [Option<DeviceBuffer<'ctx>>; 4]) -> Result<[&'a DeviceBuffer<'ctx>; 4]> {
Ok([
row[0].as_ref().ok_or(Error::IdentityMismatch)?,
row[1].as_ref().ok_or(Error::IdentityMismatch)?,
row[2].as_ref().ok_or(Error::IdentityMismatch)?,
row[3].as_ref().ok_or(Error::IdentityMismatch)?,
])
}
fn write(buffer: &mut DeviceBuffer<'_>, values: &[f32]) -> Result<()> {
let mut bytes = Vec::new();
bytes.try_reserve_exact(values.len() * 4).map_err(|_| Error::InputAllocation)?;
for value in values {
bytes.extend_from_slice(&value.to_le_bytes());
}
buffer.copy_from_owned(bytes).map_err(driver_error)
}
fn run_gdn_step(
context: &Context<'_>,
buffers: &[DeviceBuffer<'_>],
next: &mut DeviceBuffer<'_>,
readout: &mut DeviceBuffer<'_>,
) -> Result<CandidatePair> {
context
.gdn_step_f32(&buffers[0], &buffers[1], &buffers[2], &buffers[3], &buffers[4], &buffers[5], next, readout)
.map_err(driver_error)?;
Ok((download(next, STATE_ELEMENTS)?, download(readout, VALUES)?))
}
fn step_candidate<'a>(
context: &'a Context<'_>,
buffers: &mut Vec<DeviceBuffer<'a>>,
state: &[f32],
row: &[Vec<f32>; 4],
) -> Result<CandidatePair> {
for values in [state, &row[0][..2048], &row[0][2048..4096], &row[1][4096..], &row[2], &row[3]] {
buffers.push(upload(context, values)?);
}
let mut next = allocate(context, STATE_ELEMENTS)?;
let mut readout = allocate(context, VALUES)?;
let run = run_gdn_step(context, buffers, &mut next, &mut readout);
buffers.push(next);
buffers.push(readout);
run
}
// Literal old five-input native recurrence, including its complete state
// D2H finite check BEFORE readout. Always called before candidate execution.
fn original(context: &Context<'_>, state: &[f32], row: &[Vec<f32>; 4]) -> Result<CandidatePair> {
let mut buffers = Vec::new();
buffers.try_reserve_exact(8).map_err(|_| Error::InputAllocation)?;
let operation = step_candidate(context, &mut buffers, state, row);
let mut cleanup = None;
for buffer in buffers {
if let Err(error) = buffer.release() {
cleanup.get_or_insert(driver_error(error));
}
}
operation.and_then(|pair| cleanup.map_or(Ok(pair), Err))
}
fn exact(actual: &[f32], expected: &[f32], words: &mut usize) -> Result<()> {
if actual.len() != expected.len() || actual.iter().zip(expected).any(|(a, b)| a.to_bits() != b.to_bits()) {
return Err(Error::IdentityMismatch);
}
*words = words.checked_add(actual.len()).ok_or(Error::Overflow)?;
Ok(())
}
fn row_value(signed_zero: bool, row: usize, role: usize, index: usize) -> f32 {
if signed_zero && role < 2 {
if (index + row) % 2 == 0 { -0.0 } else { 0.0 }
} else {
match role {
0 => ((index % 17) as f32 - 8.0) / 128.0 + (row as f32) / 256.0,
1 => ((index % 23) as f32 - 11.0) / 64.0 - (row as f32) / 128.0,
2 => 0.875 + (index % 2) as f32 / 16.0,
_ => 0.25 + (row as f32) / 16.0,
}
}
}
fn rows(signed_zero: bool) -> [[Vec<f32>; 4]; 3] {
std::array::from_fn(|row| {
std::array::from_fn(|role| (0..COUNTS[role]).map(|index| row_value(signed_zero, row, role, index)).collect())
})
}
fn prior_state(signed_zero: bool) -> Vec<f32> {
(0..STATE_ELEMENTS)
.map(
|index| {
if signed_zero { if index % 2 == 0 { -0.0 } else { 0.0 } } else { ((index % 19) as f32 - 9.0) / 1024.0 }
},
)
.collect()
}
/// All three genuine causal old results FIRST, not fitted to candidate.
fn expected_rows(context: &Context<'_>, prior: &[f32], inputs: &[[Vec<f32>; 4]; 3]) -> Result<Vec<CandidatePair>> {
let mut expected = Vec::new();
expected.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
for row in inputs {
let previous = expected.last().map(|pair: &CandidatePair| pair.0.as_ref()).unwrap_or(prior);
expected.push(original(context, previous, row)?);
}
Ok(expected)
}
fn load_workspace(workspace: &mut Numerical<'_>, prior: &[f32], inputs: &[[Vec<f32>; 4]; 3]) -> Result<()> {
write(workspace.prior.as_mut().ok_or(Error::IdentityMismatch)?, prior)?;
for (buffers, row) in workspace.operands.iter_mut().zip(inputs) {
for (buffer, values) in buffers.iter_mut().zip(row) {
write(buffer.as_mut().ok_or(Error::IdentityMismatch)?, values)?;
}
}
Ok(())
}
fn prior_bytes(workspace: &Numerical<'_>) -> Result<Vec<u8>> {
workspace.prior.as_ref().ok_or(Error::IdentityMismatch)?.copy_to_owned(STATE_ELEMENTS * 4).map_err(driver_error)
}
fn replay_accepted(
workspace: &mut Numerical<'_>,
context: &Context<'_>,
expected: &[CandidatePair],
accepted: usize,
words: &mut usize,
) -> Result<()> {
for (index, pair) in expected.iter().take(accepted).enumerate() {
let actual = workspace.row(context, index, index.checked_sub(1).map(|n| n % 2), index % 2)?;
exact(&actual, &pair.1, words)?;
}
let actual =
download(workspace.rolling[(accepted - 1) % 2].as_ref().ok_or(Error::IdentityMismatch)?, STATE_ELEMENTS)?;
exact(&actual, &expected[accepted - 1].0, words)
}
/// Provisional full T3, then discard/replay each real accepted length.
fn replay_rows(
workspace: &mut Numerical<'_>,
context: &Context<'_>,
expected: &[CandidatePair],
words: &mut usize,
) -> Result<()> {
for (index, pair) in expected.iter().enumerate() {
let output = index % 2;
let actual = workspace.row(context, index, index.checked_sub(1).map(|n| n % 2), output)?;
exact(&actual, &pair.1, words)?;
}
for accepted in 1..=3 {
replay_accepted(workspace, context, expected, accepted, words)?;
}
Ok(())
}
fn guard_check(guard: &mut Option<GdnStateFiniteGuard<'_>>, state: &DeviceBuffer<'_>) -> Result<bool> {
guard.as_mut().ok_or(Error::IdentityMismatch)?.check_next_state(state).map_err(driver_error)
}
fn refuse_late_nonfinite(
workspace: &mut Numerical<'_>,
bad: usize,
replacement: &[f32],
guards: &mut usize,
) -> Result<()> {
let state = workspace.rolling[0].as_mut().ok_or(Error::IdentityMismatch)?;
state.copy_from_range(bad * 4, &f32::NAN.to_le_bytes()).map_err(driver_error)?;
if !matches!(download(state, STATE_ELEMENTS), Err(Error::NonFinite)) {
return Err(Error::IdentityMismatch);
}
if guard_check(&mut workspace.guard, state)? {
return Err(Error::IdentityMismatch);
}
*guards += 1;
write(state, replacement)?;
if !guard_check(&mut workspace.guard, state)? {
return Err(Error::IdentityMismatch);
}
*guards += 1;
Ok(())
}
/// A valid row after the final late nonfinite refusal resets guard status.
fn reset_row(
workspace: &mut Numerical<'_>,
context: &Context<'_>,
expected: &CandidatePair,
words: &mut usize,
) -> Result<()> {
let actual = workspace.row(context, 0, None, 0)?;
exact(&actual, &expected.1, words)?;
exact(&download(workspace.rolling[0].as_ref().ok_or(Error::IdentityMismatch)?, STATE_ELEMENTS)?, &expected.0, words)
}
fn bind_workspace<'a, 'c>(
context: &'c Context<'c>,
owner: &'a mut Option<Numerical<'c>>,
) -> Result<&'a mut Numerical<'c>> {
if owner.is_none() {
*owner = Some(Numerical::new(context)?);
}
owner.as_mut().ok_or(Error::IdentityMismatch)
}
fn replay_preserving_prior(
workspace: &mut Numerical<'_>,
context: &Context<'_>,
expected: &[CandidatePair],
words: &mut usize,
) -> Result<()> {
let before = prior_bytes(workspace)?;
replay_rows(workspace, context, expected, words)?;
let after = prior_bytes(workspace)?;
if before != after {
return Err(Error::IdentityMismatch);
}
Ok(())
}
#[derive(Default)]
struct Tally {
words: usize,
guards: usize,
}
fn check_variant<'c>(
context: &'c Context<'c>,
owner: &mut Option<Numerical<'c>>,
signed_zero: bool,
tally: &mut Tally,
) -> Result<()> {
let prior = prior_state(signed_zero);
let inputs = rows(signed_zero);
let expected = expected_rows(context, &prior, &inputs)?;
let workspace = bind_workspace(context, owner)?;
load_workspace(workspace, &prior, &inputs)?;
replay_preserving_prior(workspace, context, &expected, &mut tally.words)?;
tally.guards += 1; // Abort/rejected prefix scratch never mutated the actual prior.
for bad in [17usize, STATE_ELEMENTS - 17] {
refuse_late_nonfinite(workspace, bad, &expected[0].0, &mut tally.guards)?;
}
reset_row(workspace, context, &expected[0], &mut tally.words)
}
fn run_journal<'c>(context: &'c Context<'c>, owner: &mut Option<Numerical<'c>>) -> Result<(usize, usize)> {
let mut tally = Tally::default();
for signed_zero in [false, true] {
check_variant(context, owner, signed_zero, &mut tally)?;
}
Ok((tally.words, tally.guards))
}
#[test]
#[ignore = "Root runs only this changed exact-device journal recurrence boundary"]
fn original_first_three_rows_and_each_accepted_replay_full_state_finite_abort_cleanup() {
assert_eq!(std::env::var("LELEKA_STRA169_RUN_GDN_MTP_JOURNAL").as_deref(), Ok("yes"));
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(192 * 1024 * 1024).unwrap();
let mut owner = None;
let operation = run_journal(&context, &mut owner);
let cleanup = owner.take().map(|mut owner| owner.close()).transpose();
drop(owner);
let allocated = context.allocated_bytes();
let close = context.close();
// Cleanup and Context close precede every final quality assertion.
assert!(cleanup.is_ok());
assert_eq!(allocated, 0);
assert!(close.is_ok());
assert_eq!(operation.unwrap(), (6_414_336, 10));
println!("GDN_MTP_JOURNAL exact_words=6414336 guards=10 allocated=0 numerical_only=true");
}
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn diagnose, fn diagnose_extrema, impl GrScratch, impl Drop_for_GrScratch, impl GrRead.
//! Moved out of the parent module by STRA-338: fn diagnose, fn diagnose_extrema, impl GrScratch, impl
//! Drop_for_GrScratch, impl GrRead.
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn download_f32, fn driver_error, fn binding_error, fn validate_values, fn validate_layer, fn validate_streams ....
//! Moved out of the parent module by STRA-338: fn download_f32, fn driver_error, fn binding_error, fn
//! validate_values, fn validate_layer, fn validate_streams ....
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn read_cached_cuda, fn inject_cached_cuda, fn copy_cached_f32, fn upload_cached_f32, fn release_all, fn admit_budget ....
//! Moved out of the parent module by STRA-338: fn read_cached_cuda, fn inject_cached_cuda, fn copy_cached_f32, fn
//! upload_cached_f32, fn release_all, fn admit_budget ....
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl GrMicroInput, impl GrMicroAttention, impl GrMicroDevice, fn save_micro_values, fn micro_driver_error, impl GrMicroAttentionBank ....
//! Moved out of the parent module by STRA-338: impl GrMicroInput, impl GrMicroAttention, impl GrMicroDevice, fn
//! save_micro_values, fn micro_driver_error, impl GrMicroAttentionBank ....
#[allow(unused_imports)]
use super::*;
@@ -297,107 +297,11 @@ impl GrStage {
})
}
}
fn check_retained_origin(
binding: &ModelBinding,
ready: &ResidualReady,
(block, block_identity): (&[f32], TokenLayer),
txn: &QwenStepTxn,
) -> Result<()> {
txn.validate_binding(&binding.identity())?;
ready.validate_origin(&binding.identity(), GrRole::Attention(ready.identity.layer().get()))?;
ready.identity.validate(txn.token(), txn.position(), ready.identity.layer())?;
if ready.identity != block_identity {
return Err(Error::IdentityMismatch);
}
validate_streams(&ready.streams)?;
validate_values(block, 2560)?;
validate_values(&ready.inject, 4)
}
// The retained context, its transport flag and the exclusive actor scratch, claimed for this one handoff.
fn lease_retained_scratch<'cache, 'ctx>(
binding: &ModelBinding,
read: &DetachedGrRead,
txn: &QwenStepTxn,
cache: &'cache DenseWeightCache<'ctx>,
) -> Result<(&'ctx Context<'ctx>, RefMut<'cache, GrScratch<'ctx>>)> {
let ready = read.ready();
let context = cache.retained_context(binding, txn.cuda_context()?)?;
let failed = cache.transport_failure_flag(binding, context)?;
read.validate_retained_transport(&failed)?;
let scratch = cache.gr_scratch(binding, context)?;
check_scratch_owner(&scratch, context, (ready, &failed))?;
// Preserve admission reserve; all eleven actor buffers are eager.
admit_budget(context, 40960 + 10240 + 16)?;
read.claim_retained_handoff(&failed)?;
Ok((context, scratch))
}
// The scratch is eager on this context and belongs to the handoff's binding and transport flag.
fn check_scratch_owner(
scratch: &GrScratch<'_>,
context: &Context<'_>,
(ready, failed): (&ResidualReady, &Rc<Cell<bool>>),
) -> Result<()> {
scratch.buffer(context)?;
if !scratch.binding.matches(&ready.binding) || !Rc::ptr_eq(&scratch.failed, failed) {
return Err(Error::IdentityMismatch);
}
Ok(())
}
fn check_retained_actual(
binding: &ModelBinding,
actual: &InjectedResidual,
transaction: &Rc<()>,
txn: &mut QwenStepTxn,
) -> Result<()> {
if !Rc::ptr_eq(transaction, &txn.residual_handoff_owner()?) {
return Err(Error::IdentityMismatch);
}
let identity = actual.identity;
let layer = identity.layer();
actual.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?;
identity.validate(txn.token(), txn.position(), layer)?;
txn.validate_binding(&binding.identity())?;
validate_layer(layer, binding.layer_count())?;
diagnose(GrPhase::Inputs, validate_streams(actual.streams()))
}
fn admit_retained_read<'ctx>(
binding: &ModelBinding,
scratch: &GrScratch<'ctx>,
txn: &QwenStepTxn,
cache: &DenseWeightCache<'ctx>,
) -> Result<&'ctx Context<'ctx>> {
let context = cache.retained_context(binding, txn.cuda_context()?)?;
let failed = cache.transport_failure_flag(binding, context)?;
if !scratch.binding.matches(&binding.identity()) || !Rc::ptr_eq(&scratch.failed, &failed) {
return Err(Error::IdentityMismatch);
}
scratch.buffer(context)?;
admit_budget(context, READ_DEVICE_BYTES)?;
Ok(context)
}
fn read_retained_candidate(
binding: &ModelBinding,
cache: &DenseWeightCache<'_>,
context: &Context<'_>,
role: GrRole,
scratch: &GrScratch<'_>,
) -> Result<ReadCandidate> {
let resident = cache.gr(binding, role)?;
let weights = &resident.weights;
if !weights.matches(&binding.identity(), role) {
return Err(Error::IdentityMismatch);
}
let gpu = cache.gr_buffers(resident)?;
// EXACT qualified norm/projection/Silu/gate/mix/finite-mask math. The
// scratch already contains this producer: intentionally no write/H2D.
read_cached_cuda(context, weights.epsilon(), weights.inject().is_some(), scratch, gpu)
}
#[path = "gr_retained_handoff/checks.rs"]
mod checks;
use checks::{
admit_retained_read, check_retained_actual, check_retained_origin, lease_retained_scratch, read_retained_candidate,
};
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[path = "gr_retained_handoff_gpu.rs"]
@@ -0,0 +1,105 @@
//! Admission checks and the scratch lease of the retained attention -> FFN handoff (moved out of the parent file by
//! STRA-338).
use super::*;
pub(super) fn check_retained_origin(
binding: &ModelBinding,
ready: &ResidualReady,
(block, block_identity): (&[f32], TokenLayer),
txn: &QwenStepTxn,
) -> Result<()> {
txn.validate_binding(&binding.identity())?;
ready.validate_origin(&binding.identity(), GrRole::Attention(ready.identity.layer().get()))?;
ready.identity.validate(txn.token(), txn.position(), ready.identity.layer())?;
if ready.identity != block_identity {
return Err(Error::IdentityMismatch);
}
validate_streams(&ready.streams)?;
validate_values(block, 2560)?;
validate_values(&ready.inject, 4)
}
// The retained context, its transport flag and the exclusive actor scratch, claimed for this one handoff.
pub(super) fn lease_retained_scratch<'cache, 'ctx>(
binding: &ModelBinding,
read: &DetachedGrRead,
txn: &QwenStepTxn,
cache: &'cache DenseWeightCache<'ctx>,
) -> Result<(&'ctx Context<'ctx>, RefMut<'cache, GrScratch<'ctx>>)> {
let ready = read.ready();
let context = cache.retained_context(binding, txn.cuda_context()?)?;
let failed = cache.transport_failure_flag(binding, context)?;
read.validate_retained_transport(&failed)?;
let scratch = cache.gr_scratch(binding, context)?;
check_scratch_owner(&scratch, context, (ready, &failed))?;
// Preserve admission reserve; all eleven actor buffers are eager.
admit_budget(context, 40960 + 10240 + 16)?;
read.claim_retained_handoff(&failed)?;
Ok((context, scratch))
}
// The scratch is eager on this context and belongs to the handoff's binding and transport flag.
fn check_scratch_owner(
scratch: &GrScratch<'_>,
context: &Context<'_>,
(ready, failed): (&ResidualReady, &Rc<Cell<bool>>),
) -> Result<()> {
scratch.buffer(context)?;
if !scratch.binding.matches(&ready.binding) || !Rc::ptr_eq(&scratch.failed, failed) {
return Err(Error::IdentityMismatch);
}
Ok(())
}
pub(super) fn check_retained_actual(
binding: &ModelBinding,
actual: &InjectedResidual,
transaction: &Rc<()>,
txn: &mut QwenStepTxn,
) -> Result<()> {
if !Rc::ptr_eq(transaction, &txn.residual_handoff_owner()?) {
return Err(Error::IdentityMismatch);
}
let identity = actual.identity;
let layer = identity.layer();
actual.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?;
identity.validate(txn.token(), txn.position(), layer)?;
txn.validate_binding(&binding.identity())?;
validate_layer(layer, binding.layer_count())?;
diagnose(GrPhase::Inputs, validate_streams(actual.streams()))
}
pub(super) fn admit_retained_read<'ctx>(
binding: &ModelBinding,
scratch: &GrScratch<'ctx>,
txn: &QwenStepTxn,
cache: &DenseWeightCache<'ctx>,
) -> Result<&'ctx Context<'ctx>> {
let context = cache.retained_context(binding, txn.cuda_context()?)?;
let failed = cache.transport_failure_flag(binding, context)?;
if !scratch.binding.matches(&binding.identity()) || !Rc::ptr_eq(&scratch.failed, &failed) {
return Err(Error::IdentityMismatch);
}
scratch.buffer(context)?;
admit_budget(context, READ_DEVICE_BYTES)?;
Ok(context)
}
pub(super) fn read_retained_candidate(
binding: &ModelBinding,
cache: &DenseWeightCache<'_>,
context: &Context<'_>,
role: GrRole,
scratch: &GrScratch<'_>,
) -> Result<ReadCandidate> {
let resident = cache.gr(binding, role)?;
let weights = &resident.weights;
if !weights.matches(&binding.identity(), role) {
return Err(Error::IdentityMismatch);
}
let gpu = cache.gr_buffers(resident)?;
// EXACT qualified norm/projection/Silu/gate/mix/finite-mask math. The
// scratch already contains this producer: intentionally no write/H2D.
read_cached_cuda(context, weights.epsilon(), weights.inject().is_some(), scratch, gpu)
}
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn gather_rows, fn binding_error, impl InputReady, impl PleOwner, impl PlePrior, impl PlePending ....
//! Moved out of the parent module by STRA-338: fn gather_rows, fn binding_error, impl InputReady, impl PleOwner, impl
//! PlePrior, impl PlePending ....
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl ResidualStreams, impl InputReady, impl StagedInput, impl From_for_Error.
//! Moved out of the parent module by STRA-338: impl ResidualStreams, impl InputReady, impl StagedInput, impl
//! From_for_Error.
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn ple_cuda, fn ple_project, fn ple_budget, fn ple_values, fn ple_zeros, fn ple_upload.
//! Moved out of the parent module by STRA-338: fn ple_cuda, fn ple_project, fn ple_budget, fn ple_values, fn
//! ple_zeros, fn ple_upload.
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn ple_upload_f32, fn ple_upload_u16, fn ple_download, fn ple_driver_error, impl InputStage.
//! Moved out of the parent module by STRA-338: fn ple_upload_f32, fn ple_upload_u16, fn ple_download, fn
//! ple_driver_error, impl InputStage.
#[allow(unused_imports)]
use super::*;
@@ -25,11 +25,12 @@ struct Entry {
#[derive(Default)]
struct RowHasher(u64);
type RowMap<V> = HashMap<u64, V, BuildHasherDefault<RowHasher>>;
/// The rows the device cache holds, with a recency queue so the least recently used rows are found without scanning the map.
/// `order` holds `(age, row)` items in non-decreasing age (every age change pushes the new item at the back; ages only grow).
/// An item is live when the map still holds the row at exactly that age; an older item of a row that was touched since, or of an
/// evicted row, is stale and skipped (stale items at the front are dropped, the rest by `compact_if_loose`). A row has exactly one
/// live item. Finding the oldest `n` rows therefore reads the front of the queue, not the ~1M entries of a full cache.
/// The rows the device cache holds, with a recency queue so the least recently used rows are found without scanning
/// the map. `order` holds `(age, row)` items in non-decreasing age (every age change pushes the new item at the back;
/// ages only grow). An item is live when the map still holds the row at exactly that age; an older item of a row that
/// was touched since, or of an evicted row, is stale and skipped (stale items at the front are dropped, the rest by
/// `compact_if_loose`). A row has exactly one live item. Finding the oldest `n` rows therefore reads the front of the
/// queue, not the ~1M entries of a full cache.
#[derive(Default)]
struct Residents {
map: RowMap<Entry>,
@@ -54,7 +55,8 @@ struct Lookup {
miss_rows: Vec<u64>,
pending: Vec<(u32, u32)>,
}
/// One row of a gather the cache lacks: its position in the 16 rows, the slot it gets and the row evicted from that slot.
/// One row of a gather the cache lacks: its position in the 16 rows, the slot it gets and the row evicted from that
/// slot.
struct PlannedMiss {
at: usize,
row: u64,
@@ -94,9 +96,10 @@ pub(crate) struct KarPleCache<'ctx> {
books: DeviceBuffer<'ctx>,
slots: DeviceBuffer<'ctx>,
output: DeviceBuffer<'ctx>,
/// Staging for the scatter's update records, one buffer per miss count (`scratch[k - 1]` holds `k * 56` bytes): the scatter's
/// layout names the exact byte length of its update block, so one buffer of the largest size would be refused, and a buffer
/// allocated and freed on every token costs a `cuMemAlloc` and a `cuMemFree` (which also waits for the whole device).
/// Staging for the scatter's update records, one buffer per miss count (`scratch[k - 1]` holds `k * 56` bytes):
/// the scatter's layout names the exact byte length of its update block, so one buffer of the largest size would
/// be refused, and a buffer allocated and freed on every token costs a `cuMemAlloc` and a `cuMemFree` (which also
/// waits for the whole device).
scratch: Vec<DeviceBuffer<'ctx>>,
binding: BindingIdentity,
archive: [u8; 32],
@@ -138,7 +138,8 @@ impl<'ctx> KarPleCache<'ctx> {
}
/// Start reading, on a thread of its own, the packets of the PLE `rows` (the sixteen rows of each token of the
/// chunk after the one being computed) that neither the device cache nor an earlier read-ahead holds. Call it
/// after `commit` of the current chunk. The result is used by the next `stage_batch`; nothing here can fail a request.
/// after `commit` of the current chunk. The result is used by the next `stage_batch`; nothing here can fail a
/// request.
pub(in super::super) fn read_ahead(&mut self, binding: &KarPleBinding, rows: &[u64]) {
if self.failed || rows.is_empty() || !ahead_enabled() {
return;
@@ -28,9 +28,19 @@ impl Scan {
fn new(capacity: u32) -> Self {
Self { map: HashMap::new(), next_slot: 0, age: 0, capacity }
}
/// (selected slots, misses as (row, slot, victim)) exactly as `KarPleCache::gather` chose them before the recency queue.
fn gather(&mut self, rows: &[u64; 16]) -> ([u32; 16], Vec<(u64, u32, Option<u64>)>) {
let mut misses = Vec::<(u64, u32, Option<u64>)>::new();
/// The full-scan victim: the oldest row neither named by `rows` nor already a victim of this gather.
fn victim(&self, rows: &[u64; 16], misses: &[OldMiss]) -> (u32, Option<u64>) {
let (victim, (slot, _)) = self
.map
.iter()
.filter(|(r, _)| !rows.contains(r) && !misses.iter().any(|m| m.2 == Some(**r)))
.min_by_key(|(_, e)| e.1)
.unwrap();
(*slot, Some(*victim))
}
/// The slot choice of one gather: (selected slots, misses, the new `next_slot`).
fn plan(&self, rows: &[u64; 16]) -> ([u32; 16], Vec<OldMiss>, u32) {
let mut misses = Vec::<OldMiss>::new();
let mut selected = [0u32; 16];
let mut next_slot = self.next_slot;
for (i, row) in rows.iter().enumerate() {
@@ -46,17 +56,17 @@ impl Scan {
next_slot += 1;
(next_slot - 1, None)
} else {
let (victim, (slot, _)) = self
.map
.iter()
.filter(|(r, _)| !rows.contains(r) && !misses.iter().any(|m| m.2 == Some(**r)))
.min_by_key(|(_, e)| e.1)
.unwrap();
(*slot, Some(*victim))
self.victim(rows, &misses)
};
selected[i] = slot;
misses.push((*row, slot, victim));
}
(selected, misses, next_slot)
}
/// (selected slots, misses as (row, slot, victim)) exactly as `KarPleCache::gather` chose them before the recency
/// queue.
fn gather(&mut self, rows: &[u64; 16]) -> ([u32; 16], Vec<OldMiss>) {
let (selected, misses, next_slot) = self.plan(rows);
for m in &misses {
if let Some(v) = m.2 {
self.map.remove(&v);
@@ -71,141 +81,219 @@ impl Scan {
(selected, misses)
}
}
type OldMiss = (u64, u32, Option<u64>);
/// The device side: what a scatter writes into a slot is the row's own packet (here the row number), so a gathered row is right
/// exactly when its slot holds its own number.
/// The device side: what a scatter writes into a slot is the row's own packet (here the row number), so a gathered
/// row is right exactly when its slot holds its own number.
struct Device(Vec<u64>);
fn token(rng: &mut Rng, hot: u64, universe: u64) -> [u64; 16] {
std::array::from_fn(|_| rng.row(hot, universe))
}
/// Gathers (the decode path) on a cache much smaller than the row universe: the queue picks the same slots, the same victims
/// and ends in the same state as the full scan, and every gathered row is its own row.
/// The new queue and the old full scan run in lockstep on the same gathers.
struct Lockstep {
capacity: u32,
old: Scan,
new: Residents,
next_slot: u32,
age: u64,
device: Device,
evictions: usize,
}
impl Lockstep {
fn new(capacity: u32) -> Self {
Self {
capacity,
old: Scan::new(capacity),
new: Residents::default(),
next_slot: 0,
age: 0,
device: Device(vec![u64::MAX; capacity as usize]),
evictions: 0,
}
}
fn step(&mut self, rows: &[u64; 16], step: usize) {
let (old_selected, old_misses) = self.old.gather(rows);
let plan = plan_gather(&self.new, self.next_slot, self.capacity, rows).unwrap();
assert_eq!(plan.selected, old_selected, "step {step}");
let planned: Vec<_> = plan.misses.iter().map(|m| (m.row, m.slot, m.victim)).collect();
assert_eq!(planned, old_misses, "step {step}");
self.evictions += planned.iter().filter(|m| m.2.is_some()).count();
for m in &plan.misses {
self.device.0[m.slot as usize] = m.row;
}
publish_gather(&mut self.new, &plan.misses, rows, self.age);
self.next_slot = plan.next_slot;
self.age += 16;
for (i, row) in rows.iter().enumerate() {
let slot = plan.selected[i] as usize;
assert_eq!(self.device.0[slot], *row, "step {step} position {i}: wrong row in the slot");
}
}
fn assert_final(&self) {
let capacity = self.capacity;
let evictions = self.evictions;
assert!(evictions > 1000, "capacity {capacity}: the cache never filled ({evictions} evictions)");
let mut a: Vec<_> = self.old.map.iter().map(|(r, (s, g))| (*r, *s, *g)).collect();
let mut b: Vec<_> = self.new.map.iter().map(|(r, e)| (*r, e.slot, e.age)).collect();
a.sort();
b.sort();
assert_eq!(a, b, "capacity {capacity}: final state");
let (queue, rows) = (self.new.order.len(), self.new.len());
assert!(queue <= 2 * rows + 4096 + 16, "queue grew to {queue} for {rows} rows");
}
}
/// Gathers (the decode path) on a cache much smaller than the row universe: the queue picks the same slots, the same
/// victims and ends in the same state as the full scan, and every gathered row is its own row.
#[test]
fn gather_equals_the_full_scan_on_random_sequences() {
for (capacity, hot, universe, seed) in
[(64u32, 40u64, 500u64, 1u64), (257, 200, 3000, 2), (1000, 300, 1200, 3), (32, 20, 40, 4)]
{
let mut rng = Rng(0x9e3779b97f4a7c15 ^ seed);
let mut old = Scan::new(capacity);
let mut new = Residents::default();
let (mut next_slot, mut age) = (0u32, 0u64);
let mut device = Device(vec![u64::MAX; capacity as usize]);
let mut evictions = 0usize;
let mut run = Lockstep::new(capacity);
for step in 0..6000 {
let rows = token(&mut rng, hot, universe);
let (old_selected, old_misses) = old.gather(&rows);
let plan = plan_gather(&new, next_slot, capacity, &rows).unwrap();
assert_eq!(plan.selected, old_selected, "step {step}");
let planned: Vec<_> = plan.misses.iter().map(|m| (m.row, m.slot, m.victim)).collect();
assert_eq!(planned, old_misses, "step {step}");
evictions += planned.iter().filter(|m| m.2.is_some()).count();
for m in &plan.misses {
device.0[m.slot as usize] = m.row;
}
publish_gather(&mut new, &plan.misses, &rows, age);
next_slot = plan.next_slot;
age += 16;
for (i, row) in rows.iter().enumerate() {
assert_eq!(
device.0[plan.selected[i] as usize], *row,
"step {step} position {i}: wrong row in the slot"
);
}
run.step(&token(&mut rng, hot, universe), step);
}
assert!(evictions > 1000, "capacity {capacity}: the cache never filled ({evictions} evictions)");
let mut a: Vec<_> = old.map.iter().map(|(r, (s, g))| (*r, *s, *g)).collect();
let mut b: Vec<_> = new.map.iter().map(|(r, e)| (*r, e.slot, e.age)).collect();
a.sort();
b.sort();
assert_eq!(a, b, "capacity {capacity}: final state");
assert!(
new.order.len() <= 2 * new.len() + 4096 + 16,
"queue grew to {} for {} rows",
new.order.len(),
new.len()
);
run.assert_final();
}
}
/// Prompt chunks (`lookup_rows` + `assign_slots` + commit) mixed with decode gathers: every row always reads its own slot, no slot
/// serves two rows, and each victim is among the oldest untouched rows (no kept row is older than a victim).
#[test]
fn chunks_and_gathers_interleaved_keep_every_row_in_its_own_slot() {
let capacity = 300u32;
let mut rng = Rng(0x2545f4914f6cdd1d);
let mut entries = Residents::default();
let (mut next_slot, mut age) = (0u32, 0u64);
let mut device = Device(vec![u64::MAX; capacity as usize]);
let mut chunk_evictions = 0usize;
for step in 0..1500 {
if step % 3 == 0 {
let n = 1 + (rng.next() % 6) as usize;
let rows: Vec<[u64; 16]> = (0..n).map(|_| token(&mut rng, 150, 2500)).collect();
let stamp = age + 1;
let lookup = lookup_rows(&mut entries, &rows, stamp).unwrap();
let (miss_slot, victims, next) =
assign_slots(&entries, next_slot, capacity, stamp, lookup.miss_rows.len()).unwrap();
// a victim is no younger than any row left in the cache that the chunk did not touch
let youngest_victim = victims.iter().flatten().map(|v| entries.map[v].age).max();
if let Some(limit) = youngest_victim {
let victims_set: std::collections::HashSet<u64> = victims.iter().flatten().copied().collect();
for (r, e) in &entries.map {
if e.age < stamp && !victims_set.contains(r) {
assert!(
e.age >= limit,
"step {step}: row {r} (age {}) outlived a victim of age {limit}",
e.age
);
}
}
}
chunk_evictions += victims.iter().flatten().count();
let mut slots = lookup.slots.clone();
for (at, miss) in &lookup.pending {
slots[*at as usize] = miss_slot[*miss as usize];
}
for (i, row) in lookup.miss_rows.iter().enumerate() {
device.0[miss_slot[i] as usize] = *row;
}
for v in victims.iter().flatten() {
entries.remove(v);
}
for (i, row) in lookup.miss_rows.iter().enumerate() {
entries.insert(*row, miss_slot[i], stamp);
}
next_slot = next;
age = stamp;
for (at, row) in rows.iter().flatten().enumerate() {
assert_eq!(device.0[slots[at] as usize], *row, "step {step}: chunk position {at}");
}
} else {
let rows = token(&mut rng, 150, 2500);
let plan = plan_gather(&entries, next_slot, capacity, &rows).unwrap();
for m in &plan.misses {
device.0[m.slot as usize] = m.row;
}
publish_gather(&mut entries, &plan.misses, &rows, age);
next_slot = plan.next_slot;
age += 16;
for (i, row) in rows.iter().enumerate() {
assert_eq!(device.0[plan.selected[i] as usize], *row, "step {step}: gather position {i}");
/// Prompt chunks (`lookup_rows` + `assign_slots` + commit) mixed with decode gathers.
struct Mixed {
capacity: u32,
entries: Residents,
next_slot: u32,
age: u64,
device: Device,
chunk_evictions: usize,
}
impl Mixed {
fn new(capacity: u32) -> Self {
Self {
capacity,
entries: Residents::default(),
next_slot: 0,
age: 0,
device: Device(vec![u64::MAX; capacity as usize]),
chunk_evictions: 0,
}
}
/// A victim is no younger than any row left in the cache that the chunk did not touch.
fn assert_kept_not_older(&self, victims: &std::collections::HashSet<u64>, limit: u64, stamp: u64, step: usize) {
for (r, e) in &self.entries.map {
if e.age < stamp && !victims.contains(r) {
assert!(e.age >= limit, "step {step}: row {r} (age {}) outlived a victim of age {limit}", e.age);
}
}
}
fn assert_victims_oldest(&self, victims: &[Option<u64>], stamp: u64, step: usize) {
let youngest_victim = victims.iter().flatten().map(|v| self.entries.map[v].age).max();
if let Some(limit) = youngest_victim {
let victims_set: std::collections::HashSet<u64> = victims.iter().flatten().copied().collect();
self.assert_kept_not_older(&victims_set, limit, stamp, step);
}
}
fn commit_chunk(&mut self, lookup: &Lookup, miss_slot: &[u32], victims: &[Option<u64>], stamp: u64) {
for (i, row) in lookup.miss_rows.iter().enumerate() {
self.device.0[miss_slot[i] as usize] = *row;
}
for v in victims.iter().flatten() {
self.entries.remove(v);
}
for (i, row) in lookup.miss_rows.iter().enumerate() {
self.entries.insert(*row, miss_slot[i], stamp);
}
}
fn chunk(&mut self, rng: &mut Rng, step: usize) {
let n = 1 + (rng.next() % 6) as usize;
let rows: Vec<[u64; 16]> = (0..n).map(|_| token(rng, 150, 2500)).collect();
let stamp = self.age + 1;
let lookup = lookup_rows(&mut self.entries, &rows, stamp).unwrap();
let (miss_slot, victims, next) =
assign_slots(&self.entries, self.next_slot, self.capacity, stamp, lookup.miss_rows.len()).unwrap();
self.assert_victims_oldest(&victims, stamp, step);
self.chunk_evictions += victims.iter().flatten().count();
let mut slots = lookup.slots.clone();
for (at, miss) in &lookup.pending {
slots[*at as usize] = miss_slot[*miss as usize];
}
self.commit_chunk(&lookup, &miss_slot, &victims, stamp);
self.next_slot = next;
self.age = stamp;
for (at, row) in rows.iter().flatten().enumerate() {
assert_eq!(self.device.0[slots[at] as usize], *row, "step {step}: chunk position {at}");
}
}
fn gather(&mut self, rng: &mut Rng, step: usize) {
let rows = token(rng, 150, 2500);
let plan = plan_gather(&self.entries, self.next_slot, self.capacity, &rows).unwrap();
for m in &plan.misses {
self.device.0[m.slot as usize] = m.row;
}
publish_gather(&mut self.entries, &plan.misses, &rows, self.age);
self.next_slot = plan.next_slot;
self.age += 16;
for (i, row) in rows.iter().enumerate() {
assert_eq!(self.device.0[plan.selected[i] as usize], *row, "step {step}: gather position {i}");
}
}
fn assert_invariants(&self, step: usize) {
let mut seen = std::collections::HashSet::new();
for e in entries.map.values() {
for e in self.entries.map.values() {
assert!(seen.insert(e.slot), "step {step}: slot {} serves two rows", e.slot);
}
assert!(entries.len() <= capacity as usize);
assert!(self.entries.len() <= self.capacity as usize);
// one live queue item per row
let live = entries.order.iter().filter(|(a, r)| entries.map.get(r).is_some_and(|e| e.age == *a)).count();
assert_eq!(live, entries.len(), "step {step}");
let live = self.entries.order.iter().filter(|(a, r)| self.entries.map.get(r).is_some_and(|e| e.age == *a));
assert_eq!(live.count(), self.entries.len(), "step {step}");
}
assert!(chunk_evictions > 500, "the chunks never evicted ({chunk_evictions})");
}
/// A full cache of 200,000 rows: each missed row costs a handful of queue items, never the 200,000 entries the scan read.
/// Every row always reads its own slot, no slot serves two rows, and each victim is among the oldest untouched rows
/// (no kept row is older than a victim).
#[test]
fn chunks_and_gathers_interleaved_keep_every_row_in_its_own_slot() {
let mut rng = Rng(0x2545f4914f6cdd1d);
let mut run = Mixed::new(300);
for step in 0..1500 {
if step % 3 == 0 {
run.chunk(&mut rng, step);
} else {
run.gather(&mut rng, step);
}
run.assert_invariants(step);
}
assert!(run.chunk_evictions > 500, "the chunks never evicted ({})", run.chunk_evictions);
}
fn examined_items(entries: &Residents) -> usize {
entries.examined.load(std::sync::atomic::Ordering::Relaxed)
}
fn assert_cost_is_a_handful(examined_after_full: usize, misses_after_full: usize, capacity: u32) {
assert!(misses_after_full >= 16 * 1900, "{misses_after_full}");
// each miss examines its victim plus the sixteen protected rows at most; the old scan examined `capacity` entries
// per miss
assert!(
examined_after_full <= misses_after_full * 40,
"{examined_after_full} items examined for {misses_after_full} misses (a scan would be {})",
misses_after_full * capacity as usize
);
}
/// A hot row touched over and over leaves the queue bounded.
fn assert_hot_row_keeps_queue_bounded(entries: &mut Residents, row: u64, age: u64) {
for i in 0..50_000u64 {
entries.touch(&(row - 1 - (i % 4)), age + i + 1);
}
assert!(entries.order.len() <= 2 * entries.len() + 4096 + 1, "queue {}", entries.order.len());
}
/// A full cache of 200,000 rows: each missed row costs a handful of queue items, never the 200,000 entries the scan
/// read.
#[test]
fn eviction_in_a_full_cache_examines_a_handful_of_items_not_the_cache() {
let capacity = 200_000u32;
@@ -218,29 +306,19 @@ fn eviction_in_a_full_cache_examines_a_handful_of_items_not_the_cache() {
while batches < capacity as usize / 16 + 2000 {
let rows: [u64; 16] = std::array::from_fn(|i| row + i as u64);
row += 16;
let before = entries.examined.load(std::sync::atomic::Ordering::Relaxed);
let before = examined_items(&entries);
let plan = plan_gather(&entries, next_slot, capacity, &rows).unwrap();
publish_gather(&mut entries, &plan.misses, &rows, age);
next_slot = plan.next_slot;
age += 16;
if next_slot == capacity {
examined_after_full += entries.examined.load(std::sync::atomic::Ordering::Relaxed) - before;
examined_after_full += examined_items(&entries) - before;
misses_after_full += plan.misses.len();
}
batches += 1;
}
assert!(misses_after_full >= 16 * 1900, "{misses_after_full}");
// each miss examines its victim plus the sixteen protected rows at most; the old scan examined `capacity` entries per miss
assert!(
examined_after_full <= misses_after_full * 40,
"{examined_after_full} items examined for {misses_after_full} misses (a scan would be {})",
misses_after_full * capacity as usize
);
// and a hot row touched over and over leaves the queue bounded
for i in 0..50_000u64 {
entries.touch(&(row - 1 - (i % 4)), age + i + 1);
}
assert!(entries.order.len() <= 2 * entries.len() + 4096 + 1, "queue {}", entries.order.len());
assert_cost_is_a_handful(examined_after_full, misses_after_full, capacity);
assert_hot_row_keeps_queue_bounded(&mut entries, row, age);
}
/// A prompt chunk of 50,000 misses in a full cache reads the front of the queue, not the cache once per chunk.
@@ -259,7 +337,8 @@ fn a_chunk_eviction_examines_about_as_many_items_as_it_needs() {
assert_eq!(examined, 50_000);
}
/// Fewer evictable rows than asked is refused by the caller; `oldest` itself returns what exists, found by the full scan.
/// Fewer evictable rows than asked is refused by the caller; `oldest` itself returns what exists, found by the full
/// scan.
#[test]
fn oldest_returns_what_exists_when_the_queue_runs_short() {
let mut entries = Residents::default();
@@ -3,8 +3,8 @@
#[allow(unused_imports)]
use super::*;
/// Publish a gather the device accepted: evict the victims, map the new rows, and age the sixteen rows `age_base + 1..=16`
/// in order (a row named twice keeps the later age), as the scan-based code did.
/// Publish a gather the device accepted: evict the victims, map the new rows, and age the sixteen rows `age_base +
/// 1..=16` in order (a row named twice keeps the later age), as the scan-based code did.
pub(super) fn publish_gather(entries: &mut Residents, misses: &[PlannedMiss], rows: &[u64; 16], age_base: u64) {
for m in misses {
if let Some(victim) = m.victim {
@@ -16,9 +16,10 @@ pub(super) fn publish_gather(entries: &mut Residents, misses: &[PlannedMiss], ro
entries.touch(row, age_base + i as u64 + 1).expect("completed batch mapping");
}
}
/// `LELEKA_PLE_AHEAD=on|off` (read once) turns the read-ahead of the next chunk's PLE packets on or off. Unset: on for Windows, where the
/// archive is a file the rows are read from at 20-45 k random reads a second (5 to 12 s of every 6144-token chunk); off elsewhere, where
/// the server profile keeps the archive in a memfd and its rows are a memory read (not measured, so not changed).
/// `LELEKA_PLE_AHEAD=on|off` (read once) turns the read-ahead of the next chunk's PLE packets on or off. Unset: on
/// for Windows, where the archive is a file the rows are read from at 20-45 k random reads a second (5 to 12 s of
/// every 6144-token chunk); off elsewhere, where the server profile keeps the archive in a memfd and its rows are a
/// memory read (not measured, so not changed).
pub(super) fn ahead_enabled() -> bool {
crate::settings::process().kv.ple_ahead
}
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: fn scratch_bytes, impl Hasher_for_RowHasher, impl Residents, impl KarPleStaged, fn lookup_rows, fn assign_slots ....
//! Moved out of the parent module by STRA-338: fn scratch_bytes, impl Hasher_for_RowHasher, impl Residents, impl
//! KarPleStaged, fn lookup_rows, fn assign_slots ....
#[allow(unused_imports)]
use super::*;
@@ -71,9 +72,10 @@ impl Residents {
self.order.retain(|(age, row)| map.get(row).is_some_and(|e| e.age == *age));
}
}
/// The `need` least recently used rows with age below `below` that `skip` does not name, oldest first, as `(row, slot)`
/// (rows of equal age in queue order); fewer when the cache holds fewer. Also returns how many items were examined: the cost,
/// which a test bounds. The queue answers; the full scan runs only when the queue gave fewer rows than asked.
/// The `need` least recently used rows with age below `below` that `skip` does not name, oldest first, as `(row,
/// slot)` (rows of equal age in queue order); fewer when the cache holds fewer. Also returns how many items were
/// examined: the cost, which a test bounds. The queue answers; the full scan runs only when the queue gave fewer
/// rows than asked.
pub(super) fn oldest(
&self,
need: usize,
@@ -204,8 +206,8 @@ pub(super) fn assign_slots(
Ok((miss_slot, victims, next_slot + from_free as u32))
}
/// The slot of each of the sixteen rows of one token: held rows keep theirs, each distinct missing row gets a free slot
/// (`next_slot..capacity`) or the slot of the least recently used row that is neither one of the sixteen nor already a victim.
/// Nothing is mutated.
/// (`next_slot..capacity`) or the slot of the least recently used row that is neither one of the sixteen nor already
/// a victim. Nothing is mutated.
pub(super) fn plan_gather(
entries: &Residents,
mut next_slot: u32,
@@ -12,8 +12,8 @@ fn apply(entries: &mut Residents, lookup: &Lookup, miss_slot: &[u32], victims: &
}
}
/// The staging buffers of the scatter: one per miss count, each exactly the update block the kernel's layout names
/// (`misses * 56` bytes: slot u32, packet payload 50, partition u16), so the persistent buffers are admitted like the former
/// per-call allocation of `updates.len()` bytes.
/// (`misses * 56` bytes: slot u32, packet payload 50, partition u16), so the persistent buffers are admitted like the
/// former per-call allocation of `updates.len()` bytes.
#[test]
fn the_scatter_staging_buffers_match_the_update_records() {
assert_eq!(UPDATE_RECORD_BYTES, 4 + 50 + 2);
@@ -78,26 +78,19 @@ fn hits_keep_their_slots_and_refresh_their_age() {
}
}
#[test]
fn a_full_cache_evicts_the_oldest_rows_the_chunk_does_not_touch() {
let mut entries = Residents::default();
let capacity = 12u32;
let mut next = 0u32;
// chunk 1 fills 12 slots with rows 100..112 (stamp 1), chunk 2 refreshes 100..104 (stamp 2)
/// Chunk 1 fills `capacity` slots with rows 100..112 (stamp 1), chunk 2 refreshes 100..104 (stamp 2).
fn fill_and_refresh(entries: &mut Residents, capacity: u32) -> u32 {
let rows1: Vec<u64> = (100..112).collect();
let lookup = lookup_rows(&mut entries, &chunk(&rows1), 1).unwrap();
let (slot, victims, n) = assign_slots(&entries, next, capacity, 1, lookup.miss_rows.len()).unwrap();
apply(&mut entries, &lookup, &slot, &victims, 1);
next = n;
assert_eq!(next, capacity);
let lookup = lookup_rows(&mut entries, &chunk(&[100, 101, 102, 103]), 2).unwrap();
assert!(lookup.miss_rows.is_empty());
// chunk 3 touches 100, 101 and needs four new rows: the victims are the four oldest of 104..112 (age 1)
let rows3 = [100u64, 101, 500, 501, 502, 503];
let lookup = lookup_rows(&mut entries, &chunk(&rows3), 3).unwrap();
assert_eq!(lookup.miss_rows, vec![500, 501, 502, 503]);
let (slot, victims, n) = assign_slots(&entries, next, capacity, 3, lookup.miss_rows.len()).unwrap();
let lookup = lookup_rows(entries, &chunk(&rows1), 1).unwrap();
let (slot, victims, n) = assign_slots(entries, 0, capacity, 1, lookup.miss_rows.len()).unwrap();
apply(entries, &lookup, &slot, &victims, 1);
assert_eq!(n, capacity);
let lookup = lookup_rows(entries, &chunk(&[100, 101, 102, 103]), 2).unwrap();
assert!(lookup.miss_rows.is_empty());
n
}
fn assert_victims_are_the_oldest(entries: &Residents, slot: &[u32], victims: &[Option<u64>]) {
let evicted: Vec<u64> = victims.iter().map(|v| v.expect("eviction")).collect();
assert!(evicted.iter().all(|r| (104..112).contains(r)), "{evicted:?}");
let distinct: std::collections::HashSet<_> = slot.iter().collect();
@@ -106,6 +99,20 @@ fn a_full_cache_evicts_the_oldest_rows_the_chunk_does_not_touch() {
for (i, v) in evicted.iter().enumerate() {
assert_eq!(entries.map[v].slot, slot[i]);
}
}
#[test]
fn a_full_cache_evicts_the_oldest_rows_the_chunk_does_not_touch() {
let mut entries = Residents::default();
let capacity = 12u32;
let next = fill_and_refresh(&mut entries, capacity);
// chunk 3 touches 100, 101 and needs four new rows: the victims are the four oldest of 104..112 (age 1)
let rows3 = [100u64, 101, 500, 501, 502, 503];
let lookup = lookup_rows(&mut entries, &chunk(&rows3), 3).unwrap();
assert_eq!(lookup.miss_rows, vec![500, 501, 502, 503]);
let (slot, victims, n) = assign_slots(&entries, next, capacity, 3, lookup.miss_rows.len()).unwrap();
assert_eq!(n, capacity);
assert_victims_are_the_oldest(&entries, &slot, &victims);
apply(&mut entries, &lookup, &slot, &victims, 3);
consistent(&entries);
assert_eq!(entries.len(), capacity as usize);
@@ -114,25 +121,16 @@ fn a_full_cache_evicts_the_oldest_rows_the_chunk_does_not_touch() {
}
}
/// Upstream 41cf05a0 `36381540` (`gather_batch` matched the prefetched rows by position): here rows are looked up by row
/// id, so a reordered, shifted, repeated or partly new chunk finds each row in the slot it was given, and a hit never moves.
#[test]
fn rows_are_matched_by_row_id_never_by_position_in_the_chunk() {
let mut entries = Residents::default();
let first: Vec<u64> = (1..=32).map(|r| r * 1000).collect();
let lookup = lookup_rows(&mut entries, &chunk(&first), 1).unwrap();
let (slot, victims, _) = assign_slots(&entries, 0, 64, 1, lookup.miss_rows.len()).unwrap();
apply(&mut entries, &lookup, &slot, &victims, 1);
let given: std::collections::HashMap<u64, u32> = entries.map.iter().map(|(r, e)| (*r, e.slot)).collect();
let slot_of = |row: u64| given[&row];
let expect = |rows: &[u64]| -> Vec<u32> { rows.iter().map(|&r| slot_of(r)).collect() };
let flat = |lookup: &Lookup| lookup.slots.clone();
type Given = std::collections::HashMap<u64, u32>;
fn assert_reorders_keep_slots(entries: &mut Residents, first: &[u64], given: &Given) {
let expect = |rows: &[u64]| -> Vec<u32> { rows.iter().map(|&r| given[&r]).collect() };
// a permutation (halves swapped), a reversal, a shift by one position, a repeat of one row and a subset
let mut swapped = first.clone();
let mut swapped = first.to_vec();
swapped.rotate_left(16);
let mut reversed = first.clone();
let mut reversed = first.to_vec();
reversed.reverse();
let mut shifted = first.clone();
let mut shifted = first.to_vec();
shifted.rotate_left(1);
for (name, rows) in [
("swapped", swapped),
@@ -141,16 +139,20 @@ fn rows_are_matched_by_row_id_never_by_position_in_the_chunk() {
("one row repeated", vec![first[5]; 16]),
("subset", (0..16).map(|i| first[(i * 7) % 32]).collect()),
] {
let lookup = lookup_rows(&mut entries, &chunk(&rows), 2).unwrap();
let lookup = lookup_rows(entries, &chunk(&rows), 2).unwrap();
assert!(lookup.miss_rows.is_empty() && lookup.pending.is_empty(), "{name}: a cached row is a miss");
assert_eq!(flat(&lookup), expect(&rows), "{name}: a position got another row's slot");
assert_eq!(lookup.slots.clone(), expect(&rows), "{name}: a position got another row's slot");
}
// a chunk of known and new rows: the known keep their slots wherever they stand, each new row is one miss however often it repeats
}
/// A chunk of known and new rows: the known keep their slots wherever they stand, each new row is one miss however
/// often it repeats.
fn assert_mixed_chunk_keeps_known_slots(entries: &mut Residents, first: &[u64], given: &Given) {
let mixed: Vec<u64> = vec![first[3], 77_001, first[0], 77_001, 77_002, first[3], first[31], 77_002];
let lookup = lookup_rows(&mut entries, &chunk(&mixed), 3).unwrap();
let lookup = lookup_rows(entries, &chunk(&mixed), 3).unwrap();
assert_eq!(lookup.miss_rows, vec![77_001, 77_002]);
for (at, &row) in mixed.iter().enumerate() {
let want = if row >= 77_000 { u32::MAX } else { slot_of(row) };
let want = if row >= 77_000 { u32::MAX } else { given[&row] };
// `chunk` pads a short chunk by repeating its rows: the first `mixed.len()` positions are the rows themselves
assert_eq!(lookup.slots[at], want, "mixed position {at}");
}
@@ -159,6 +161,21 @@ fn rows_are_matched_by_row_id_never_by_position_in_the_chunk() {
assert_eq!((named(0), named(1)), (4, 4));
}
/// Upstream 41cf05a0 `36381540` (`gather_batch` matched the prefetched rows by position): here rows are looked up by
/// row id, so a reordered, shifted, repeated or partly new chunk finds each row in the slot it was given, and a hit
/// never moves.
#[test]
fn rows_are_matched_by_row_id_never_by_position_in_the_chunk() {
let mut entries = Residents::default();
let first: Vec<u64> = (1..=32).map(|r| r * 1000).collect();
let lookup = lookup_rows(&mut entries, &chunk(&first), 1).unwrap();
let (slot, victims, _) = assign_slots(&entries, 0, 64, 1, lookup.miss_rows.len()).unwrap();
apply(&mut entries, &lookup, &slot, &victims, 1);
let given: Given = entries.map.iter().map(|(r, e)| (*r, e.slot)).collect();
assert_reorders_keep_slots(&mut entries, &first, &given);
assert_mixed_chunk_keeps_known_slots(&mut entries, &first, &given);
}
#[test]
fn a_chunk_that_needs_more_slots_than_the_untouched_rows_hold_is_refused() {
let mut entries = Residents::default();