diff --git a/crates/skippy-api/src/native-recipe.json b/crates/skippy-api/src/native-recipe.json index d1303fc5..9364c1a8 100644 --- a/crates/skippy-api/src/native-recipe.json +++ b/crates/skippy-api/src/native-recipe.json @@ -1,4 +1,4 @@ { "llama_upstream_sha": "918fe468dbaae80bcdaf975c1b368023f2578ead", - "patch_queue_sha256": "17cc7b399600fdc0a4636febf6a25915ea96118098c7777c17fccf1d976bf229" + "patch_queue_sha256": "44322ef9a21dc40bc1fb1cb05a462ff986c9324f8b70af217c9c104f224dda8a" } \ No newline at end of file diff --git a/crates/skippy-correctness/README.md b/crates/skippy-correctness/README.md index e446cc31..eb21c167 100644 --- a/crates/skippy-correctness/README.md +++ b/crates/skippy-correctness/README.md @@ -222,8 +222,12 @@ same activation/cache contracts without requiring a monolithic full GGUF. - `state-handoff` validates state export/import for a whole model or a stage range selected with `--state-layer-start`, `--state-layer-end`, and `--state-stage-index`. `--state-payload-kind` selects `full-state`, - `resident-kv`, `recurrent-only`, or `kv-recurrent` payloads. All ranges use - direct local runtime handoff; `full-state` remains the default payload. + `resident-kv`, or `kv-recurrent` payloads. All ranges use direct local + runtime handoff; `full-state` remains the default payload. `kv-recurrent` + carries the parts the stage itself is checkpointed by: a KV page where it + holds attention layers, and recurrent state where it holds recurrent layers, + so a hybrid model's middle stage with no attention layers carries recurrent + state alone. `--binary-control` is rejected because binary state export/import is unavailable. Omit it to run the supported local handoff. The report includes the handoff transport, payload kind, state payload size, @@ -233,7 +237,7 @@ same activation/cache contracts without requiring a monolithic full GGUF. input to exactly that prefix plus one continuation token. Use `--cache-hit-repeats` to repeatedly attach the exported state and decode the same continuation, producing a recompute-vs-cache-hit speedup estimate. Use - `--allow-mismatch` only for diagnostic payloads such as recurrent-only. + `--allow-mismatch` only for diagnostic payloads. - `native-mtp-open-ai-ab` launches a real two-stage `skippy-serving serve-binary` split three times through the embedded OpenAI frontend. The baseline run selects `--native-mtp=false --speculative-strategy disabled`. diff --git a/crates/skippy-correctness/src/cli.rs b/crates/skippy-correctness/src/cli.rs index 5e590be9..e85a47d0 100644 --- a/crates/skippy-correctness/src/cli.rs +++ b/crates/skippy-correctness/src/cli.rs @@ -552,7 +552,8 @@ pub struct GlmDsaStage0TraceArgs { pub enum StatePayloadKind { ResidentKv, FullState, - RecurrentOnly, + /// The stage's exact checkpoint: a KV page where it holds attention + /// layers, and the recurrent state where it holds recurrent layers. KvRecurrent, } diff --git a/crates/skippy-correctness/src/runner/remote_handoff.rs b/crates/skippy-correctness/src/runner/remote_handoff.rs index 25f032ba..23eb6cba 100644 --- a/crates/skippy-correctness/src/runner/remote_handoff.rs +++ b/crates/skippy-correctness/src/runner/remote_handoff.rs @@ -1766,7 +1766,6 @@ fn payload_kind_name(kind: StatePayloadKind) -> &'static str { match kind { StatePayloadKind::ResidentKv => "resident-kv", StatePayloadKind::FullState => "full-state", - StatePayloadKind::RecurrentOnly => "recurrent-only", StatePayloadKind::KvRecurrent => "kv-recurrent", } } diff --git a/crates/skippy-correctness/src/runner/state_handoff.rs b/crates/skippy-correctness/src/runner/state_handoff.rs index 1307f2a4..cba182c4 100644 --- a/crates/skippy-correctness/src/runner/state_handoff.rs +++ b/crates/skippy-correctness/src/runner/state_handoff.rs @@ -8,8 +8,8 @@ use skippy_protocol::binary::{ recv_reply, state_flags, write_stage_message, }; use skippy_runtime::{ - ActivationFrame, GgufStageRuntimePlan, MtpSource, RuntimeConfig, RuntimeKvPageDesc, StageModel, - StageSession, + ActivationFrame, CheckpointParts, CheckpointShape, GgufStageRuntimePlan, MtpSource, + RuntimeConfig, RuntimeKvPageDesc, StageModel, StageSession, }; use crate::{ @@ -96,7 +96,6 @@ pub(in crate::runner) enum LocalStatePayload { token_count: u64, }, FullState(Vec), - RecurrentOnly(Vec), KvRecurrent { kv_desc: Option, kv: Vec, @@ -108,7 +107,7 @@ impl LocalStatePayload { fn byte_len(&self) -> usize { match self { Self::ResidentKv { .. } => 0, - Self::FullState(bytes) | Self::RecurrentOnly(bytes) => bytes.len(), + Self::FullState(bytes) => bytes.len(), Self::KvRecurrent { kv, recurrent, .. } => kv.len().saturating_add(recurrent.len()), } } @@ -125,8 +124,7 @@ impl LocalStatePayload { .. }, ) => a_count == b_count, - (Self::FullState(a), Self::FullState(b)) - | (Self::RecurrentOnly(a), Self::RecurrentOnly(b)) => a == b, + (Self::FullState(a), Self::FullState(b)) => a == b, ( Self::KvRecurrent { kv_desc: a_desc, @@ -157,12 +155,6 @@ impl LocalStatePayload { None, None, ), - Self::RecurrentOnly(recurrent) => payload_digest_report( - state_payload_kind_name(StatePayloadKind::RecurrentOnly), - recurrent, - None, - Some(recurrent.as_slice()), - ), Self::KvRecurrent { kv, recurrent, .. } => { let mut hasher = Sha256::new(); hasher.update(b"kv-recurrent:kv:"); @@ -796,7 +788,7 @@ fn run_local_state_handoff( let source_prefill_ms = elapsed_ms(source_prefill_started); let source_export_started = Instant::now(); - let state_payload = export_local_state_payload(&mut source, args, prefix.len() as u64) + let state_payload = export_local_state_payload(&model, &mut source, args, prefix.len() as u64) .context("local state handoff source export failed")?; let source_export_ms = elapsed_ms(source_export_started); @@ -850,7 +842,7 @@ fn run_local_state_handoff( { state_payload.clone() } else { - export_local_state_payload(&mut restore, args, prefix.len() as u64) + export_local_state_payload(&model, &mut restore, args, prefix.len() as u64) .context("local state handoff restore export failed")? }; let restore_export_ms = elapsed_ms(restore_export_started); @@ -1309,11 +1301,12 @@ fn create_local_cache_hit_session( let mut session = model .create_session() .context("failed to create local state handoff cache-hit session")?; - import_local_state_payload(&mut session, args, payload, token_count, token_ids)?; + import_local_state_payload(model, &mut session, args, payload, token_count, token_ids)?; Ok(session) } fn export_local_state_payload( + model: &StageModel, session: &mut StageSession, args: &BinaryStateHandoffConfig, token_count: u64, @@ -1331,18 +1324,24 @@ fn export_local_state_payload( session .export_full_state(args.state_layer_start as i32, args.state_layer_end as i32)?, )), - StatePayloadKind::RecurrentOnly => Ok(LocalStatePayload::RecurrentOnly( - session.export_recurrent_state()?, - )), StatePayloadKind::KvRecurrent => { - let page = export_optional_kv_page( - session, - args.state_layer_start as i32, - args.state_layer_end as i32, - 0, - token_count, - )?; - let recurrent = session.export_recurrent_state()?; + let shape = stage_checkpoint_shape(model)?; + let page = shape + .has_page() + .then(|| { + session.export_kv_page( + args.state_layer_start as i32, + args.state_layer_end as i32, + 0, + token_count, + ) + }) + .transpose()?; + let recurrent = if shape.has_recurrent() { + session.export_recurrent_state()? + } else { + Vec::new() + }; Ok(LocalStatePayload::KvRecurrent { kv_desc: page.as_ref().map(|page| page.desc.clone()), kv: page.map(|page| page.payload).unwrap_or_default(), @@ -1374,7 +1373,14 @@ fn measure_resident_state_bytes( )) } +fn stage_checkpoint_shape(model: &StageModel) -> Result { + model + .checkpoint_shape() + .context("this stage has no exact checkpoint; use --state-payload-kind full-state") +} + fn import_local_state_payload( + model: &StageModel, session: &mut StageSession, args: &BinaryStateHandoffConfig, payload: &LocalStatePayload, @@ -1400,51 +1406,26 @@ fn import_local_state_payload( bytes, token_count, ), - LocalStatePayload::RecurrentOnly(bytes) => { - session.import_recurrent_state_for_token_count(bytes, token_count) - } LocalStatePayload::KvRecurrent { kv_desc, kv, recurrent, } => { - if let Some(kv_desc) = kv_desc { - session.import_kv_page(kv_desc, kv)?; - } else if !kv.is_empty() { - bail!("KV-recurrent payload has KV bytes but no KV descriptor"); - } - session.import_recurrent_state_for_token_count(recurrent, token_count) + let page = match kv_desc { + Some(kv_desc) => Some((kv_desc, kv.as_slice())), + None if kv.is_empty() => None, + None => bail!("KV-recurrent payload has KV bytes but no KV descriptor"), + }; + let parts = CheckpointParts::fit(stage_checkpoint_shape(model)?, page, recurrent)?; + session.import_checkpoint(&parts, token_count, &[]) } } } -fn export_optional_kv_page( - session: &mut StageSession, - layer_start: i32, - layer_end: i32, - token_start: u64, - token_count: u64, -) -> Result> { - match session.export_kv_page(layer_start, layer_end, token_start, token_count) { - Ok(page) => Ok(Some(page)), - Err(error) if is_native_kv_unavailable(&error) => Ok(None), - Err(error) => Err(error), - } -} - -fn is_native_kv_unavailable(error: &anyhow::Error) -> bool { - error.chain().any(|cause| { - let message = cause.to_string(); - message.contains("runtime memory type is not supported for native KV pages") - || message.contains("runtime has no attention KV cache") - }) -} - fn state_payload_kind_name(kind: StatePayloadKind) -> &'static str { match kind { StatePayloadKind::ResidentKv => "resident-kv", StatePayloadKind::FullState => "full-state", - StatePayloadKind::RecurrentOnly => "recurrent-only", StatePayloadKind::KvRecurrent => "kv-recurrent", } } @@ -1872,12 +1853,7 @@ mod tests { #[test] fn binary_control_rejects_every_payload_before_model_or_server_access() { - for payload in [ - "resident-kv", - "full-state", - "recurrent-only", - "kv-recurrent", - ] { + for payload in ["resident-kv", "full-state", "kv-recurrent"] { let cli = Cli::try_parse_from([ "skippy-correctness", "state-handoff", diff --git a/crates/skippy-correctness/tests/parity_models/mod.rs b/crates/skippy-correctness/tests/parity_models/mod.rs index aca86845..6191b675 100644 --- a/crates/skippy-correctness/tests/parity_models/mod.rs +++ b/crates/skippy-correctness/tests/parity_models/mod.rs @@ -1,6 +1,7 @@ use std::{ collections::BTreeSet, fs, + ops::Range, path::{Path, PathBuf}, process::Command, sync::OnceLock, @@ -11,8 +12,9 @@ use serde::Deserialize; use serde_json::Value; use skippy_model_ref::split_gguf_shard_info; use skippy_runtime::{ - ActivationFrame, GGML_TYPE_F16, IterationBatchPhase, IterationBatchRequest, MtpSource, - RuntimeConfig, RuntimeKvPage, RuntimeLoadMode, StageModel, StageSession, + ActivationFrame, CheckpointParts, CheckpointShape, GGML_TYPE_F16, IterationBatchPhase, + IterationBatchRequest, MtpSource, RuntimeConfig, RuntimeKvPage, RuntimeLoadMode, StageModel, + StageSession, package::{PackageStageRequest, inspect_layer_package, materialize_layer_package_details}, redirect_native_logs_to_file, }; @@ -1370,17 +1372,18 @@ fn run_stage_state_restore( let mut source = target.create_session()?; source.prefill_chunk_frame(&prefix, prefill_input.as_ref(), 0)?; - let payload = export_state_payload(&mut source, state_kind, stage_start, stage_end, 1)?; + let payload = + export_state_payload(&target, &mut source, state_kind, stage_start, stage_end, 1)?; let (source_predicted, source_frame) = source.decode_step_frame(continuation, decode_input.as_ref(), 0)?; let mut restored = target.create_session()?; import_state_payload( + &target, &mut restored, &payload, state_kind, - stage_start, - stage_end, + stage_start..stage_end, 1, &prefix, )?; @@ -1464,11 +1467,11 @@ fn verify_suffix_prefill_after_restore( let mut restored = target.create_session()?; import_state_payload( + target, &mut restored, payload, state_kind, - stage_start, - stage_end, + stage_start..stage_end, 1, prefix, )?; @@ -1519,7 +1522,14 @@ fn activation_frames_match(source: &ActivationFrame, restored: &ActivationFrame) }) } +fn stage_checkpoint_shape(target: &StageModel) -> Result { + target + .checkpoint_shape() + .context("KvRecurrent family stage has no exact checkpoint") +} + fn export_state_payload( + target: &StageModel, session: &mut StageSession, state_kind: StateKind, layer_start: u32, @@ -1532,18 +1542,19 @@ fn export_state_payload( Ok(StatePayload::ResidentKv) } StateKind::KvRecurrent => { - let kv = match session.export_kv_page( - layer_start as i32, - layer_end as i32, - 0, - token_count, - ) { - Ok(page) => Some(page), - Err(error) if native_kv_unavailable(&error) => None, - Err(error) => return Err(error), + let shape = stage_checkpoint_shape(target)?; + let kv = shape + .has_page() + .then(|| { + session.export_kv_page(layer_start as i32, layer_end as i32, 0, token_count) + }) + .transpose()?; + let recurrent = if shape.has_recurrent() { + session.export_recurrent_state()? + } else { + Vec::new() }; - let recurrent = session.export_recurrent_state()?; - if recurrent.is_empty() { + if shape.has_recurrent() && recurrent.is_empty() { bail!("KvRecurrent family exported empty recurrent state"); } Ok(StatePayload::KvRecurrent { kv, recurrent }) @@ -1552,11 +1563,11 @@ fn export_state_payload( } fn import_state_payload( + target: &StageModel, session: &mut StageSession, payload: &StatePayload, state_kind: StateKind, - layer_start: u32, - layer_end: u32, + layers: Range, token_count: u64, token_ids: &[i32], ) -> Result<()> { @@ -1565,27 +1576,14 @@ fn import_state_payload( session.restore_prefix(CACHE_SEQ_ID, token_ids) } (StateKind::KvRecurrent, StatePayload::KvRecurrent { kv, recurrent }) => { - if let Some(kv) = kv { - session.import_kv_page(&kv.desc, &kv.payload)?; - } - session.import_recurrent_state_for_token_count(recurrent, token_count) + let page = kv.as_ref().map(|kv| (&kv.desc, kv.payload.as_slice())); + stage_checkpoint_shape(target) + .and_then(|shape| CheckpointParts::fit(shape, page, recurrent)) + .and_then(|parts| session.import_checkpoint(&parts, token_count, &[])) } _ => bail!("state payload kind mismatch"), } - .with_context(|| { - format!( - "import state payload for layers {layer_start}..{layer_end} and {token_count} tokens" - ) - }) -} - -fn native_kv_unavailable(error: &anyhow::Error) -> bool { - error.chain().any(|cause| { - let message = cause.to_string(); - message.contains("runtime memory type is not supported for native KV pages") - || message.contains("runtime has no attention KV cache") - || message.contains("no KV cache layers selected by layer range") - }) + .with_context(|| format!("import state payload for layers {layers:?} and {token_count} tokens")) } fn open_stage_model(path: &StagePath, shape: StageShape, n_gpu_layers: i32) -> Result { diff --git a/crates/skippy-ffi/README.md b/crates/skippy-ffi/README.md index 59cdb9e2..1a3bfe80 100644 --- a/crates/skippy-ffi/README.md +++ b/crates/skippy-ffi/README.md @@ -105,11 +105,16 @@ same Rust crate. ## ABI Contract -The staged ABI is versioned as `0.1.92`. The patch header in +The staged ABI is versioned as `0.1.93`. The patch header in `llama_cpp/patches/` and the Rust constants in `crates/skippy-ffi/src/lib.rs` are the source of truth, so keep this README aligned with those files instead of treating it as canonical prose. +ABI `0.1.93` adds `skippy_model_checkpoint_parts` and `skippy_import_checkpoint`, +which name and import a stage checkpoint whole, and makes +`skippy_import_recurrent_state` refuse a recurrent state its attention cells do +not end with. + ABI `0.1.92` combines llama.cpp b12780's enlarged `llama_model_quantize_params` (ABI `0.1.88` on main), which crosses the FFI boundary both by value and by pointer, with the shared verification contract, which adds diff --git a/crates/skippy-ffi/src/bindings/skippy.rs b/crates/skippy-ffi/src/bindings/skippy.rs index 20ef4a18..b5a5eb07 100644 --- a/crates/skippy-ffi/src/bindings/skippy.rs +++ b/crates/skippy-ffi/src/bindings/skippy.rs @@ -6,7 +6,7 @@ pub const SKIPPY_ABI_VERSION_MAJOR: u32 = 0; pub const SKIPPY_ABI_VERSION_MINOR: u32 = 1; -pub const SKIPPY_ABI_VERSION_PATCH: u32 = 92; +pub const SKIPPY_ABI_VERSION_PATCH: u32 = 93; pub const SKIPPY_ACTIVATION_FRAME_VERSION: u32 = 2; pub const SKIPPY_ACTIVATION_BOUNDARY_DESC_VERSION: u32 = 2; pub const SKIPPY_ACTIVATION_IDENTITY_BYTES: u32 = 32; @@ -1558,7 +1558,7 @@ unsafe extern "C" { ) -> skippy_status; } unsafe extern "C" { - #[doc = " @brief Exports only recurrent memory; attention pages are exported independently."] + #[doc = " @brief Exports the session's recurrent state alone, without its attention cells.\n It checkpoints a stage by itself only when skippy_model_checkpoint_parts\n names no KV page part; skippy_export_full_state exports the whole sequence."] pub fn skippy_export_recurrent_state( session: *mut skippy_session, output: *mut ::std::os::raw::c_void, @@ -1579,7 +1579,7 @@ unsafe extern "C" { ) -> skippy_status; } unsafe extern "C" { - #[doc = " @brief Imports recurrent-only state into a session."] + #[doc = " @brief Imports recurrent state after the attention cells it continues from.\n When the stage holds attention layers, the session's attention cells must\n already end where the state does: import the KV page first. A state that\n ends elsewhere is refused, and the sequence is left empty."] pub fn skippy_import_recurrent_state( session: *mut skippy_session, input: *const ::std::os::raw::c_void, @@ -1587,6 +1587,41 @@ unsafe extern "C" { out_error: *mut *mut skippy_error, ) -> skippy_status; } +#[repr(u32)] +#[doc = " @brief The parts of a stage checkpoint."] +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +pub enum skippy_checkpoint_part { + KvPage = 1, + Recurrent = 2, +} +unsafe extern "C" { + #[doc = " @brief Returns the skippy_checkpoint_part bits a checkpoint of this stage carries.\n The parts follow the stage's layers rather than its model family: a hybrid\n model's stage holding no attention layers is checkpointed by its recurrent\n state alone. Zero means only full state checkpoints the stage."] + pub fn skippy_model_checkpoint_parts(model: *const skippy_model) -> u32; +} +#[doc = " @brief One stage checkpoint, in the parts skippy_model_checkpoint_parts names."] +#[repr(C)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct skippy_checkpoint_view { + #[doc = " The KV page, or null when the checkpoint has no KV page part."] + pub page: *const skippy_kv_page_desc, + pub page_payload: *const ::std::os::raw::c_void, + pub page_payload_bytes: usize, + #[doc = " skippy_export_recurrent_state's bytes, or none when the checkpoint has no recurrent part."] + pub recurrent: *const ::std::os::raw::c_void, + pub recurrent_bytes: usize, + #[doc = " The position the checkpoint resumes from."] + pub token_count: u64, + #[doc = " The token history, token_count long, or null to leave it empty."] + pub tokens: *const llama_token, +} +unsafe extern "C" { + #[doc = " @brief Imports a checkpoint into a fresh session whole, or leaves the session empty.\n The checkpoint must carry exactly the parts the stage needs, and its KV page\n must end at token_count. The page goes in first, then the recurrent state,\n the position and the token history; any failure empties the sequence again."] + pub fn skippy_import_checkpoint( + session: *mut skippy_session, + checkpoint: *const skippy_checkpoint_view, + out_error: *mut *mut skippy_error, + ) -> skippy_status; +} unsafe extern "C" { #[doc = " @brief Trims the session's token history and associated state."] pub fn skippy_trim_session( diff --git a/crates/skippy-ffi/src/dynamic.rs b/crates/skippy-ffi/src/dynamic.rs index ce0eb63e..02577d3a 100644 --- a/crates/skippy-ffi/src/dynamic.rs +++ b/crates/skippy-ffi/src/dynamic.rs @@ -9,10 +9,10 @@ use crate::runtime::{SkippyModelOpenFromPartsWithEventsFn, SkippyModelOpenWithEv use crate::{ ABI_VERSION_MAJOR, ABI_VERSION_MINOR, ABI_VERSION_PATCH, AbiVersion, ActivationBoundaryDesc, ActivationDesc, AsrAbortCallback, AsrInfoV1, AsrModel, AsrResult, AsrSegmentV1, - AsrTranscribeParamsV1, BackendDevice, CacheGenRecordV1, ClefInfoV1, ClefModel, Error, - GenerationSignalWindow, IterationRequest, KvPageDesc, LayaInfoV1, LayaMemoryV1, LayaModel, - LayaSequence, LlamaLogCallback, LlamaModelQuantizeParams, LlamaPerfContextFn, Model, ModelInfo, - MtmdBitmap, MtmdContext, MtmdContextParams, MtmdDecoderPos, MtmdGenAudioInfo, + AsrTranscribeParamsV1, BackendDevice, CacheGenRecordV1, CheckpointView, ClefInfoV1, ClefModel, + Error, GenerationSignalWindow, IterationRequest, KvPageDesc, LayaInfoV1, LayaMemoryV1, + LayaModel, LayaSequence, LlamaLogCallback, LlamaModelQuantizeParams, LlamaPerfContextFn, Model, + ModelInfo, MtmdBitmap, MtmdContext, MtmdContextParams, MtmdDecoderPos, MtmdGenAudioInfo, MtmdHelperBitmapWrapper, MtmdHelperDecodeBudget, MtmdHelperGenAudio, MtmdHelperGenAudioInput, MtmdHelperInitOpt, MtmdHelperVideo, MtmdInputChunkType, MtmdInputChunks, MtmdInputText, NativeMtpDraft, NativeRuntimeLoadError, NgramCache, Opaque, RuntimeConfig, SamplingConfig, @@ -268,6 +268,8 @@ dynamic_symbols! { skippy_model_kv_pool_cells(model: *const Model) -> u32; skippy_export_recurrent_state(session: *mut Session, output: *mut c_void, output_capacity: usize, out_bytes: *mut usize, out_error: *mut *mut Error) -> Status; skippy_import_recurrent_state(session: *mut Session, input: *const c_void, input_bytes: usize, out_error: *mut *mut Error) -> Status; + skippy_model_checkpoint_parts(model: *const Model) -> u32; + skippy_import_checkpoint(session: *mut Session, checkpoint: *const CheckpointView, out_error: *mut *mut Error) -> Status; skippy_session_export_resident_kv_page(session: *mut Session, cache_seq_id: i32, layer_start: i32, layer_end: i32, token_start: u64, token_count: u64, out_desc: *mut KvPageDesc, output: *mut c_void, output_capacity: usize, out_bytes: *mut usize, out_error: *mut *mut Error) -> Status; skippy_session_export_resident_recurrent_state(session: *mut Session, cache_seq_id: i32, output: *mut c_void, output_capacity: usize, out_bytes: *mut usize, out_error: *mut *mut Error) -> Status; skippy_session_resident_prefix_bytes(session: *mut Session, cache_seq_id: i32, out_bytes: *mut u64, out_error: *mut *mut Error) -> Status; diff --git a/crates/skippy-ffi/src/lib.rs b/crates/skippy-ffi/src/lib.rs index 6b918c23..d5bf2da1 100644 --- a/crates/skippy-ffi/src/lib.rs +++ b/crates/skippy-ffi/src/lib.rs @@ -5,7 +5,7 @@ mod dynamic_library; // without compiling the crate to determine native-runtime compatibility. pub const ABI_VERSION_MAJOR: u32 = 0; pub const ABI_VERSION_MINOR: u32 = 1; -pub const ABI_VERSION_PATCH: u32 = 92; +pub const ABI_VERSION_PATCH: u32 = 93; // The facade constants are parsed without compiling; tie them to the generated // bindings' view of the native ABI version at compile time so a common.h bump @@ -138,9 +138,10 @@ pub use stage_plan::{ pub use state::{ CACHEGEN_RECORD_EXACT, CACHEGEN_RECORD_F16, CACHEGEN_RECORD_F16_TRANSPOSED, CACHEGEN_RECORD_F32, CACHEGEN_RECORD_F32_TRANSPOSED, CACHEGEN_RECORD_Q4_0, - CACHEGEN_RECORD_Q8_0, CACHEGEN_RECORD_V1_ABI_VERSION, CacheGenRecordV1, - KV_PAGE_CODEC_ISWA_COMPOSITE_V1, KV_PAGE_CODEC_SINGLE_V1, KV_PAGE_FLAG_CANONICAL_POSITIONS, - KV_PAGE_FLAG_HAS_K_IDX, KV_PAGE_FLAG_V_TRANSPOSED, KvPageComponentDesc, KvPageDesc, + CACHEGEN_RECORD_Q8_0, CACHEGEN_RECORD_V1_ABI_VERSION, CHECKPOINT_PART_KV_PAGE, + CHECKPOINT_PART_RECURRENT, CacheGenRecordV1, CheckpointView, KV_PAGE_CODEC_ISWA_COMPOSITE_V1, + KV_PAGE_CODEC_SINGLE_V1, KV_PAGE_FLAG_CANONICAL_POSITIONS, KV_PAGE_FLAG_HAS_K_IDX, + KV_PAGE_FLAG_V_TRANSPOSED, KvPageComponentDesc, KvPageDesc, }; #[cfg(not(feature = "dynamic-runtime"))] @@ -184,11 +185,12 @@ pub use dynamic::{ skippy_decode_step_sampled, skippy_decode_step_sampled_mtp, skippy_decode_step_sampled_mtp_fn, skippy_detokenize, skippy_error_free, skippy_export_full_state, skippy_export_kv_page, skippy_export_recurrent_state, skippy_export_state, skippy_import_cachegen_kv_page_v1, - skippy_import_full_state, skippy_import_kv_page, skippy_import_recurrent_state, - skippy_import_state, skippy_iteration_batch_sampled, skippy_laya_model_free, - skippy_laya_model_info_v1, skippy_laya_model_memory_v1, skippy_laya_model_open, - skippy_laya_read, skippy_laya_tokenize, skippy_model_attach_mtp_draft_model_fn, - skippy_model_free, skippy_model_info_free, skippy_model_info_open, skippy_model_info_tensor_at, + skippy_import_checkpoint, skippy_import_full_state, skippy_import_kv_page, + skippy_import_recurrent_state, skippy_import_state, skippy_iteration_batch_sampled, + skippy_laya_model_free, skippy_laya_model_info_v1, skippy_laya_model_memory_v1, + skippy_laya_model_open, skippy_laya_read, skippy_laya_tokenize, + skippy_model_attach_mtp_draft_model_fn, skippy_model_checkpoint_parts, skippy_model_free, + skippy_model_info_free, skippy_model_info_open, skippy_model_info_tensor_at, skippy_model_info_tensor_count, skippy_model_input_activation_boundary, skippy_model_kv_pool_cells, skippy_model_llama_model, skippy_model_memory_cache_capabilities, skippy_model_open, skippy_model_open_from_parts, skippy_model_open_from_parts_with_events_fn, @@ -256,27 +258,27 @@ pub use static_bindings::{ skippy_decode_step_frame_sampled_mtp, skippy_decode_step_sampled, skippy_decode_step_sampled_mtp, skippy_detokenize, skippy_error_free, skippy_export_full_state, skippy_export_kv_page, skippy_export_recurrent_state, skippy_export_state, - skippy_import_cachegen_kv_page_v1, skippy_import_full_state, skippy_import_kv_page, - skippy_import_recurrent_state, skippy_import_state, skippy_iteration_batch_sampled, - skippy_laya_model_free, skippy_laya_model_info_v1, skippy_laya_model_memory_v1, - skippy_laya_model_open, skippy_laya_read, skippy_laya_tokenize, - skippy_model_attach_mtp_draft_model, skippy_model_free, skippy_model_info_free, - skippy_model_info_open, skippy_model_info_tensor_at, skippy_model_info_tensor_count, - skippy_model_input_activation_boundary, skippy_model_kv_pool_cells, skippy_model_llama_model, - skippy_model_memory_cache_capabilities, skippy_model_open, skippy_model_open_from_parts, - skippy_model_output_activation_boundary, skippy_model_supports_causal_readout, - skippy_model_workload_info_v1, skippy_ngram_cache_append, skippy_ngram_cache_create, - skippy_ngram_cache_draft, skippy_ngram_cache_free, skippy_ngram_cache_reset, - skippy_parse_chat_response_json, skippy_prefill_chunk, skippy_prefill_chunk_frame, - skippy_prefill_chunk_frame_sampled, skippy_prefill_chunk_frame_sampled_with_positions, - skippy_prefill_chunk_frame_with_positions, skippy_retire_verify_checkpoint, - skippy_session_batch_size, skippy_session_begin_external_decode, - skippy_session_configure_chat_sampling, skippy_session_copy_output_activation_frame, - skippy_session_create, skippy_session_create_from_resident_prefix, - skippy_session_drop_sequence, skippy_session_embed, skippy_session_encode_prompt, - skippy_session_end_external_decode, skippy_session_export_resident_kv_page, - skippy_session_export_resident_recurrent_state, skippy_session_free, - skippy_session_last_token_signal, skippy_session_llama_context, + skippy_import_cachegen_kv_page_v1, skippy_import_checkpoint, skippy_import_full_state, + skippy_import_kv_page, skippy_import_recurrent_state, skippy_import_state, + skippy_iteration_batch_sampled, skippy_laya_model_free, skippy_laya_model_info_v1, + skippy_laya_model_memory_v1, skippy_laya_model_open, skippy_laya_read, skippy_laya_tokenize, + skippy_model_attach_mtp_draft_model, skippy_model_checkpoint_parts, skippy_model_free, + skippy_model_info_free, skippy_model_info_open, skippy_model_info_tensor_at, + skippy_model_info_tensor_count, skippy_model_input_activation_boundary, + skippy_model_kv_pool_cells, skippy_model_llama_model, skippy_model_memory_cache_capabilities, + skippy_model_open, skippy_model_open_from_parts, skippy_model_output_activation_boundary, + skippy_model_supports_causal_readout, skippy_model_workload_info_v1, skippy_ngram_cache_append, + skippy_ngram_cache_create, skippy_ngram_cache_draft, skippy_ngram_cache_free, + skippy_ngram_cache_reset, skippy_parse_chat_response_json, skippy_prefill_chunk, + skippy_prefill_chunk_frame, skippy_prefill_chunk_frame_sampled, + skippy_prefill_chunk_frame_sampled_with_positions, skippy_prefill_chunk_frame_with_positions, + skippy_retire_verify_checkpoint, skippy_session_batch_size, + skippy_session_begin_external_decode, skippy_session_configure_chat_sampling, + skippy_session_copy_output_activation_frame, skippy_session_create, + skippy_session_create_from_resident_prefix, skippy_session_drop_sequence, skippy_session_embed, + skippy_session_encode_prompt, skippy_session_end_external_decode, + skippy_session_export_resident_kv_page, skippy_session_export_resident_recurrent_state, + skippy_session_free, skippy_session_last_token_signal, skippy_session_llama_context, skippy_session_memory_used_cells, skippy_session_position, skippy_session_rerank, skippy_session_reset, skippy_session_resident_prefix_bytes, skippy_session_restore_prefix, skippy_session_restore_token_history, skippy_session_sample_current, diff --git a/crates/skippy-ffi/src/state.rs b/crates/skippy-ffi/src/state.rs index 1ddf5df5..87a6f333 100644 --- a/crates/skippy-ffi/src/state.rs +++ b/crates/skippy-ffi/src/state.rs @@ -50,6 +50,12 @@ pub const CACHEGEN_RECORD_Q4_0: u32 = bindings::skippy::skippy_cachegen_record_k pub type CacheGenRecordV1 = bindings::skippy::skippy_cachegen_record_v1; +pub const CHECKPOINT_PART_KV_PAGE: u32 = bindings::skippy::skippy_checkpoint_part::KvPage as u32; +pub const CHECKPOINT_PART_RECURRENT: u32 = + bindings::skippy::skippy_checkpoint_part::Recurrent as u32; + +pub type CheckpointView = bindings::skippy::skippy_checkpoint_view; + pub type KvPageDesc = bindings::skippy::skippy_kv_page_desc; #[allow(clippy::derivable_impls)] diff --git a/crates/skippy-runtime/src/checkpoint_shape.rs b/crates/skippy-runtime/src/checkpoint_shape.rs new file mode 100644 index 00000000..04e8f2f8 --- /dev/null +++ b/crates/skippy-runtime/src/checkpoint_shape.rs @@ -0,0 +1,144 @@ +//! The parts an exact checkpoint of one stage carries. + +use crate::types::MemoryCacheCapabilities; + +/// The parts an exact checkpoint of one stage carries, read from the loaded +/// stage rather than its model family: a hybrid model's stage that holds no +/// attention layers is checkpointed by its recurrent state alone. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CheckpointShape { + /// A KV page alone. + Attention, + /// The recurrent state alone. + Recurrent, + /// A KV page and the recurrent state that ends where it does. + AttentionAndRecurrent, +} + +impl CheckpointShape { + pub(crate) fn from_native_parts(parts: u32) -> Option { + Self::from_parts( + parts & skippy_ffi::CHECKPOINT_PART_KV_PAGE != 0, + parts & skippy_ffi::CHECKPOINT_PART_RECURRENT != 0, + ) + } + + /// The shape the resident cache keeps for a stage: its attention cells + /// where it holds them, and a checkpoint where it holds recurrent state. + pub fn of_resident(capabilities: MemoryCacheCapabilities) -> Option { + if !capabilities.resident { + return None; + } + Self::from_parts( + capabilities.resident_attention, + capabilities.resident_checkpoint, + ) + } + + fn from_parts(page: bool, recurrent: bool) -> Option { + match (page, recurrent) { + (true, false) => Some(Self::Attention), + (false, true) => Some(Self::Recurrent), + (true, true) => Some(Self::AttentionAndRecurrent), + (false, false) => None, + } + } + + pub fn has_page(self) -> bool { + !matches!(self, Self::Recurrent) + } + + pub fn has_recurrent(self) -> bool { + !matches!(self, Self::Attention) + } + + /// Whether exported components hold every part of the shape: a described + /// KV page where the stage keeps attention, and recurrent bytes where it + /// keeps recurrent state. + pub fn is_covered_by(self, kv_bytes: u64, recurrent_bytes: u64, has_descriptor: bool) -> bool { + (!self.has_page() || (kv_bytes > 0 && has_descriptor)) + && (!self.has_recurrent() || recurrent_bytes > 0) + } + + /// The cache payload kind that stores the checkpoint. + pub fn payload_kind(self) -> skippy_cache::ExactStatePayloadKind { + match self { + Self::Recurrent => skippy_cache::ExactStatePayloadKind::RecurrentOnly, + Self::Attention | Self::AttentionAndRecurrent => { + skippy_cache::ExactStatePayloadKind::KvRecurrent + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use skippy_cache::ExactStatePayloadKind; + + fn resident(attention: bool, checkpoint: bool) -> MemoryCacheCapabilities { + MemoryCacheCapabilities { + resident: true, + resident_attention: attention, + resident_checkpoint: checkpoint, + ..MemoryCacheCapabilities::default() + } + } + + #[test] + fn the_native_parts_name_the_shape() { + let page = skippy_ffi::CHECKPOINT_PART_KV_PAGE; + let recurrent = skippy_ffi::CHECKPOINT_PART_RECURRENT; + assert_eq!(CheckpointShape::from_native_parts(0), None); + assert_eq!( + CheckpointShape::from_native_parts(page), + Some(CheckpointShape::Attention) + ); + assert_eq!( + CheckpointShape::from_native_parts(recurrent), + Some(CheckpointShape::Recurrent) + ); + assert_eq!( + CheckpointShape::from_native_parts(page | recurrent), + Some(CheckpointShape::AttentionAndRecurrent) + ); + } + + #[test] + fn a_stage_without_resident_memory_has_no_resident_shape() { + let capabilities = MemoryCacheCapabilities { + resident: false, + ..resident(true, true) + }; + assert_eq!(CheckpointShape::of_resident(capabilities), None); + assert_eq!(CheckpointShape::of_resident(resident(false, false)), None); + } + + #[test] + fn a_hybrid_checkpoint_needs_its_page_and_its_recurrent_state() { + let shape = CheckpointShape::of_resident(resident(true, true)).unwrap(); + assert_eq!(shape, CheckpointShape::AttentionAndRecurrent); + assert!(shape.is_covered_by(1, 1, true)); + assert!(!shape.is_covered_by(0, 1, true)); + assert!(!shape.is_covered_by(1, 1, false)); + assert!(!shape.is_covered_by(1, 0, true)); + assert_eq!(shape.payload_kind(), ExactStatePayloadKind::KvRecurrent); + } + + #[test] + fn a_stage_without_attention_layers_is_checkpointed_by_recurrent_state_alone() { + let shape = CheckpointShape::of_resident(resident(false, true)).unwrap(); + assert_eq!(shape, CheckpointShape::Recurrent); + assert!(shape.is_covered_by(0, 1, false)); + assert!(!shape.is_covered_by(0, 0, false)); + assert_eq!(shape.payload_kind(), ExactStatePayloadKind::RecurrentOnly); + } + + #[test] + fn an_attention_checkpoint_needs_only_a_described_page() { + let shape = CheckpointShape::of_resident(resident(true, false)).unwrap(); + assert_eq!(shape, CheckpointShape::Attention); + assert!(shape.is_covered_by(1, 0, true)); + assert!(!shape.is_covered_by(1, 0, false)); + } +} diff --git a/crates/skippy-runtime/src/kv_pages.rs b/crates/skippy-runtime/src/kv_pages.rs index cb5a1408..1e659330 100644 --- a/crates/skippy-runtime/src/kv_pages.rs +++ b/crates/skippy-runtime/src/kv_pages.rs @@ -1,7 +1,7 @@ use crate::native_timing::native_call; use std::ptr; -use anyhow::{Result, ensure}; +use anyhow::{Result, bail, ensure}; use skippy_cache::cachegen::archive::{ CacheGenArchive, ComponentLayout, PageLayout, RecordKind, ValidatedArchive, ValueType, decode_page, encode_page, validate_archive, @@ -11,9 +11,77 @@ use skippy_ffi::{CacheGenRecordV1, KvPageDesc as RawKvPageDesc}; use crate::error::{ensure_ok, free_error}; use crate::session::StageSession; use crate::{ - GGML_TYPE_F16, GGML_TYPE_F32, GGML_TYPE_Q4_0, GGML_TYPE_Q8_0, KV_PAGE_FLAG_V_TRANSPOSED, + CheckpointShape, GGML_TYPE_F16, GGML_TYPE_F32, GGML_TYPE_Q4_0, GGML_TYPE_Q8_0, + KV_PAGE_FLAG_V_TRANSPOSED, }; +/// One stage checkpoint, built to the stage's [`CheckpointShape`]: a hybrid +/// checkpoint cannot be built without both its KV page and its recurrent state. +#[derive(Debug, Clone, Copy)] +pub enum CheckpointParts<'a> { + Attention { + desc: &'a RuntimeKvPageDesc, + page: &'a [u8], + }, + Recurrent { + state: &'a [u8], + }, + AttentionAndRecurrent { + desc: &'a RuntimeKvPageDesc, + page: &'a [u8], + state: &'a [u8], + }, +} + +impl<'a> CheckpointParts<'a> { + /// Fit exported components to a shape. A part the shape needs and the + /// export lacks, or one it does not need, is an error, not a quieter restore. + pub fn fit( + shape: CheckpointShape, + page: Option<(&'a RuntimeKvPageDesc, &'a [u8])>, + state: &'a [u8], + ) -> Result { + Ok(match (shape, page, state.is_empty()) { + (CheckpointShape::Attention, Some((desc, page)), true) => { + Self::Attention { desc, page } + } + (CheckpointShape::Recurrent, None, false) => Self::Recurrent { state }, + (CheckpointShape::AttentionAndRecurrent, Some((desc, page)), false) => { + Self::AttentionAndRecurrent { desc, page, state } + } + (shape, page, no_state) => bail!( + "a {shape:?} checkpoint cannot be built from {} and {}", + if page.is_some() { + "a KV page" + } else { + "no KV page" + }, + if no_state { + "no recurrent state" + } else { + "recurrent state" + }, + ), + }) + } + + fn page(&self) -> Option<(&'a RuntimeKvPageDesc, &'a [u8])> { + match *self { + Self::Attention { desc, page } | Self::AttentionAndRecurrent { desc, page, .. } => { + Some((desc, page)) + } + Self::Recurrent { .. } => None, + } + } + + fn state(&self) -> &'a [u8] { + match *self { + Self::Recurrent { state } | Self::AttentionAndRecurrent { state, .. } => state, + Self::Attention { .. } => &[], + } + } +} + /// Encode one complete runtime KV page into the portable CacheGen archive /// consumed directly by the native device import ABI. pub fn encode_cachegen_kv_page(desc: &RuntimeKvPageDesc, raw: &[u8]) -> Result { @@ -582,6 +650,58 @@ impl StageSession { Ok(()) } + /// Import a whole checkpoint into this fresh session. The native side + /// checks the parts against the stage again, imports the page, the + /// recurrent state, the position and the token history in that order, and + /// leaves the session empty if any of them fails. + pub fn import_checkpoint( + &mut self, + parts: &CheckpointParts<'_>, + token_count: u64, + tokens: &[i32], + ) -> Result<()> { + ensure!( + tokens.is_empty() || tokens.len() as u64 == token_count, + "checkpoint token history has {} tokens for position {token_count}", + tokens.len() + ); + let page = parts.page(); + if let Some((desc, payload)) = page { + desc.validate_payload(payload.len())?; + } + let raw_desc = page.map(|(desc, _)| desc.as_raw()); + let state = parts.state(); + let view = skippy_ffi::CheckpointView { + page: raw_desc.as_ref().map_or(ptr::null(), ptr::from_ref), + page_payload: page.map_or(ptr::null(), |(_, payload)| payload.as_ptr().cast()), + page_payload_bytes: page.map_or(0, |(_, payload)| payload.len()), + recurrent: if state.is_empty() { + ptr::null() + } else { + state.as_ptr().cast() + }, + recurrent_bytes: state.len(), + token_count, + tokens: if tokens.is_empty() { + ptr::null() + } else { + tokens.as_ptr() + }, + }; + let mut error = ptr::null_mut(); + // SAFETY: every pointer in the view borrows from `parts`, `raw_desc` + // or `tokens`, all of which outlive the call; native code copies them. + let status = unsafe { native_call!(skippy_import_checkpoint(self.raw, &view, &mut error)) }; + if let Err(error) = ensure_ok(status, error) { + self.token_count = 0; + return Err(error); + } + self.token_count = token_count; + // Imported target state has no matching draft features. + self.dflash_after_replace(); + Ok(()) + } + pub fn import_recurrent_state_for_token_count( &mut self, input: &[u8], @@ -604,7 +724,41 @@ fn validate_imported_full_state_position(expected: u64, actual: u64) -> Result<( mod tests { use skippy_cache::cachegen::archive::{Record, RecordKind, ValidatedArchive}; - use super::{cachegen_records, validate_imported_full_state_position}; + use super::{CheckpointParts, cachegen_records, validate_imported_full_state_position}; + use crate::{CheckpointShape, RuntimeKvPageDesc}; + + #[test] + fn a_checkpoint_is_built_only_from_exactly_its_shapes_parts() { + let desc = RuntimeKvPageDesc { + version: 1, + layer_start: 0, + layer_end: 1, + token_start: 0, + token_count: 1, + layer_count: 1, + k_type: crate::GGML_TYPE_F16, + v_type: crate::GGML_TYPE_F16, + k_row_bytes: 1, + v_row_bytes: 1, + v_element_bytes: 1, + k_idx_row_bytes: 0, + payload_bytes: 1, + flags: 0, + codec: 0, + component_count: 0, + components: Box::new([Default::default(); 2]), + }; + let page = Some((&desc, &[1_u8][..])); + let state = [2_u8]; + let hybrid = CheckpointShape::AttentionAndRecurrent; + assert!(CheckpointParts::fit(hybrid, page, &state).is_ok()); + assert!(CheckpointParts::fit(hybrid, None, &state).is_err()); + assert!(CheckpointParts::fit(hybrid, page, &[]).is_err()); + assert!(CheckpointParts::fit(CheckpointShape::Recurrent, None, &state).is_ok()); + assert!(CheckpointParts::fit(CheckpointShape::Recurrent, page, &state).is_err()); + assert!(CheckpointParts::fit(CheckpointShape::Attention, page, &[]).is_ok()); + assert!(CheckpointParts::fit(CheckpointShape::Attention, page, &state).is_err()); + } #[test] fn maps_validated_cachegen_records_to_the_native_abi() { diff --git a/crates/skippy-runtime/src/lib.rs b/crates/skippy-runtime/src/lib.rs index 68e68387..64fc3fb6 100644 --- a/crates/skippy-runtime/src/lib.rs +++ b/crates/skippy-runtime/src/lib.rs @@ -5,6 +5,7 @@ pub(crate) use skippy_ffi::TensorRole; mod activation; mod capability_probe; mod chat_sampling_metadata; +mod checkpoint_shape; pub mod clef; mod config; pub mod decision; @@ -41,6 +42,7 @@ pub use activation::{ DecodeFrameBatchRequest, IterationBatchPhase, IterationBatchRequest, PartialBatchExecution, }; pub use capability_probe::{CapabilityReport, probe_capabilities}; +pub use checkpoint_shape::CheckpointShape; pub use clef::{ClefModel, ClefModelInfo}; pub use config::{ FlashAttentionType, GGML_TYPE_F16, GGML_TYPE_F32, GGML_TYPE_I32, GGML_TYPE_Q4_0, @@ -65,7 +67,7 @@ pub use gguf_writer::{ ModelInfo, write_gguf_from_parts, write_gguf_from_parts_consuming, write_gguf_metadata_from_parts, }; -pub use kv_pages::{decode_cachegen_kv_page, encode_cachegen_kv_page}; +pub use kv_pages::{CheckpointParts, decode_cachegen_kv_page, encode_cachegen_kv_page}; pub use laya::{LayaMemory, LayaModel, LayaModelInfo}; pub use logging::{ LLAMA_LOG_LEVEL_DEBUG, MeasuredNativeBuffers, NativeLogEvent, NativeLogParserMode, diff --git a/crates/skippy-runtime/src/native.rs b/crates/skippy-runtime/src/native.rs index d0839eb6..71726e76 100644 --- a/crates/skippy-runtime/src/native.rs +++ b/crates/skippy-runtime/src/native.rs @@ -226,6 +226,14 @@ impl StageModel { raw.try_into() } + /// The parts an exact checkpoint of this stage carries, or `None` when + /// only full state checkpoints it, and for the dummy model. + pub fn checkpoint_shape(&self) -> Option { + self.has_native_model() + .then(|| unsafe { skippy_ffi::skippy_model_checkpoint_parts(self.inner.raw) }) + .and_then(crate::CheckpointShape::from_native_parts) + } + /// A loaded causal graph can read next-token scores without sampling. /// This is independent of whether this worker owns the terminal head. pub fn supports_causal_readout(&self) -> bool { diff --git a/crates/skippy-serving/README.md b/crates/skippy-serving/README.md index 927e894c..19ba07e6 100644 --- a/crates/skippy-serving/README.md +++ b/crates/skippy-serving/README.md @@ -34,7 +34,7 @@ This adds native startup, not model-reference resolution or clean-install proof. The iteration scheduler combines equal-length verification windows from independent sessions on a complete causal target. -The combined implementation requires native ABI `0.1.92`. Each lane keeps its own sampler, checkpoint, +The combined implementation requires native ABI `0.1.93`. Each lane keeps its own sampler, checkpoint, rejection boundary and repair. Unsupported models and batches exceeding the actual native microbatch capacity use independent verification. diff --git a/crates/skippy-serving/src/kv_integration/resident_offload.rs b/crates/skippy-serving/src/kv_integration/resident_offload.rs index 85f74f4a..38ba54e1 100644 --- a/crates/skippy-serving/src/kv_integration/resident_offload.rs +++ b/crates/skippy-serving/src/kv_integration/resident_offload.rs @@ -50,14 +50,14 @@ impl KvStageIntegration { if !self.records_resident_prefixes() { return kind != skippy_cache::ExactStatePayloadKind::RecurrentOnly; } - self.loaded_memory_cache.is_some_and(|caps| { - if caps.resident_attention { - kind == skippy_cache::ExactStatePayloadKind::KvRecurrent - } else { - caps.resident_checkpoint - && kind == skippy_cache::ExactStatePayloadKind::RecurrentOnly - } - }) + self.resident_checkpoint_shape() + .is_some_and(|shape| shape.payload_kind() == kind) + } + + /// The parts a resident prefix of this stage is checkpointed by. + fn resident_checkpoint_shape(&self) -> Option { + self.loaded_memory_cache + .and_then(skippy_runtime::CheckpointShape::of_resident) } pub(super) fn native_components_are_complete( @@ -66,11 +66,8 @@ impl KvStageIntegration { recurrent_bytes: u64, has_descriptor: bool, ) -> bool { - self.loaded_memory_cache.is_none_or(|caps| { - !caps.resident - || ((!caps.resident_attention || (kv_bytes > 0 && has_descriptor)) - && (!caps.resident_checkpoint || recurrent_bytes > 0)) - }) + self.resident_checkpoint_shape() + .is_none_or(|shape| shape.is_covered_by(kv_bytes, recurrent_bytes, has_descriptor)) } pub(super) fn release_native_prefix( diff --git a/docs/CAUSAL_DECISIONS.md b/docs/CAUSAL_DECISIONS.md index 90b38cf2..a131bec8 100644 --- a/docs/CAUSAL_DECISIONS.md +++ b/docs/CAUSAL_DECISIONS.md @@ -112,7 +112,7 @@ fallback. In split execution, the terminal worker computes scores and returns only a bounded selected-token vector. Full vocabulary logits remain inside the native runtime. All workers must support stage protocol generation 18, wire header -version 18 and Skippy ABI 0.1.92. Upgrade the whole chain together; older stage +version 18 and Skippy ABI 0.1.93. Upgrade the whole chain together; older stage peers fail negotiation. Additive `system_one` discovery does not grant this ability to an older runtime. No persisted-data migration is required. diff --git a/docs/native-api.md b/docs/native-api.md index e60428db..a5cd4f1c 100644 --- a/docs/native-api.md +++ b/docs/native-api.md @@ -9,7 +9,7 @@ description: Generated reference for the capability-oriented Skippy C ABI. This reference is generated from the patched llama.cpp public headers. It documents the native C ABI used by Skippy's Rust FFI layer and staged runtime. The ABI is experimental and versioned for lockstep native/Rust builds. -Current generated surface: **21 headers** and **138 exported functions**. +Current generated surface: **21 headers** and **140 exported functions**. ## Quick navigation @@ -194,7 +194,7 @@ Current generated surface: **21 headers** and **138 exported functions**.
- state.h21 functions + state.h23 functions
skippy_model_memory_cache_capabilities skippy_model_kv_pool_cells @@ -204,6 +204,8 @@ Current generated surface: **21 headers** and **138 exported functions**. skippy_export_recurrent_state skippy_import_full_state skippy_import_recurrent_state + skippy_model_checkpoint_parts + skippy_import_checkpoint skippy_trim_session skippy_retire_verify_checkpoint skippy_session_verify_rollback_counts @@ -1813,7 +1815,7 @@ LLAMA_API enum skippy_status skippy_export_full_state( #### `skippy_export_recurrent_state` -Exports only recurrent memory; attention pages are exported independently. +Exports the session's recurrent state alone, without its attention cells. It checkpoints a stage by itself only when skippy_model_checkpoint_parts names no KV page part; skippy_export_full_state exports the whole sequence. ```cpp LLAMA_API enum skippy_status skippy_export_recurrent_state( @@ -1842,7 +1844,7 @@ LLAMA_API enum skippy_status skippy_import_full_state( #### `skippy_import_recurrent_state` -Imports recurrent-only state into a session. +Imports recurrent state after the attention cells it continues from. When the stage holds attention layers, the session's attention cells must already end where the state does: import the KV page first. A state that ends elsewhere is refused, and the sequence is left empty. ```cpp LLAMA_API enum skippy_status skippy_import_recurrent_state( @@ -1852,6 +1854,28 @@ LLAMA_API enum skippy_status skippy_import_recurrent_state( struct skippy_error ** out_error); ``` + +#### `skippy_model_checkpoint_parts` + +Returns the skippy_checkpoint_part bits a checkpoint of this stage carries. The parts follow the stage's layers rather than its model family: a hybrid model's stage holding no attention layers is checkpointed by its recurrent state alone. Zero means only full state checkpoints the stage. + +```cpp +LLAMA_API uint32_t skippy_model_checkpoint_parts( + const struct skippy_model * model); +``` + + +#### `skippy_import_checkpoint` + +Imports a checkpoint into a fresh session whole, or leaves the session empty. The checkpoint must carry exactly the parts the stage needs, and its KV page must end at token_count. The page goes in first, then the recurrent state, the position and the token history; any failure empties the sequence again. + +```cpp +LLAMA_API enum skippy_status skippy_import_checkpoint( + struct skippy_session * session, + const struct skippy_checkpoint_view * checkpoint, + struct skippy_error ** out_error); +``` + #### `skippy_trim_session` @@ -2291,7 +2315,7 @@ The headers also define the following enums, structs, opaque handles, and ABI co - `activation.h`: `skippy_activation_part_desc`, `skippy_activation_boundary_desc`, `skippy_activation_desc`, `SKIPPY_ACTIVATION_FRAME_VERSION = 2`, `SKIPPY_ACTIVATION_BOUNDARY_DESC_VERSION = 2`, `SKIPPY_ACTIVATION_IDENTITY_BYTES = 32`, `SKIPPY_ACTIVATION_MAX_DIMS = 4`, `SKIPPY_ACTIVATION_MAX_PARTS = 16`, `SKIPPY_ACTIVATION_PART_OPTIONAL = (UINT32_C(1) << 0)` - `asr.h`: `skippy_asr_model`, `skippy_asr_result`, `skippy_asr_info_v1`, `skippy_asr_transcribe_params_v1`, `skippy_asr_segment_v1`, `SKIPPY_ASR_INFO_V1_ABI_VERSION = 1`, `SKIPPY_ASR_TRANSCRIBE_PARAMS_V1_ABI_VERSION = 1`, `SKIPPY_ASR_SEGMENT_V1_ABI_VERSION = 1`, `SKIPPY_ASR_SAMPLE_RATE = 16000`, `SKIPPY_ASR_MAX_SAMPLES = (SKIPPY_ASR_SAMPLE_RATE * 60 * 30)` - `clef.h`: `skippy_clef_model`, `skippy_clef_order`, `skippy_clef_info_v1`, `SKIPPY_CLEF_INFO_V1_ABI_VERSION = 1` -- `common.h`: `skippy_feature`, `skippy_status`, `skippy_error`, `skippy_abi_version`, `SKIPPY_ABI_VERSION_MAJOR = 0`, `SKIPPY_ABI_VERSION_MINOR = 1`, `SKIPPY_ABI_VERSION_PATCH = 92`, `SKIPPY_FEATURE_RUNTIME_EVENT_REPORTER = ((uint64_t)1 << 31)`, `SKIPPY_FEATURE_MODEL_LOAD_EVENTS_V2 = ((uint64_t)1 << 32)`, `SKIPPY_FEATURE_KV_EVENTS = ((uint64_t)1 << 33)`, `SKIPPY_FEATURE_DEVICE_EVENTS = ((uint64_t)1 << 34)`, `SKIPPY_FEATURE_DIAGNOSTIC_EVENTS = ((uint64_t)1 << 35)`, `SKIPPY_FEATURE_NATIVE_TRACING = (UINT64_C(1) << 43)`, `SKIPPY_FEATURE_UNLOAD_EVENTS = ((uint64_t)1 << 36)`, `SKIPPY_FEATURE_NON_CHAT_WORKLOADS = ((uint64_t)1 << 37)`, `SKIPPY_FEATURE_SYSTEM_ONE = ((uint64_t)1 << 38)`, `SKIPPY_FEATURE_CACHEGEN_KV_PAGE = (UINT64_C(1) << 39)`, `SKIPPY_FEATURE_LAYA_DECISIONS = (UINT64_C(1) << 40)`, `SKIPPY_FEATURE_SPEECH_RECOGNITION = (UINT64_C(1) << 41)`, `SKIPPY_FEATURE_CLEF_DECISIONS = (UINT64_C(1) << 42)` +- `common.h`: `skippy_feature`, `skippy_status`, `skippy_error`, `skippy_abi_version`, `SKIPPY_ABI_VERSION_MAJOR = 0`, `SKIPPY_ABI_VERSION_MINOR = 1`, `SKIPPY_ABI_VERSION_PATCH = 93`, `SKIPPY_FEATURE_RUNTIME_EVENT_REPORTER = ((uint64_t)1 << 31)`, `SKIPPY_FEATURE_MODEL_LOAD_EVENTS_V2 = ((uint64_t)1 << 32)`, `SKIPPY_FEATURE_KV_EVENTS = ((uint64_t)1 << 33)`, `SKIPPY_FEATURE_DEVICE_EVENTS = ((uint64_t)1 << 34)`, `SKIPPY_FEATURE_DIAGNOSTIC_EVENTS = ((uint64_t)1 << 35)`, `SKIPPY_FEATURE_NATIVE_TRACING = (UINT64_C(1) << 43)`, `SKIPPY_FEATURE_UNLOAD_EVENTS = ((uint64_t)1 << 36)`, `SKIPPY_FEATURE_NON_CHAT_WORKLOADS = ((uint64_t)1 << 37)`, `SKIPPY_FEATURE_SYSTEM_ONE = ((uint64_t)1 << 38)`, `SKIPPY_FEATURE_CACHEGEN_KV_PAGE = (UINT64_C(1) << 39)`, `SKIPPY_FEATURE_LAYA_DECISIONS = (UINT64_C(1) << 40)`, `SKIPPY_FEATURE_SPEECH_RECOGNITION = (UINT64_C(1) << 41)`, `SKIPPY_FEATURE_CLEF_DECISIONS = (UINT64_C(1) << 42)` - `devices.h`: `skippy_backend_device_type`, `skippy_backend_device_cap`, `skippy_backend_device` - `events.h`: `skippy_runtime_event_v1`, `skippy_runtime_event_reporter_v1`, `SKIPPY_RUNTIME_EVENT_V1_ABI_VERSION = 1` - `execution.h`: `skippy_token_score_request`, `skippy_iteration_request`, `skippy_verify_request` @@ -2303,7 +2327,7 @@ The headers also define the following enums, structs, opaque handles, and ABI co - `signals.h`: `skippy_token_signal`, `skippy_generation_signal_window` - `speculative_decoding.h`: `skippy_ngram_cache`, `skippy_native_mtp_draft`, `SKIPPY_NATIVE_MTP_MAX_DRAFT_TOKENS = 8` - `stage_plan.h`: `skippy_stage_planner`, `skippy_stage_plan`, `skippy_stage_plan_string_ref_v1`, `skippy_stage_planner_tensor_v1`, `skippy_stage_planner_profile_v1`, `skippy_stage_planner_config_v1`, `skippy_stage_plan_value_kind`, `skippy_stage_plan_state_kind`, `skippy_stage_plan_state_access`, `skippy_stage_plan_state_residency`, `skippy_stage_plan_desc_v1`, `skippy_stage_plan_profile_desc_v1`, `skippy_stage_plan_value_desc_v1`, `skippy_stage_plan_state_desc_v1`, `SKIPPY_STAGE_PLANNER_CONFIG_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLANNER_TENSOR_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLANNER_PROFILE_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLAN_DESC_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLAN_PROFILE_DESC_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLAN_VALUE_DESC_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLAN_STATE_DESC_V1_ABI_VERSION = 1`, `SKIPPY_STAGE_PLAN_MAX_DIMS = 4` -- `state.h`: `skippy_memory_cache_capability`, `skippy_kv_page_flag`, `skippy_kv_page_codec`, `skippy_kv_page_component_role`, `skippy_cachegen_record_kind`, `skippy_cachegen_record_v1`, `skippy_kv_page_component_desc`, `skippy_kv_page_desc`, `SKIPPY_CACHEGEN_RECORD_V1_ABI_VERSION = 1` +- `state.h`: `skippy_memory_cache_capability`, `skippy_kv_page_flag`, `skippy_kv_page_codec`, `skippy_kv_page_component_role`, `skippy_cachegen_record_kind`, `skippy_cachegen_record_v1`, `skippy_kv_page_component_desc`, `skippy_kv_page_desc`, `skippy_checkpoint_part`, `skippy_checkpoint_view`, `SKIPPY_CACHEGEN_RECORD_V1_ABI_VERSION = 1` - `system_one.h`: `skippy_model`, `skippy_system_one_slot` - `tracing.h`: `skippy_native_span_v1`, `skippy_gpu_command_timing_v1`, `SKIPPY_NATIVE_SPAN_V1_ABI_VERSION = 1`, `SKIPPY_NATIVE_SPAN_ID_BIT = (UINT64_C(1) << 63)`, `SKIPPY_GPU_COMMAND_TIMING_V1_ABI_VERSION = 1` - `workloads.h`: `skippy_model`, `skippy_session`, `skippy_workload_kind`, `skippy_workload_pooling`, `skippy_workload_info_v1`, `SKIPPY_WORKLOAD_INFO_V1_ABI_VERSION = 1` diff --git a/llama_cpp/patches/model_support/0027-skippy-import-stage-checkpoints-whole-and-check-recurrent-imports.patch b/llama_cpp/patches/model_support/0027-skippy-import-stage-checkpoints-whole-and-check-recurrent-imports.patch new file mode 100644 index 00000000..2a57fa34 --- /dev/null +++ b/llama_cpp/patches/model_support/0027-skippy-import-stage-checkpoints-whole-and-check-recurrent-imports.patch @@ -0,0 +1,334 @@ +From 2fbaa6a89ed1cabaafd7b7ff4e12cd84536a9c4a Mon Sep 17 00:00:00 2001 +From: Jared Wyles +Date: Sat, 21 Nov 2026 22:30:00 +1100 +Subject: [PATCH] skippy: import stage checkpoints whole, and check recurrent + imports + +skippy_export_recurrent_state carries a session's recurrent memory alone: +since resident prefixes keep the attention cells as shared pool cells, the +attention half of a hybrid checkpoint travels as the KV page instead. Nothing +held importers to that. A hybrid session restored from the recurrent state +alone had no attention cells; it failed much later, at a page export, with a +message about missing token positions. + +llama.cpp's own partial states have the same gap: LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY +saves the recurrent and sliding-window halves, and the server keeps the +full-attention cells and the checkpoint's position range consistent by its own +bookkeeping. Here the native side checks against the live session instead. + +- skippy_import_recurrent_state refuses a state that does not end where the + session's attention cells do, when the stage holds attention layers, and + leaves the sequence empty. A hybrid model's stage with no attention layers + keeps empty attention cells and is not checked. +- skippy_model_checkpoint_parts reports what a checkpoint of the stage + carries: a KV page, recurrent state, or both. It follows the stage's layers, + so such a stage reports recurrent state alone. +- skippy_import_checkpoint takes the parts together, refuses any part the + stage does not need and any it lacks, imports them in order with the + position and token history, and empties the sequence again on failure. + +The sampling-history snapshot restores through skippy_import_checkpoint. The +hybrid state test also checks that the recurrent state alone, and the page +alone, are refused and leave the session usable for the whole pair. The +native ABI moves to 0.1.91. +--- + include/skippy/common.h | 2 +- + include/skippy/state.h | 49 +++++++++++++- + src/skippy/resident_prefix.cpp | 95 +++++++++++++++++++++++++++ + src/skippy/tests/sampling_history.cpp | 54 ++++++++++----- + 4 files changed, 182 insertions(+), 18 deletions(-) + +diff --git a/include/skippy/common.h b/include/skippy/common.h +index 465c7bf45e5bd3b0354977a3b6c735d58d12f927..f3887a80e1b3ba7f1d57610a80fe6870e21b9085 100644 +--- a/include/skippy/common.h ++++ b/include/skippy/common.h +@@ -46,7 +46,7 @@ extern "C" { + + #define SKIPPY_ABI_VERSION_MAJOR 0 + #define SKIPPY_ABI_VERSION_MINOR 1 +-#define SKIPPY_ABI_VERSION_PATCH 92 ++#define SKIPPY_ABI_VERSION_PATCH 93 + + #if defined(_MSC_VER) + #define SKIPPY_DEPRECATED(message) __declspec(deprecated(message)) +diff --git a/include/skippy/state.h b/include/skippy/state.h +index 6f8a934844112295a656a7bd33f7326d2ae1cc2e..49dca0cfd21d6efb7c30a113c0405ae185cf5480 100644 +--- a/include/skippy/state.h ++++ b/include/skippy/state.h +@@ -145,7 +145,10 @@ LLAMA_API enum skippy_status skippy_export_full_state( + size_t * out_bytes, + struct skippy_error ** out_error); + +-/** @brief Exports only recurrent memory; attention pages are exported independently. */ ++/** @brief Exports the session's recurrent state alone, without its attention cells. ++ * It checkpoints a stage by itself only when skippy_model_checkpoint_parts ++ * names no KV page part; skippy_export_full_state exports the whole sequence. ++ */ + LLAMA_API enum skippy_status skippy_export_recurrent_state( + struct skippy_session * session, + void * output, +@@ -162,13 +165,55 @@ LLAMA_API enum skippy_status skippy_import_full_state( + size_t input_bytes, + struct skippy_error ** out_error); + +-/** @brief Imports recurrent-only state into a session. */ ++/** @brief Imports recurrent state after the attention cells it continues from. ++ * When the stage holds attention layers, the session's attention cells must ++ * already end where the state does: import the KV page first. A state that ++ * ends elsewhere is refused, and the sequence is left empty. ++ */ + LLAMA_API enum skippy_status skippy_import_recurrent_state( + struct skippy_session * session, + const void * input, + size_t input_bytes, + struct skippy_error ** out_error); + ++/** @brief The parts of a stage checkpoint. */ ++enum skippy_checkpoint_part { ++ SKIPPY_CHECKPOINT_PART_KV_PAGE = 1 << 0, ++ SKIPPY_CHECKPOINT_PART_RECURRENT = 1 << 1, ++}; ++ ++/** @brief Returns the skippy_checkpoint_part bits a checkpoint of this stage carries. ++ * The parts follow the stage's layers rather than its model family: a hybrid ++ * model's stage holding no attention layers is checkpointed by its recurrent ++ * state alone. Zero means only full state checkpoints the stage. ++ */ ++LLAMA_API uint32_t skippy_model_checkpoint_parts(const struct skippy_model * model); ++ ++/** @brief One stage checkpoint, in the parts skippy_model_checkpoint_parts names. */ ++struct skippy_checkpoint_view { ++ /** The KV page, or null when the checkpoint has no KV page part. */ ++ const struct skippy_kv_page_desc * page; ++ const void * page_payload; ++ size_t page_payload_bytes; ++ /** skippy_export_recurrent_state's bytes, or none when the checkpoint has no recurrent part. */ ++ const void * recurrent; ++ size_t recurrent_bytes; ++ /** The position the checkpoint resumes from. */ ++ uint64_t token_count; ++ /** The token history, token_count long, or null to leave it empty. */ ++ const llama_token * tokens; ++}; ++ ++/** @brief Imports a checkpoint into a fresh session whole, or leaves the session empty. ++ * The checkpoint must carry exactly the parts the stage needs, and its KV page ++ * must end at token_count. The page goes in first, then the recurrent state, ++ * the position and the token history; any failure empties the sequence again. ++ */ ++LLAMA_API enum skippy_status skippy_import_checkpoint( ++ struct skippy_session * session, ++ const struct skippy_checkpoint_view * checkpoint, ++ struct skippy_error ** out_error); ++ + /** @brief Trims the session's token history and associated state. */ + LLAMA_API enum skippy_status skippy_trim_session( + struct skippy_session * session, +diff --git a/src/skippy/resident_prefix.cpp b/src/skippy/resident_prefix.cpp +index ebe660b64c9f5411a72bc271468d244dd29ba411..6a23de773b959875a79a0ab561cfa8f34dcccf03 100644 +--- a/src/skippy/resident_prefix.cpp ++++ b/src/skippy/resident_prefix.cpp +@@ -20,6 +20,7 @@ + #include + #include + #include ++#include + + namespace { + +@@ -35,6 +36,28 @@ llama_memory_t attention_memory(llama_memory_t memory) { + return skippy_memory_recurrent_adapter(memory) ? nullptr : memory; + } + ++// A hybrid stage whose layer range holds no attention layers keeps attention ++// cells with no rows; its recurrent state checkpoints it alone. ++bool holds_attention_rows(llama_memory_t memory) { ++ auto * attention = attention_memory(memory); ++ if (auto * iswa = dynamic_cast(attention)) { ++ return !iswa->get_base()->get_layer_ids().empty() || !iswa->get_swa()->get_layer_ids().empty(); ++ } ++ if (auto * kv = dynamic_cast(attention)) { ++ return !kv->get_layer_ids().empty(); ++ } ++ return attention != nullptr; ++} ++ ++const char * describe_parts(uint32_t parts) { ++ switch (parts) { ++ case SKIPPY_CHECKPOINT_PART_KV_PAGE | SKIPPY_CHECKPOINT_PART_RECURRENT: return "a KV page and recurrent state"; ++ case SKIPPY_CHECKPOINT_PART_KV_PAGE: return "a KV page alone"; ++ case SKIPPY_CHECKPOINT_PART_RECURRENT: return "recurrent state alone"; ++ default: return "no parts"; ++ } ++} ++ + skippy_status validate_session(skippy_session * session, int32_t cache_seq_id, + skippy_error ** error) { + if (!session || !session->ctx || !session->stage_model || !session->ctx->get_memory()) { +@@ -402,10 +425,82 @@ enum skippy_status skippy_import_recurrent_state(skippy_session * session, const + if (reader.n_bytes() != bytes) { + throw std::runtime_error("recurrent checkpoint has trailing data"); + } ++ auto * memory = session->ctx->get_memory(); ++ if (holds_attention_rows(memory) ++ && attention_memory(memory)->seq_pos_max(session->seq_id) != recurrent->seq_pos_max(session->seq_id)) { ++ memory->seq_rm(session->seq_id, -1, -1); ++ skippy_session_set_position(session, 0, nullptr); ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, ++ "recurrent state does not end where the session's attention cells do; import its KV page first"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } + return skippy_success(error); + } catch (const std::exception & exception) { return native_error(error, exception); } + } + ++uint32_t skippy_model_checkpoint_parts(const skippy_model * model) { ++ if (!model || !model->ctx || !model->ctx->get_memory() ++ || !(skippy_model_memory_cache_capabilities(model) & SKIPPY_MEMORY_CACHE_KV_RECURRENT)) { ++ return 0; ++ } ++ auto * memory = model->ctx->get_memory(); ++ return (holds_attention_rows(memory) ? SKIPPY_CHECKPOINT_PART_KV_PAGE : 0u) ++ | (skippy_memory_recurrent_adapter(memory) ? SKIPPY_CHECKPOINT_PART_RECURRENT : 0u); ++} ++ ++enum skippy_status skippy_import_checkpoint(skippy_session * session, ++ const skippy_checkpoint_view * checkpoint, skippy_error ** error) { ++ if (!session || !session->ctx || !session->stage_model || !session->ctx->get_memory() || !checkpoint ++ || (checkpoint->page && !checkpoint->page_payload) ++ || (checkpoint->recurrent_bytes && !checkpoint->recurrent)) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "session and checkpoint are required"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ const uint32_t needed = skippy_model_checkpoint_parts(session->stage_model); ++ if (!needed) { ++ skippy_set_error(error, SKIPPY_STATUS_UNSUPPORTED, "only full state checkpoints this stage"); ++ return SKIPPY_STATUS_UNSUPPORTED; ++ } ++ const uint32_t carried = (checkpoint->page ? SKIPPY_CHECKPOINT_PART_KV_PAGE : 0u) ++ | (checkpoint->recurrent_bytes ? SKIPPY_CHECKPOINT_PART_RECURRENT : 0u); ++ if (carried != needed) { ++ const std::string message = std::string("this stage is checkpointed by ") + describe_parts(needed) ++ + ", but the checkpoint carries " + describe_parts(carried); ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, message.c_str()); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ if (session->n_past != 0) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "a checkpoint is imported into a fresh session"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ if (checkpoint->token_count > static_cast(std::numeric_limits::max()) ++ || (checkpoint->page ++ && checkpoint->page->token_start + checkpoint->page->token_count != checkpoint->token_count)) { ++ skippy_set_error(error, SKIPPY_STATUS_INVALID_ARGUMENT, "the checkpoint's KV page must end at its position"); ++ return SKIPPY_STATUS_INVALID_ARGUMENT; ++ } ++ const auto empty_again = [&](skippy_status status) { ++ session->ctx->get_memory()->seq_rm(session->seq_id, -1, -1); ++ skippy_session_set_position(session, 0, nullptr); ++ return status; ++ }; ++ if (checkpoint->page) { ++ const auto status = skippy_import_kv_page(session, checkpoint->page, checkpoint->page_payload, ++ checkpoint->page_payload_bytes, error); ++ if (status != SKIPPY_STATUS_OK) { return empty_again(status); } ++ } ++ if (checkpoint->recurrent_bytes) { ++ const auto status = skippy_import_recurrent_state(session, checkpoint->recurrent, ++ checkpoint->recurrent_bytes, error); ++ if (status != SKIPPY_STATUS_OK) { return empty_again(status); } ++ } ++ auto status = skippy_session_set_position(session, static_cast(checkpoint->token_count), error); ++ if (status == SKIPPY_STATUS_OK && checkpoint->tokens) { ++ status = skippy_session_restore_token_history(session, checkpoint->tokens, checkpoint->token_count, error); ++ } ++ return status == SKIPPY_STATUS_OK ? status : empty_again(status); ++} ++ + enum skippy_status skippy_session_export_resident_recurrent_state(skippy_session * session, + int32_t cache_seq_id, void * output, size_t capacity, size_t * bytes, skippy_error ** error) { + if (!bytes) { +diff --git a/src/skippy/tests/sampling_history.cpp b/src/skippy/tests/sampling_history.cpp +index fea240bea9869846b35169b7ef85b4ce2d04454a..2d20c55bb928be06d0f420f1e92406edcb68468c 100644 +--- a/src/skippy/tests/sampling_history.cpp ++++ b/src/skippy/tests/sampling_history.cpp +@@ -231,23 +231,23 @@ struct snapshot { + } + } + ++ skippy_checkpoint_view view(const std::vector & prefix) const { ++ return { &page, payload.data(), payload.size(), recurrent.empty() ? nullptr : recurrent.data(), ++ recurrent.size(), prefix.size(), prefix.data() }; ++ } ++ + void restore(skippy_session * session, const std::vector & prefix) const { + skippy_error * error = nullptr; +- auto status = full +- ? skippy_import_full_state(session, 0, layers, payload.data(), payload.size(), &error) +- : skippy_import_kv_page(session, &page, payload.data(), payload.size(), &error); +- ok(status, error); +- if (!recurrent.empty()) { ++ if (full) { ++ ok(skippy_import_full_state(session, 0, layers, payload.data(), payload.size(), &error), error); ++ error = nullptr; ++ ok(skippy_session_set_position(session, prefix.size(), &error), error); + error = nullptr; +- status = skippy_import_recurrent_state(session, recurrent.data(), recurrent.size(), &error); +- ok(status, error); ++ ok(skippy_session_restore_token_history(session, prefix.data(), prefix.size(), &error), error); ++ } else { ++ const auto checkpoint = view(prefix); ++ ok(skippy_import_checkpoint(session, &checkpoint, &error), error); + } +- error = nullptr; +- status = skippy_session_set_position(session, prefix.size(), &error); +- ok(status, error); +- error = nullptr; +- status = skippy_session_restore_token_history(session, prefix.data(), prefix.size(), &error); +- ok(status, error); + CHECK(session->token_history == prefix); + } + }; +@@ -677,9 +677,12 @@ void raw_import_reclaims_chunks(skippy_model * model) { + + // A hybrid checkpoint is the composition of an independently exported attention + // page and recurrent-only component. Restoring the recurrent component alone +-// leaves no attention cells. Compare both components byte for byte after restore, +-// then compare continuation logits with a prefix prefilled from scratch. ++// leaves no attention cells, so the import refuses either half and leaves the ++// session empty for the whole pair. Compare both components byte for byte after ++// restore, then compare continuation logits with a prefix prefilled from scratch. + void state_round_trip(skippy_model * model) { ++ CHECK(skippy_model_checkpoint_parts(model) ++ == (SKIPPY_CHECKPOINT_PART_KV_PAGE | SKIPPY_CHECKPOINT_PART_RECURRENT)); + const std::vector prefix(128, 1); + auto * source = create(model); + prefill(source, prefix); +@@ -690,6 +693,27 @@ void state_round_trip(skippy_model * model) { + const snapshot checkpoint(source, false); + release(source); + ++ auto * half = create(model); ++ skippy_error * error = nullptr; ++ CHECK(skippy_import_recurrent_state(half, checkpoint.recurrent.data(), checkpoint.recurrent.size(), &error) ++ == SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(error); ++ auto recurrent_alone = checkpoint.view(prefix); ++ recurrent_alone.page = nullptr; ++ error = nullptr; ++ CHECK(skippy_import_checkpoint(half, &recurrent_alone, &error) == SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(error); ++ auto page_alone = checkpoint.view(prefix); ++ page_alone.recurrent = nullptr; ++ page_alone.recurrent_bytes = 0; ++ error = nullptr; ++ CHECK(skippy_import_checkpoint(half, &page_alone, &error) == SKIPPY_STATUS_INVALID_ARGUMENT); ++ skippy_error_free(error); ++ CHECK(half->n_past == 0); ++ checkpoint.restore(half, prefix); ++ CHECK(export_page(half, prefix.size()) == source_page); ++ release(half); ++ + auto * restored = create(model); + checkpoint.restore(restored, prefix); + const auto restored_page = export_page(restored, prefix.size()); diff --git a/llama_cpp/patches/model_support/series b/llama_cpp/patches/model_support/series index 157f7412..424abe89 100644 --- a/llama_cpp/patches/model_support/series +++ b/llama_cpp/patches/model_support/series @@ -24,3 +24,4 @@ 0024-models-preserve-checkpoint-layouts-and-head-scales.patch 0025-abi-distinguish-b12780-upstream-c-layouts.patch 0026-skippy-bump-the-native-abi-for-shared-verification.patch +0027-skippy-import-stage-checkpoints-whole-and-check-recurrent-imports.patch