STRA-338 size2 en1: backend, governor, proofs and model-binding helpers cut to the limits
This commit is contained in:
@@ -31,8 +31,9 @@ pub(super) fn prepare_prompt(
|
||||
context: u32,
|
||||
) -> Result<Vec<u32>, BackendError> {
|
||||
validate_request(request)?;
|
||||
// The prompt may carry marks (`LiteralMarks`) for control-token text that was inside a message: that text is encoded as
|
||||
// ordinary text, the template's own literals as special tokens. A prompt without marks encodes as before.
|
||||
// The prompt may carry marks (`LiteralMarks`) for control-token text that was inside a message: that text is
|
||||
// encoded as ordinary text, the template's own literals as special tokens. A prompt without marks encodes as
|
||||
// before.
|
||||
let tokens = tokenizer.encode_marked(&request.prompt).map_err(|_| invalid("prompt tokenization failed"))?;
|
||||
if tokens.is_empty()
|
||||
|| tokens.len().checked_add(request.max_output_tokens as usize).is_none_or(|total| total > context as usize)
|
||||
|
||||
@@ -45,30 +45,33 @@ pub(super) fn validate_handle(model: &LoadedModel, kar_expert_native_digest: Opt
|
||||
|| model.handle.chars().any(char::is_control)
|
||||
|| model.descriptor != pinned_model_descriptor()
|
||||
|| model.load_config_version != LOAD_CONFIG_VERSION
|
||||
|| !match &model.effective_mode {
|
||||
// With a KAR expert source the Native handle carries the source
|
||||
// identity; it must equal the digest this owner would publish.
|
||||
InferenceMode::Native => model.mode_identity_digest == kar_expert_native_digest.unwrap_or(MODE_DIGEST),
|
||||
InferenceMode::ExperimentalKarPle { profile_id } => {
|
||||
profile_id == KAR_PROFILE
|
||||
&& model.mode_identity_digest.strip_prefix("sha256:").is_some_and(|hex| {
|
||||
hex.len() == 64 && hex.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
|
||||
})
|
||||
}
|
||||
InferenceMode::ExperimentalMtp { profile_id } => {
|
||||
(profile_id == NATIVE_MTP_PROFILE || profile_id == KAR_MTP_PROFILE)
|
||||
&& model.mode_identity_digest.strip_prefix("sha256:").is_some_and(|hex| {
|
||||
hex.len() == 64 && hex.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
|
||||
})
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
|| !mode_identity_valid(model, kar_expert_native_digest)
|
||||
{
|
||||
return Err(invalid("invalid loaded model identity"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mode_identity_valid(model: &LoadedModel, kar_expert_native_digest: Option<&str>) -> bool {
|
||||
match &model.effective_mode {
|
||||
// With a KAR expert source the Native handle carries the source
|
||||
// identity; it must equal the digest this owner would publish.
|
||||
InferenceMode::Native => model.mode_identity_digest == kar_expert_native_digest.unwrap_or(MODE_DIGEST),
|
||||
InferenceMode::ExperimentalKarPle { profile_id } => profile_id == KAR_PROFILE && sha256_digest(model),
|
||||
InferenceMode::ExperimentalMtp { profile_id } => {
|
||||
(profile_id == NATIVE_MTP_PROFILE || profile_id == KAR_MTP_PROFILE) && sha256_digest(model)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn sha256_digest(model: &LoadedModel) -> bool {
|
||||
model
|
||||
.mode_identity_digest
|
||||
.strip_prefix("sha256:")
|
||||
.is_some_and(|hex| hex.len() == 64 && hex.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)))
|
||||
}
|
||||
|
||||
pub(super) fn validate_request(request: &GenerationRequest) -> Result<(), BackendError> {
|
||||
if request.request_id.is_empty()
|
||||
|| request.request_id.len() > 128
|
||||
|
||||
@@ -113,7 +113,8 @@ impl OriginalServeOptions {
|
||||
pub(super) fn ineligible(facts: &ConfigFacts) -> Option<&'static str> {
|
||||
if facts.kar_expert {
|
||||
return Some(
|
||||
"a KAR expert source is configured: the Original executors read the pinned model's own mapped routed experts, not a KAR level decode",
|
||||
"a KAR expert source is configured: the Original executors read the pinned model's own mapped routed \
|
||||
experts, not a KAR level decode",
|
||||
);
|
||||
}
|
||||
if facts.experimental {
|
||||
|
||||
@@ -32,21 +32,26 @@ fn refuse_starved_host() -> Result<(), BackendError> {
|
||||
if let Some(governor) = leleka_memory::Governor::global() {
|
||||
let need = governor.policy().soft_floor.saturating_add(RECONFIGURE_HEADROOM_BYTES);
|
||||
if let Some(available) = governor.probe().effective_available().filter(|available| *available < need) {
|
||||
return Err(BackendError {
|
||||
code: ErrorCode::ResourceExhausted,
|
||||
message: format!(
|
||||
"reconfigure refused: only {} MiB of host memory are available and reopening the serve stack needs {} MiB (the soft floor plus {} MiB); free memory first or restart with `leleka up`; nothing was changed",
|
||||
available >> 20,
|
||||
need >> 20,
|
||||
RECONFIGURE_HEADROOM_BYTES >> 20
|
||||
),
|
||||
retryable: false,
|
||||
});
|
||||
return Err(starved_host_error(available, need));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn starved_host_error(available: u64, need: u64) -> BackendError {
|
||||
BackendError {
|
||||
code: ErrorCode::ResourceExhausted,
|
||||
message: format!(
|
||||
"reconfigure refused: only {} MiB of host memory are available and reopening the serve stack needs {} \
|
||||
MiB (the soft floor plus {} MiB); free memory first or restart with `leleka up`; nothing was changed",
|
||||
available >> 20,
|
||||
need >> 20,
|
||||
RECONFIGURE_HEADROOM_BYTES >> 20
|
||||
),
|
||||
retryable: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn open_stack<'a, 'ctx>(
|
||||
env: &ReopenEnv<'a, 'ctx, '_>,
|
||||
options: &OriginalServeOptions,
|
||||
|
||||
@@ -12,7 +12,8 @@ pub use leleka_engine_core::memory::{mem_available, memory_admit};
|
||||
/// Available host physical memory right now; `None` when unknown (any
|
||||
/// non-Linux target, unreadable or malformed `/proc/meminfo`).
|
||||
pub fn available_memory() -> Option<u64> {
|
||||
// with the memory governor installed: MemAvailable limited by the cgroup headroom, the same number every guard decides on
|
||||
// with the memory governor installed: MemAvailable limited by the cgroup headroom, the same number every guard
|
||||
// decides on
|
||||
if let Some(governor) = leleka_memory::Governor::global() {
|
||||
return governor.available_now();
|
||||
}
|
||||
|
||||
@@ -81,19 +81,26 @@ pub fn model_geometry(facts: &OriginalSessionFacts) -> ModelGeometry {
|
||||
|
||||
/// The authoritative host copy mirrors the pool set of the format.
|
||||
fn host_pools(q: &OriginalQsaFacts) -> HostPools {
|
||||
let streamed = q.mode != 0;
|
||||
let (k_pool, v_pool) = (q.has("k_pool"), q.has("v_pool"));
|
||||
let int8 = q.kv_int8 || q.kv_hybrid;
|
||||
HostPools {
|
||||
k_pool: streamed && k_pool,
|
||||
v_pool: streamed && v_pool,
|
||||
k_q: streamed && int8 && !q.kv_q4 && q.has("k_q"),
|
||||
v_q: streamed && q.kv_int8 && !q.kv_q4 && q.has("v_q"),
|
||||
k_scale: streamed && q.kv_int8 && q.has("k_scale"),
|
||||
v_scale: streamed && q.kv_int8 && q.has("v_scale"),
|
||||
k_q4: streamed && q.kv_q4 && q.has("k_q4"),
|
||||
v_q4: streamed && (q.kv_q4 || q.kv_hybrid) && q.has("v_q4"),
|
||||
if q.mode == 0 {
|
||||
return HostPools::default();
|
||||
}
|
||||
let mut pools = HostPools { k_pool: q.has("k_pool"), v_pool: q.has("v_pool"), ..HostPools::default() };
|
||||
int8_pools(q, &mut pools);
|
||||
q4_pools(q, &mut pools);
|
||||
pools
|
||||
}
|
||||
|
||||
fn int8_pools(q: &OriginalQsaFacts, pools: &mut HostPools) {
|
||||
let int8 = q.kv_int8 || q.kv_hybrid;
|
||||
pools.k_q = int8 && !q.kv_q4 && q.has("k_q");
|
||||
pools.v_q = q.kv_int8 && !q.kv_q4 && q.has("v_q");
|
||||
pools.k_scale = q.kv_int8 && q.has("k_scale");
|
||||
pools.v_scale = q.kv_int8 && q.has("v_scale");
|
||||
}
|
||||
|
||||
fn q4_pools(q: &OriginalQsaFacts, pools: &mut HostPools) {
|
||||
pools.k_q4 = q.kv_q4 && q.has("k_q4");
|
||||
pools.v_q4 = (q.kv_q4 || q.kv_hybrid) && q.has("v_q4");
|
||||
}
|
||||
|
||||
fn stream_map(q: &OriginalQsaFacts) -> StreamMap {
|
||||
|
||||
@@ -58,7 +58,8 @@ fn report_timing(stack: &OriginalServeStack<'_, '_>, label: &str, produced: usiz
|
||||
let (prompt_ms, decode_ms) = stack.last_timing();
|
||||
let rate = if decode_ms > 0.0 { produced as f64 * 1e3 / decode_ms } else { 0.0 };
|
||||
eprintln!(
|
||||
"DBG timing {label}: prompt {prompt_ms:.1} ms, decode {decode_ms:.1} ms, produced {produced}, decode {rate:.2} tok/s"
|
||||
"DBG timing {label}: prompt {prompt_ms:.1} ms, decode {decode_ms:.1} ms, produced {produced}, \
|
||||
decode {rate:.2} tok/s"
|
||||
);
|
||||
if let Some(stats) = stack.expert_tier_stats() {
|
||||
eprintln!("DBG timing {label}: {}", stats.describe());
|
||||
|
||||
@@ -65,8 +65,10 @@ impl FiveCaseReport {
|
||||
json!({"schema":1,"admission":self.admission,"cases":cases,
|
||||
"boundary_error":self.boundary_error,"one_loaded_owner":true,
|
||||
"fresh_target_draft_each_case":true,"retained_prefix_tokens":0,
|
||||
"cache_state":"same retained expert/KAR/dense owners; actual per-case before/after counters recorded; no cold/warm equivalence assumption",
|
||||
"scope":"owner generation through Usage/terminal, true channel EOF and consumer join; no HTTP/end-agent claim",
|
||||
"cache_state":"same retained expert/KAR/dense owners; actual per-case before/after counters recorded; \
|
||||
no cold/warm equivalence assumption",
|
||||
"scope":"owner generation through Usage/terminal, true channel EOF and consumer join; \
|
||||
no HTTP/end-agent claim",
|
||||
"quality_against_original17":null,"paired_performance_accepted":false,
|
||||
"requires_root_matching_genuine_original17_cases":true})
|
||||
}
|
||||
|
||||
+36
-17
@@ -100,13 +100,21 @@ fn request_for_band(tokenizer: &Tokenizer, lower: usize) -> io::Result<(String,
|
||||
// Search is bounded and every count is from the complete real frame. The
|
||||
// bracket must remain monotone for this filler or we refuse, never invent IDs.
|
||||
let upper = lower.checked_add(255).ok_or_else(|| refused("band overflow"))?;
|
||||
let mut lo = 0usize;
|
||||
let mut hi = 480000usize; // <=960KB filler; renderer overhead separately checked.
|
||||
let mut lo_count = encoded(tokenizer, lo)?.2.len();
|
||||
let mut hi_count = encoded(tokenizer, hi)?.2.len();
|
||||
let lo = 0usize;
|
||||
let hi = 480000usize; // <=960KB filler; renderer overhead separately checked.
|
||||
let lo_count = encoded(tokenizer, lo)?.2.len();
|
||||
let hi_count = encoded(tokenizer, hi)?.2.len();
|
||||
if lo_count >= lower || hi_count <= upper {
|
||||
return Err(refused("public count band not bracketed"));
|
||||
}
|
||||
bisect_band(tokenizer, (lower, upper), [(lo, lo_count), (hi, hi_count)])
|
||||
}
|
||||
/// The bounded bisection between the two bracket ends (`(filler length, framed count)` each).
|
||||
fn bisect_band(
|
||||
tokenizer: &Tokenizer,
|
||||
(lower, upper): (usize, usize),
|
||||
[(mut lo, mut lo_count), (mut hi, mut hi_count)]: [(usize, usize); 2],
|
||||
) -> io::Result<(String, String, Vec<u32>)> {
|
||||
for _ in 0..22 {
|
||||
if hi <= lo + 1 {
|
||||
break;
|
||||
@@ -134,7 +142,8 @@ fn json_bytes(value: &Value) -> io::Result<Vec<u8>> {
|
||||
/// The artifacts of one band: its request, framed prompt and IDs are appended to `artifacts`; returns its frame entry.
|
||||
fn band_frame(tokenizer: &Tokenizer, lower: usize, artifacts: &mut Vec<Artifact>) -> io::Result<Value> {
|
||||
let (body, prompt, ids) = request_for_band(tokenizer, lower)?;
|
||||
let request = json!({"model":"pinned-native-model","instructions":INSTRUCTIONS,"input":body,"tools":[],"max_output_tokens":OUTPUT,"temperature":0,"stream":true,"store":false});
|
||||
let request = json!({"model":"pinned-native-model","instructions":INSTRUCTIONS,"input":body,"tools":[],
|
||||
"max_output_tokens":OUTPUT,"temperature":0,"stream":true,"store":false});
|
||||
let request_bytes = json_bytes(&request)?;
|
||||
if request_bytes.len() > BYTE_CAP || prompt.len() > BYTE_CAP || ids.len() + OUTPUT > CONTEXT {
|
||||
return Err(refused("actual request/prompt/context cap"));
|
||||
@@ -204,6 +213,26 @@ fn write_artifacts(output: &Path, artifacts: Vec<Artifact>) -> io::Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The band artifacts followed by the shared `FRAME.json`; returns the shared frame summary and every artifact.
|
||||
fn build_artifacts(tokenizer: &Tokenizer, bound_model_digest: &str) -> io::Result<(Value, Vec<Artifact>)> {
|
||||
let mut artifacts = Vec::<Artifact>::new();
|
||||
let mut frames = Vec::<Value>::new();
|
||||
for lower in [170000usize, 190000usize] {
|
||||
frames.push(band_frame(tokenizer, lower, &mut artifacts)?);
|
||||
}
|
||||
let frame = push_frame_summary(frames, bound_model_digest, &mut artifacts)?;
|
||||
Ok((frame, artifacts))
|
||||
}
|
||||
/// The serialized total of the artifacts, refused over the aggregate cap or the caller's remaining budget.
|
||||
fn artifacts_total(artifacts: &[Artifact], remaining_artifact_bytes: usize) -> io::Result<usize> {
|
||||
let total = artifacts
|
||||
.iter()
|
||||
.try_fold(0usize, |n, a| n.checked_add(a.bytes.len()).ok_or_else(|| refused("artifact total overflow")))?;
|
||||
if total > ARTIFACT_CAP || total > remaining_artifact_bytes {
|
||||
return Err(refused("aggregate artifacts cap"));
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
/// Returns compact shared FRAME metadata after writing all public artifacts.
|
||||
/// Caller supplies the actual ModelBinding digest and its already-built tokenizer;
|
||||
/// this function does not certify a caller-supplied tokenizer's provenance.
|
||||
@@ -218,18 +247,8 @@ pub(crate) fn produce_on_bound_tokenizer(
|
||||
return Err(refused("wrong bound model"));
|
||||
}
|
||||
check_fresh_output(output)?;
|
||||
let mut artifacts = Vec::<Artifact>::new();
|
||||
let mut frames = Vec::<Value>::new();
|
||||
for lower in [170000usize, 190000usize] {
|
||||
frames.push(band_frame(tokenizer, lower, &mut artifacts)?);
|
||||
}
|
||||
let frame = push_frame_summary(frames, bound_model_digest, &mut artifacts)?;
|
||||
let total = artifacts
|
||||
.iter()
|
||||
.try_fold(0usize, |n, a| n.checked_add(a.bytes.len()).ok_or_else(|| refused("artifact total overflow")))?;
|
||||
if total > ARTIFACT_CAP || total > remaining_artifact_bytes {
|
||||
return Err(refused("aggregate artifacts cap"));
|
||||
}
|
||||
let (frame, artifacts) = build_artifacts(tokenizer, bound_model_digest)?;
|
||||
let total = artifacts_total(&artifacts, remaining_artifact_bytes)?;
|
||||
// Atomically reserve the actual serialized total in the caller's shared
|
||||
// whole-package budget before writes, including FRAME JSON newline.
|
||||
reserve(total)?;
|
||||
|
||||
+23
-7
@@ -68,20 +68,33 @@ pub(super) fn save_cleanup(
|
||||
catch_unwind(AssertUnwindSafe(|| artifacts.save()))
|
||||
}
|
||||
|
||||
fn cache_before(candidate: &std::thread::Result<fivecase_runtime::FiveCaseReport>) -> Option<Value> {
|
||||
candidate.as_ref().ok().map(|report| report.json_after_teardown()["cases"][0]["cache_before"].clone())
|
||||
}
|
||||
|
||||
fn cache_after(candidate: &std::thread::Result<fivecase_runtime::FiveCaseReport>) -> Option<Value> {
|
||||
candidate
|
||||
.as_ref()
|
||||
.ok()
|
||||
.map(|report| report.json_after_teardown()["cases"].as_array().unwrap().last().unwrap()["cache_after"].clone())
|
||||
}
|
||||
|
||||
impl CleanupArtifacts<'_> {
|
||||
fn owner_wall_json(&self) -> Value {
|
||||
let (candidate, wall) = (self.candidate, &self.torn.wall);
|
||||
json!({"schema":1,"valid":wall.valid,
|
||||
"error":wall.error,"rows":wall.rows,
|
||||
"metadata":self.hardware,"owner_output_directory":self.root,
|
||||
"cache_before":candidate.as_ref().ok().map(|report|report.json_after_teardown()["cases"][0]["cache_before"].clone()),
|
||||
"cache_after":candidate.as_ref().ok().map(|report|report.json_after_teardown()["cases"].as_array().unwrap().last().unwrap()["cache_after"].clone()),
|
||||
"scope":"six fixed producer categories during actual owner generation; excludes loading, preload and helper",
|
||||
"cache_before":cache_before(candidate),
|
||||
"cache_after":cache_after(candidate),
|
||||
"scope":"six fixed producer categories during actual owner generation; excludes loading, preload and \
|
||||
helper",
|
||||
"drained_after_all_attempted_teardown":true,
|
||||
"counts":"attempted mixed scalar/group/role/drain invocations, including errors; not products or tokens",
|
||||
"clock":"inclusive CPU owner wall with existing completion waits; not GPU service time",
|
||||
"nested_totals_not_additive":true,"complete_request_accounting":false,
|
||||
"overhead":"one Instant pair and bounded TLS accounting per armed invocation; diagnostic run has instrumentation overhead",
|
||||
"overhead":"one Instant pair and bounded TLS accounting per armed invocation; diagnostic run has \
|
||||
instrumentation overhead",
|
||||
"additional_cuda_calls":0,"additional_tensor_reads":0,
|
||||
"performance_acceptance":false})
|
||||
}
|
||||
@@ -161,12 +174,15 @@ fn case1_native_parity(five_json: &Value, baseline: &Baseline) -> bool {
|
||||
fn quality_json(hardware: &Value, driver_version: &Value, allocated: usize, parity: bool) -> Value {
|
||||
json!({"case1_retained_native_parity":parity,
|
||||
"quality_against_original17":null,"requires_matching_original_five":true,
|
||||
"changed_owner_policy":"incremental-capture-strata-adaptive-4-96-CPU-miss-event-shared192-gdn-journal-qk40960-qsa108544",
|
||||
"changed_owner_policy":"incremental-capture-strata-adaptive-4-96-CPU-miss-event-shared192-gdn-journal-\
|
||||
qk40960-qsa108544",
|
||||
"spill_floor_bytes":1073741824u64,"actual_cuda_driver_version":driver_version,
|
||||
"model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"hardware":hardware,
|
||||
"allocated":allocated,"cleanup_complete":true,"same_request_case1":true,
|
||||
"cache_state":"no replayed helper; actual per-case before/after counters; same loaded owners but fresh target/draft each request",
|
||||
"GateC":false,"GateD":false,"performance_acceptance":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false})
|
||||
"cache_state":"no replayed helper; actual per-case before/after counters; same loaded owners but fresh \
|
||||
target/draft each request",
|
||||
"GateC":false,"GateD":false,"performance_acceptance":false,"HTTP_endagent_speed_claim":false,
|
||||
"longcontext_170K":false})
|
||||
}
|
||||
|
||||
/// The final judgement once every teardown attempt was made: the documents, the assertions and the parity.
|
||||
|
||||
@@ -83,8 +83,9 @@ pub(crate) fn install(laptop: bool, settings: &Settings) -> Result<&'static Gove
|
||||
fn bank_item(g: &Governor, args: &StartArgs, settings: &Settings) -> FixedItem {
|
||||
if args.expert_source_mapped {
|
||||
let total = g.probe().effective_total().unwrap_or(0);
|
||||
// `LELEKA_MAPPED_WORKING_SET_GIB`: the hot part the plan should expect to stay resident when the desktop competes for RAM (the workstation
|
||||
// preset on Windows sets it; the OS still decides what is really resident, this is the accounting of the start check and the cache budgets).
|
||||
// `LELEKA_MAPPED_WORKING_SET_GIB`: the hot part the plan should expect to stay resident when the desktop
|
||||
// competes for RAM (the workstation preset on Windows sets it; the OS still decides what is really resident,
|
||||
// this is the accounting of the start check and the cache budgets).
|
||||
let reserve = settings.serve.mapped_working_set_gib.map_or_else(
|
||||
|| mapped_working_set(total, RESIDENT_BANK_BYTES),
|
||||
|gib| ((gib * (1u64 << 30) as f64) as u64).min(RESIDENT_BANK_BYTES),
|
||||
@@ -124,7 +125,8 @@ fn fixed_items(g: &Governor, args: &StartArgs, settings: &Settings) -> Vec<Fixed
|
||||
"rings_staging_pool_checkpoints",
|
||||
if args.expert_source_mapped { OTHER_FIXED_ESTIMATE } else { OTHER_FIXED_ESTIMATE_RESIDENT },
|
||||
Space::HostPinned,
|
||||
"dense weights host side, native head, MoE arena, MTP pins, CPU pool, empty-prompt checkpoints (measured, docs/memory-safety.md section 3)",
|
||||
"dense weights host side, native head, MoE arena, MTP pins, CPU pool, empty-prompt checkpoints (measured, \
|
||||
docs/memory-safety.md section 3)",
|
||||
));
|
||||
fixed
|
||||
}
|
||||
@@ -186,8 +188,8 @@ pub(crate) fn guard_archive(
|
||||
if archive.file_backed() {
|
||||
return Ok(());
|
||||
}
|
||||
// A sparse memfd (`--kar-sparse-extents-sha256`) holds only the extents the serve path reads: lock, heal and count those, never a hole
|
||||
// (locking a hole allocates zero pages for it).
|
||||
// A sparse memfd (`--kar-sparse-extents-sha256`) holds only the extents the serve path reads: lock, heal and
|
||||
// count those, never a hole (locking a hole allocates zero pages for it).
|
||||
let extents = archive.sparse_extents();
|
||||
g.guard_archive_extents(
|
||||
archive.archive_handle().as_fd(),
|
||||
|
||||
@@ -223,7 +223,6 @@ pub(crate) fn config_identity_digest(config: &KarExpertSourceConfig) -> [u8; 32]
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
|
||||
fn run_device(context: &Context<'_>, rows: &[GpuRows; 3], packets: &[Vec<u8>; 3], input: &[f32]) -> Result<Box<[f32]>> {
|
||||
use super::kar_levels::{driver_geometry, driver_shape};
|
||||
use leleka_cuda_driver::kar_decode_levels::KarDecodeError;
|
||||
use leleka_cuda_driver::kar_decode_levels_gpu::{KarDecodeLevels, KarMatrix};
|
||||
let matrix = |i: usize| -> Result<KarMatrix<'_>> {
|
||||
// The driver derives the launch geometry independently; any
|
||||
@@ -232,7 +231,15 @@ fn run_device(context: &Context<'_>, rows: &[GpuRows; 3], packets: &[Vec<u8>; 3]
|
||||
.ok_or(KarSourceError::Layout("planner and driver geometry disagree"))?;
|
||||
Ok(KarMatrix { geometry, shape: driver_shape(&rows[i]), packet: &packets[i] })
|
||||
};
|
||||
let map = |error: KarDecodeError| match error {
|
||||
let (gate, up, down) = (matrix(0)?, matrix(1)?, matrix(2)?);
|
||||
let program = KarDecodeLevels::open(context).map_err(device_error)?;
|
||||
program.expert_mlp_to_host(&gate, &up, &down, input).map(Vec::into_boxed_slice).map_err(device_error)
|
||||
}
|
||||
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
|
||||
fn device_error(error: leleka_cuda_driver::kar_decode_levels::KarDecodeError) -> KarSourceError {
|
||||
use leleka_cuda_driver::kar_decode_levels::KarDecodeError;
|
||||
match error {
|
||||
KarDecodeError::Unpinned => KarSourceError::Unsupported,
|
||||
KarDecodeError::NonFinite => KarSourceError::NonFinite,
|
||||
KarDecodeError::DeviceStatus(_) => KarSourceError::Device("device status"),
|
||||
@@ -240,10 +247,7 @@ fn run_device(context: &Context<'_>, rows: &[GpuRows; 3], packets: &[Vec<u8>; 3]
|
||||
KarDecodeError::Driver(leleka_cuda_driver::Error::BudgetExceeded)
|
||||
| KarDecodeError::Driver(leleka_cuda_driver::Error::HostAllocation) => KarSourceError::Budget,
|
||||
KarDecodeError::Driver(_) => KarSourceError::Device("driver"),
|
||||
};
|
||||
let (gate, up, down) = (matrix(0)?, matrix(1)?, matrix(2)?);
|
||||
let program = KarDecodeLevels::open(context).map_err(map)?;
|
||||
program.expert_mlp_to_host(&gate, &up, &down, input).map(Vec::into_boxed_slice).map_err(map)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))]
|
||||
|
||||
@@ -11,25 +11,32 @@ pub(crate) use leleka_model_format::kar_levels::{
|
||||
};
|
||||
|
||||
use leleka_cuda_driver::kar_decode_levels::{DecodeGeometry, MultiplyGeometry};
|
||||
use leleka_model_format::kar_kernel_model::WindowPlan;
|
||||
use leleka_model_format::kar_kernel_model::{DecodeParams, WindowPlan};
|
||||
|
||||
/// The driver-side geometry for a planned window, or `None` if the driver's
|
||||
/// own derivation disagrees with the planner (planner/driver drift).
|
||||
pub(crate) fn driver_geometry(plan: &WindowPlan) -> Option<DecodeGeometry> {
|
||||
let g = DecodeGeometry::for_window(u32::from(plan.level), plan.group, plan.start, u64::from(plan.count)).ok()?;
|
||||
let p = &plan.params;
|
||||
let same = g.level == p.level
|
||||
let same = same_header(&g, p) && same_layout(&g, p);
|
||||
(same && g.validate().is_ok()).then_some(g)
|
||||
}
|
||||
|
||||
fn same_header(g: &DecodeGeometry, p: &DecodeParams) -> bool {
|
||||
g.level == p.level
|
||||
&& g.group == p.group
|
||||
&& g.count == p.count
|
||||
&& g.head32 == p.head32
|
||||
&& g.head_group == p.head_group
|
||||
&& g.scales_offset == p.scales_offset
|
||||
}
|
||||
|
||||
fn same_layout(g: &DecodeGeometry, p: &DecodeParams) -> bool {
|
||||
g.scales_offset == p.scales_offset
|
||||
&& g.planes_offset == p.planes_offset
|
||||
&& g.plane_stride_words == p.plane_stride_words
|
||||
&& g.window_words == p.window_words
|
||||
&& g.window_groups == p.window_groups
|
||||
&& g.packet_bytes == p.packet_bytes;
|
||||
(same && g.validate().is_ok()).then_some(g)
|
||||
&& g.packet_bytes == p.packet_bytes
|
||||
}
|
||||
|
||||
pub(crate) fn driver_shape(rows: &GpuRows) -> MultiplyGeometry {
|
||||
|
||||
@@ -98,16 +98,24 @@ fn index(role: GdnMatrixRole) -> usize {
|
||||
}
|
||||
}
|
||||
fn kind(kind: u32, bf16_only: bool) -> InputResult<GdnMatrixKind> {
|
||||
Ok(match kind {
|
||||
0 | 30 => GdnMatrixKind::Bf16,
|
||||
8 if !bf16_only => GdnMatrixKind::Q8_0,
|
||||
12 if !bf16_only => GdnMatrixKind::Q4K,
|
||||
13 if !bf16_only => GdnMatrixKind::Q5K,
|
||||
14 if !bf16_only => GdnMatrixKind::Q6K,
|
||||
20 if !bf16_only => GdnMatrixKind::Iq4Nl,
|
||||
23 if !bf16_only => GdnMatrixKind::Iq4Xs,
|
||||
_ => return Err(E::UnsupportedKind),
|
||||
})
|
||||
if matches!(kind, 0 | 30) {
|
||||
return Ok(GdnMatrixKind::Bf16);
|
||||
}
|
||||
if bf16_only {
|
||||
return Err(E::UnsupportedKind);
|
||||
}
|
||||
quantised_kind(kind).ok_or(E::UnsupportedKind)
|
||||
}
|
||||
fn quantised_kind(kind: u32) -> Option<GdnMatrixKind> {
|
||||
match kind {
|
||||
8 => Some(GdnMatrixKind::Q8_0),
|
||||
12 => Some(GdnMatrixKind::Q4K),
|
||||
13 => Some(GdnMatrixKind::Q5K),
|
||||
14 => Some(GdnMatrixKind::Q6K),
|
||||
20 => Some(GdnMatrixKind::Iq4Nl),
|
||||
23 => Some(GdnMatrixKind::Iq4Xs),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn descriptor(
|
||||
kind_value: u32,
|
||||
@@ -241,10 +249,7 @@ impl ModelBinding {
|
||||
let layer8 = u8::try_from(layer).map_err(|_| E::Range)?;
|
||||
let matrices = gdn_matrices(&mut artifact, layer8)?;
|
||||
admit_small_weights(&mut artifact, layer8)?;
|
||||
let conv = read_f32(&mut artifact, gdn_role(layer8, LayerRole::SsmConv1d), 4, 10240)?;
|
||||
let a = read_f32(&mut artifact, gdn_role(layer8, LayerRole::SsmA), 48, 1)?;
|
||||
let dt = read_f32(&mut artifact, gdn_role(layer8, LayerRole::SsmDtBias), 48, 1)?;
|
||||
let norm = read_f32(&mut artifact, gdn_role(layer8, LayerRole::SsmNorm), 128, 1)?;
|
||||
let (conv, a, dt, norm) = read_small_weights(&mut artifact, layer8)?;
|
||||
Ok(GdnWeights { binding: self.identity(), layer, matrices, conv, a, dt, norm, epsilon })
|
||||
}
|
||||
pub(crate) fn gdn_matrix_block(
|
||||
@@ -263,13 +268,7 @@ impl ModelBinding {
|
||||
}
|
||||
let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?;
|
||||
let bf16_only = matches!(role, GdnMatrixRole::Alpha | GdnMatrixRole::Beta);
|
||||
admit_block_tensor(&mut artifact, &m, bf16_only)?;
|
||||
let row_size = super::decode::row_bytes(m.kind, m.columns)?;
|
||||
let output_row = if m.kind == 0 { m.columns.checked_mul(2).ok_or(E::Geometry)? } else { row_size };
|
||||
let mut bytes = Vec::new();
|
||||
bytes.try_reserve_exact(output_row.checked_mul(count).ok_or(E::Geometry)?).map_err(|_| E::Allocation)?;
|
||||
let packed = read_packed_rows(&mut artifact, &m, (first, count), row_size)?;
|
||||
append_gdn_rows(&mut bytes, &packed, &m, row_size)?;
|
||||
let bytes = read_block_bytes(&mut artifact, &m, bf16_only, (first, count))?;
|
||||
Ok(GdnWeightBlock {
|
||||
kind: kind(m.kind, false)?,
|
||||
columns: m.columns,
|
||||
@@ -278,6 +277,33 @@ impl ModelBinding {
|
||||
})
|
||||
}
|
||||
}
|
||||
/// The device bytes of the rows `[first, first + count)` of an admitted matrix.
|
||||
fn read_block_bytes(
|
||||
artifact: &mut Qwen4ExpArtifact,
|
||||
m: &Matrix,
|
||||
bf16_only: bool,
|
||||
(first, count): (usize, usize),
|
||||
) -> InputResult<Vec<u8>> {
|
||||
admit_block_tensor(artifact, m, bf16_only)?;
|
||||
let row_size = super::decode::row_bytes(m.kind, m.columns)?;
|
||||
let output_row = if m.kind == 0 { m.columns.checked_mul(2).ok_or(E::Geometry)? } else { row_size };
|
||||
let mut bytes = Vec::new();
|
||||
bytes.try_reserve_exact(output_row.checked_mul(count).ok_or(E::Geometry)?).map_err(|_| E::Allocation)?;
|
||||
let packed = read_packed_rows(artifact, m, (first, count), row_size)?;
|
||||
append_gdn_rows(&mut bytes, &packed, m, row_size)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
/// The conv, A, dt-bias and norm vectors of a GDN layer, read in this order.
|
||||
fn read_small_weights(
|
||||
artifact: &mut Qwen4ExpArtifact,
|
||||
layer: u8,
|
||||
) -> InputResult<(Box<[f32]>, Box<[f32]>, Box<[f32]>, Box<[f32]>)> {
|
||||
let conv = read_f32(artifact, gdn_role(layer, LayerRole::SsmConv1d), 4, 10240)?;
|
||||
let a = read_f32(artifact, gdn_role(layer, LayerRole::SsmA), 48, 1)?;
|
||||
let dt = read_f32(artifact, gdn_role(layer, LayerRole::SsmDtBias), 48, 1)?;
|
||||
let norm = read_f32(artifact, gdn_role(layer, LayerRole::SsmNorm), 128, 1)?;
|
||||
Ok((conv, a, dt, norm))
|
||||
}
|
||||
fn block_range(first: usize, count: usize, rows: usize) -> InputResult<()> {
|
||||
if count == 0 || count > 64 || first.checked_add(count).is_none_or(|end| end > rows) {
|
||||
return Err(E::Range);
|
||||
|
||||
@@ -69,15 +69,26 @@ fn read_norm(artifact: &mut super::Qwen4ExpArtifact, norm_role: TensorRole) -> I
|
||||
Ok(norm.into_boxed_slice())
|
||||
}
|
||||
|
||||
type GrTensors = (Box<[f32]>, Box<[u16]>, Box<[u16]>, Option<Box<[u16]>>);
|
||||
|
||||
/// The norm row, then the down, up and optional inject matrices, read in this order.
|
||||
fn read_gr_tensors(
|
||||
artifact: &mut super::Qwen4ExpArtifact,
|
||||
roles: &[Option<RoleDescriptor>; 4],
|
||||
) -> InputResult<GrTensors> {
|
||||
let norm = read_norm(artifact, roles[0].ok_or(InputBindingError::Geometry)?.0)?;
|
||||
let down = read_bf16(artifact, roles[1].ok_or(InputBindingError::Geometry)?)?;
|
||||
let up = read_bf16(artifact, roles[2].ok_or(InputBindingError::Geometry)?)?;
|
||||
let inject = roles[3].map(|descriptor| read_bf16(artifact, descriptor)).transpose()?;
|
||||
Ok((norm, down, up, inject))
|
||||
}
|
||||
|
||||
impl ModelBinding {
|
||||
pub(crate) fn gr_weights(&self, role: GrRole) -> InputResult<GrWeights> {
|
||||
let roles = role_set(role, self.layer_count())?;
|
||||
let mut artifact = self.artifact.try_borrow_mut().map_err(|_| InputBindingError::Busy)?;
|
||||
admit_role_set(&mut artifact, &roles)?;
|
||||
let norm = read_norm(&mut artifact, roles[0].ok_or(InputBindingError::Geometry)?.0)?;
|
||||
let down = read_bf16(&mut artifact, roles[1].ok_or(InputBindingError::Geometry)?)?;
|
||||
let up = read_bf16(&mut artifact, roles[2].ok_or(InputBindingError::Geometry)?)?;
|
||||
let inject = roles[3].map(|descriptor| read_bf16(&mut artifact, descriptor)).transpose()?;
|
||||
let (norm, down, up, inject) = read_gr_tensors(&mut artifact, &roles)?;
|
||||
Ok(GrWeights {
|
||||
binding: self.identity(),
|
||||
role,
|
||||
|
||||
@@ -159,6 +159,7 @@ fn inherited_real_memfd_requires_irreversible_seals_and_independent_owned_handle
|
||||
drop(fixture);
|
||||
assert!(!directory.exists());
|
||||
println!(
|
||||
"INHERITED_KAR_SEALS COMPLETE bytes=8 fd_refusals=13 provenance_refusals=2 kernel_irreversible=4 cleanup=complete"
|
||||
"INHERITED_KAR_SEALS COMPLETE bytes=8 fd_refusals=13 provenance_refusals=2 kernel_irreversible=4 \
|
||||
cleanup=complete"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,22 +1,26 @@
|
||||
use super::{InputBindingError, InputResult};
|
||||
use leleka_quant_core as quant;
|
||||
|
||||
/// `(kind, elements per block, bytes per block)` of every supported source kind.
|
||||
const BLOCKS: [(u32, usize, usize); 13] = [
|
||||
(0, 1, 4),
|
||||
(1, 1, 2),
|
||||
(30, 1, 2),
|
||||
(8, 32, 34),
|
||||
(12, 256, 144),
|
||||
(13, 256, 176),
|
||||
(14, 256, 210),
|
||||
(18, 256, 98),
|
||||
(20, 32, 18),
|
||||
(21, 256, 110),
|
||||
(22, 256, 82),
|
||||
(23, 256, 136),
|
||||
(42, 64, 18),
|
||||
];
|
||||
|
||||
pub(super) fn row_bytes(kind: u32, values: usize) -> InputResult<usize> {
|
||||
let (elements, bytes) = match kind {
|
||||
0 => (1, 4),
|
||||
1 | 30 => (1, 2),
|
||||
8 => (32, 34),
|
||||
12 => (256, 144),
|
||||
13 => (256, 176),
|
||||
14 => (256, 210),
|
||||
18 => (256, 98),
|
||||
20 => (32, 18),
|
||||
21 => (256, 110),
|
||||
22 => (256, 82),
|
||||
23 => (256, 136),
|
||||
42 => (64, 18),
|
||||
_ => return Err(InputBindingError::UnsupportedKind),
|
||||
};
|
||||
let (_, elements, bytes) =
|
||||
*BLOCKS.iter().find(|block| block.0 == kind).ok_or(InputBindingError::UnsupportedKind)?;
|
||||
if values == 0 || !values.is_multiple_of(elements) {
|
||||
return Err(InputBindingError::Geometry);
|
||||
}
|
||||
@@ -50,20 +54,24 @@ fn scalar(kind: u32, bytes: &[u8], output: &mut [f32]) {
|
||||
}
|
||||
}
|
||||
}
|
||||
type Decoder = fn(&[u8], &mut [f32]) -> Result<(), String>;
|
||||
|
||||
/// The block decoder of every packed source kind.
|
||||
const DECODERS: [(u32, Decoder); 10] = [
|
||||
(8, quant::q8_0::decode_into),
|
||||
(12, quant::q4_k::decode_into),
|
||||
(13, quant::q5_k::decode_into),
|
||||
(14, quant::q6_k::decode_into),
|
||||
(18, quant::iq3_xxs::decode_into),
|
||||
(20, quant::iq4_nl::decode_into),
|
||||
(21, quant::iq3_s::decode_into),
|
||||
(22, quant::iq2_s::decode_into),
|
||||
(23, quant::iq4_xs::decode_into),
|
||||
(42, quant::q2_0::decode_into),
|
||||
];
|
||||
|
||||
fn packed(kind: u32, bytes: &[u8], output: &mut [f32]) -> InputResult<()> {
|
||||
let decode = match kind {
|
||||
8 => quant::q8_0::decode_into,
|
||||
12 => quant::q4_k::decode_into,
|
||||
13 => quant::q5_k::decode_into,
|
||||
14 => quant::q6_k::decode_into,
|
||||
18 => quant::iq3_xxs::decode_into,
|
||||
20 => quant::iq4_nl::decode_into,
|
||||
21 => quant::iq3_s::decode_into,
|
||||
22 => quant::iq2_s::decode_into,
|
||||
23 => quant::iq4_xs::decode_into,
|
||||
42 => quant::q2_0::decode_into,
|
||||
_ => return Err(InputBindingError::UnsupportedKind),
|
||||
};
|
||||
let decode = DECODERS.iter().find(|entry| entry.0 == kind).ok_or(InputBindingError::UnsupportedKind)?.1;
|
||||
decode(bytes, output).map_err(|_| InputBindingError::Geometry)
|
||||
}
|
||||
|
||||
|
||||
+16
-8
@@ -192,13 +192,26 @@ pub(super) fn reopen_read_only_archive(source: &File, expected_bytes: u64) -> In
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(super) fn verify_open_provenance(file: &File, expected_digest: [u8; 32]) -> InputResult<()> {
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::os::unix::fs::FileExt;
|
||||
use sha2::Digest;
|
||||
let meta = file.metadata().map_err(private_copy::provenance_error)?;
|
||||
let length = meta.len();
|
||||
if !meta.is_file() || length == 0 || length > 1024 * 1024 {
|
||||
return Err(InputBindingError::Range);
|
||||
}
|
||||
let digest = hash_file(file, length)?;
|
||||
if file.metadata().map_err(private_copy::provenance_error)?.len() != length
|
||||
|| digest.finalize().as_slice() != expected_digest
|
||||
{
|
||||
return Err(InputBindingError::Metadata);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// SHA-256 state over the first `length` bytes of the file, read in 64 KiB blocks.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn hash_file(file: &File, length: u64) -> InputResult<sha2::Sha256> {
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::os::unix::fs::FileExt;
|
||||
let mut digest = Sha256::new();
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
let mut offset = 0u64;
|
||||
@@ -209,10 +222,5 @@ pub(super) fn verify_open_provenance(file: &File, expected_digest: [u8; 32]) ->
|
||||
digest.update(&buffer[..count]);
|
||||
offset += count as u64;
|
||||
}
|
||||
if file.metadata().map_err(private_copy::provenance_error)?.len() != length
|
||||
|| digest.finalize().as_slice() != expected_digest
|
||||
{
|
||||
return Err(InputBindingError::Metadata);
|
||||
}
|
||||
Ok(())
|
||||
Ok(digest)
|
||||
}
|
||||
|
||||
+25
-15
@@ -30,8 +30,8 @@ pub(crate) fn load_pinned_inherited_archive(source: &InheritedKarArchive) -> Inp
|
||||
log_startup_read(source, &artifact);
|
||||
return Ok(artifact);
|
||||
};
|
||||
// A sparse memfd: the digest of its extents, not the archive's SHA-256. The extents the governor locks must be exactly the
|
||||
// ones the verifier hashed and the row reader reads.
|
||||
// A sparse memfd: the digest of its extents, not the archive's SHA-256. The extents the governor locks must be
|
||||
// exactly the ones the verifier hashed and the row reader reads.
|
||||
let artifact =
|
||||
VerifiedKarPleArtifact::verify_sparse(inspection.into_owner_controlled(), profile, &sparse.extents_sha256)
|
||||
.map_err(|e| kar_failure(LoadPhase::Verify, e))?;
|
||||
@@ -42,13 +42,14 @@ pub(crate) fn load_pinned_inherited_archive(source: &InheritedKarArchive) -> Inp
|
||||
Ok(artifact)
|
||||
}
|
||||
|
||||
/// One line in the engine log of what opening the archive read from it: the header, directory and books, and whether the whole archive
|
||||
/// was hashed (a stamp or the parent's attestation makes that 0). The rows a request reads later are not in it; they pass through the
|
||||
/// page cache of an ordinary file one 4 KiB page at a time.
|
||||
/// One line in the engine log of what opening the archive read from it: the header, directory and books, and whether
|
||||
/// the whole archive was hashed (a stamp or the parent's attestation makes that 0). The rows a request reads later are
|
||||
/// not in it; they pass through the page cache of an ordinary file one 4 KiB page at a time.
|
||||
pub(super) fn log_startup_read(source: &InheritedKarArchive, artifact: &VerifiedKarPleArtifact) {
|
||||
let read = artifact.startup_read();
|
||||
eprintln!(
|
||||
"leleka-kar-startup source={} verify={} metadata_bytes={} book_bytes={} hashed_bytes={} total_read_bytes={} identity_recheck={}",
|
||||
"leleka-kar-startup source={} verify={} metadata_bytes={} book_bytes={} hashed_bytes={} \
|
||||
total_read_bytes={} identity_recheck={}",
|
||||
if source.file_backed { "file" } else { "memfd" },
|
||||
read.trust.as_str(),
|
||||
read.metadata_bytes,
|
||||
@@ -171,24 +172,33 @@ pub(super) fn input_diagnostic<W: std::io::Write>(
|
||||
pub(super) fn input_failure(phase: LoadPhase, error: InputBindingError) -> InputBindingError {
|
||||
input_diagnostic(&mut std::io::stderr().lock(), phase, error)
|
||||
}
|
||||
pub(super) fn kar_diagnostic<W: std::io::Write>(sink: &mut W, phase: LoadPhase, failure: &KarError) {
|
||||
let class = match failure {
|
||||
/// The stable class name a failure is logged under.
|
||||
fn kar_class(failure: &KarError) -> &'static str {
|
||||
match failure {
|
||||
KarError::Allocation => "Allocation",
|
||||
KarError::Io(_) => "Io",
|
||||
KarError::Range(_) => "Range",
|
||||
KarError::Format("KAR header CRC-32 mismatch") => "HeaderCrc",
|
||||
KarError::Format(_) => "Format",
|
||||
KarError::Integrity("KAR archive/provenance identity mismatch") => "ArchiveIdentity",
|
||||
KarError::Integrity("KAR full archive SHA-256 mismatch") => "ArchiveSha",
|
||||
KarError::Integrity("KAR payload CRC-32 mismatch") => "PayloadCrc",
|
||||
KarError::Integrity("KAR archive length changed") => "ArchiveLength",
|
||||
KarError::Integrity("KAR sparse extents SHA-256 mismatch") => "ExtentsSha",
|
||||
KarError::Integrity(_) => "Integrity",
|
||||
KarError::Integrity(message) => integrity_class(message),
|
||||
KarError::Profile("KAR PLE partition missing") => "PartitionMissing",
|
||||
KarError::Profile("KAR PLE partition/source mapping mismatch") => "PartitionMapping",
|
||||
KarError::Profile("KAR PLE nonfinite book") => "BookFinite",
|
||||
KarError::Profile(_) => "Profile",
|
||||
};
|
||||
}
|
||||
}
|
||||
fn integrity_class(message: &str) -> &'static str {
|
||||
match message {
|
||||
"KAR archive/provenance identity mismatch" => "ArchiveIdentity",
|
||||
"KAR full archive SHA-256 mismatch" => "ArchiveSha",
|
||||
"KAR payload CRC-32 mismatch" => "PayloadCrc",
|
||||
"KAR archive length changed" => "ArchiveLength",
|
||||
"KAR sparse extents SHA-256 mismatch" => "ExtentsSha",
|
||||
_ => "Integrity",
|
||||
}
|
||||
}
|
||||
pub(super) fn kar_diagnostic<W: std::io::Write>(sink: &mut W, phase: LoadPhase, failure: &KarError) {
|
||||
let class = kar_class(failure);
|
||||
if let KarError::Io(cause) = failure {
|
||||
let _ = writeln!(
|
||||
sink,
|
||||
|
||||
@@ -62,8 +62,7 @@ pub(crate) fn load_pinned_archive(source: &Path, owner_root: &Path) -> InputResu
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(super) fn verify_pinned_provenance(source: &Path) -> InputResult<()> {
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::io::Read;
|
||||
use sha2::Digest;
|
||||
let mut name = source.as_os_str().to_os_string();
|
||||
name.push(".provenance.json");
|
||||
let mut file = private_copy::open_regular(Path::new(&name), None)?;
|
||||
@@ -71,6 +70,18 @@ pub(super) fn verify_pinned_provenance(source: &Path) -> InputResult<()> {
|
||||
if length == 0 || length > 1024 * 1024 {
|
||||
return Err(InputBindingError::Range);
|
||||
}
|
||||
let (digest, total) = hash_stream(&mut file, length)?;
|
||||
if total != length || digest.finalize().as_slice() != PROVENANCE_DIGEST {
|
||||
return Err(InputBindingError::Metadata);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// SHA-256 state and byte count of the file's stream, refused when it holds more than `length` bytes.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn hash_stream(file: &mut File, length: u64) -> InputResult<(sha2::Sha256, u64)> {
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::io::Read;
|
||||
let mut digest = Sha256::new();
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
let mut total = 0u64;
|
||||
@@ -85,10 +96,7 @@ pub(super) fn verify_pinned_provenance(source: &Path) -> InputResult<()> {
|
||||
}
|
||||
digest.update(&buffer[..count]);
|
||||
}
|
||||
if total != length || digest.finalize().as_slice() != PROVENANCE_DIGEST {
|
||||
return Err(InputBindingError::Metadata);
|
||||
}
|
||||
Ok(())
|
||||
Ok((digest, total))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
|
||||
+31
-10
@@ -119,7 +119,7 @@ impl Drop for OwnedCopy {
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(in super::super) fn freeze(source: &mut File, _owner_root: &Path, bytes: u64) -> InputResult<File> {
|
||||
use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, fcntl_get_seals, memfd_create};
|
||||
use rustix::fs::{MemfdFlags, memfd_create};
|
||||
// Safe OwnedFd -> File conversion transfers ownership exactly once.
|
||||
// No pathname, filesystem quota, permission change or privileged call
|
||||
// is needed. Unsupported/failed sealing refuses admission outright.
|
||||
@@ -128,12 +128,32 @@ pub(in super::super) fn freeze(source: &mut File, _owner_root: &Path, bytes: u64
|
||||
let mut writer = File::from(fd);
|
||||
copy_exact(source, &mut writer, bytes)?;
|
||||
writer.sync_all().map_err(|e| phase_error(IoPhase::Sync, e))?;
|
||||
seal_writer(&writer)?;
|
||||
check_sealed_writer(&writer, bytes)?;
|
||||
// A cloned descriptor retains the same sealed inode. Its access mode
|
||||
// cannot bypass the kernel seals. Close the copy writer before return.
|
||||
let mut reader = writer.try_clone().map_err(|e| phase_error(IoPhase::OpenReader, e))?;
|
||||
drop(writer);
|
||||
reader.rewind().map_err(|e| phase_error(IoPhase::OpenReader, e))?;
|
||||
Ok(reader)
|
||||
}
|
||||
|
||||
/// Adds every irreversible seal and checks that the kernel reports all of them.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn seal_writer(writer: &File) -> InputResult<()> {
|
||||
use rustix::fs::{SealFlags, fcntl_add_seals, fcntl_get_seals};
|
||||
let required = SealFlags::WRITE | SealFlags::GROW | SealFlags::SHRINK | SealFlags::SEAL;
|
||||
fcntl_add_seals(&writer, required).map_err(|e| phase_error(IoPhase::Seal, e.into()))?;
|
||||
let actual = fcntl_get_seals(&writer).map_err(|e| phase_error(IoPhase::Seal, e.into()))?;
|
||||
fcntl_add_seals(writer, required).map_err(|e| phase_error(IoPhase::Seal, e.into()))?;
|
||||
let actual = fcntl_get_seals(writer).map_err(|e| phase_error(IoPhase::Seal, e.into()))?;
|
||||
if !actual.contains(required) {
|
||||
return Err(input_failure(LoadPhase::ReaderIdentity, InputBindingError::Metadata));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The sealed memfd is a regular file of exactly `bytes` that no name refers to.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn check_sealed_writer(writer: &File, bytes: u64) -> InputResult<()> {
|
||||
let meta = writer.metadata().map_err(|e| phase_error(IoPhase::WriterMetadata, e))?;
|
||||
if !meta.is_file() || meta.len() != bytes {
|
||||
return Err(input_failure(LoadPhase::ReaderLength, InputBindingError::Range));
|
||||
@@ -141,12 +161,7 @@ pub(in super::super) fn freeze(source: &mut File, _owner_root: &Path, bytes: u64
|
||||
if meta.nlink() != 0 {
|
||||
return Err(input_failure(LoadPhase::ReaderDetached, InputBindingError::Metadata));
|
||||
}
|
||||
// A cloned descriptor retains the same sealed inode. Its access mode
|
||||
// cannot bypass the kernel seals. Close the copy writer before return.
|
||||
let mut reader = writer.try_clone().map_err(|e| phase_error(IoPhase::OpenReader, e))?;
|
||||
drop(writer);
|
||||
reader.rewind().map_err(|e| phase_error(IoPhase::OpenReader, e))?;
|
||||
Ok(reader)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -160,8 +175,14 @@ pub(in super::super) fn freeze(source: &mut File, owner_root: &Path, bytes: u64)
|
||||
let reader = checked_reader(&own, bytes)?;
|
||||
drop(writer);
|
||||
own.detach()?;
|
||||
check_detached(&reader)?;
|
||||
Ok(reader)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn check_detached(reader: &File) -> InputResult<()> {
|
||||
if reader.metadata().map_err(|e| phase_error(IoPhase::DetachedMetadata, e))?.nlink() != 0 {
|
||||
return Err(input_failure(LoadPhase::ReaderDetached, InputBindingError::Metadata));
|
||||
}
|
||||
Ok(reader)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -14,6 +14,11 @@ pub(super) fn validate_row(kind: u32, bytes: &[u8], values: usize) -> InputResul
|
||||
if bytes.len() != super::super::decode::row_bytes(kind, values)? {
|
||||
return Err(E::Geometry);
|
||||
}
|
||||
check_half_scales(kind, bytes, block_bytes)
|
||||
}
|
||||
|
||||
/// Every block's leading half scale is finite.
|
||||
fn check_half_scales(kind: u32, bytes: &[u8], block_bytes: usize) -> InputResult<()> {
|
||||
// These layouts contain exactly one FP16 float field, at offset0. All
|
||||
// remaining fields select bounded integers/signs. For a finite half scale:
|
||||
// IQ3_XXS <=65504*15.5*.5*255; IQ2_S <=65504*15.5*.25*255;
|
||||
|
||||
+26
-14
@@ -71,6 +71,23 @@ fn preload_matrix_role(role: u8) -> InputResult<MoeMatrixRole> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The routed and shared matrices of a layer (gate, up, down each), then its shared gate scalar.
|
||||
fn layer_matrices(artifact: &Qwen4ExpArtifact, layer: u8) -> InputResult<([Matrix; 3], [Matrix; 3])> {
|
||||
let make = |role: LayerRole, routed: bool, down: bool| moe_matrix(artifact, layer, role, (routed, down));
|
||||
let routed = [
|
||||
make(LayerRole::FfnGateExperts, true, false)?,
|
||||
make(LayerRole::FfnUpExperts, true, false)?,
|
||||
make(LayerRole::FfnDownExperts, true, true)?,
|
||||
];
|
||||
let shared = [
|
||||
make(LayerRole::FfnGateShared, false, false)?,
|
||||
make(LayerRole::FfnUpShared, false, false)?,
|
||||
make(LayerRole::FfnDownShared, false, true)?,
|
||||
];
|
||||
check_gate_scalar(artifact, layer)?;
|
||||
Ok((routed, shared))
|
||||
}
|
||||
|
||||
impl ModelBinding {
|
||||
pub(crate) fn moe_expert_weights(&self, layer: u32, selected: [u32; SELECTED]) -> InputResult<MoeExpertWeights> {
|
||||
validate_selected(&selected)?;
|
||||
@@ -80,18 +97,7 @@ impl ModelBinding {
|
||||
let layer_index = u8::try_from(layer).map_err(|_| E::Range)?;
|
||||
let artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?;
|
||||
check_moe_metadata(&artifact)?;
|
||||
let make = |role: LayerRole, routed: bool, down: bool| moe_matrix(&artifact, layer_index, role, (routed, down));
|
||||
let routed = [
|
||||
make(LayerRole::FfnGateExperts, true, false)?,
|
||||
make(LayerRole::FfnUpExperts, true, false)?,
|
||||
make(LayerRole::FfnDownExperts, true, true)?,
|
||||
];
|
||||
let shared = [
|
||||
make(LayerRole::FfnGateShared, false, false)?,
|
||||
make(LayerRole::FfnUpShared, false, false)?,
|
||||
make(LayerRole::FfnDownShared, false, true)?,
|
||||
];
|
||||
check_gate_scalar(&artifact, layer_index)?;
|
||||
let (routed, shared) = layer_matrices(&artifact, layer_index)?;
|
||||
Ok(MoeExpertWeights { binding: self.identity(), layer, selected, routed, shared })
|
||||
}
|
||||
/// Actual bound tensor/expert address; no synthetic selected-route object.
|
||||
@@ -116,13 +122,19 @@ impl ModelBinding {
|
||||
artifact.validate_tensor_source(tensor_role).map_err(|_| E::Read)?;
|
||||
Ok(key)
|
||||
}
|
||||
/// The matrix role and expert of a preload descriptor that names the actual bound tensor.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(crate) fn moe_preload_block(&self, key: MoeWeightDescriptor) -> InputResult<Box<[u8]>> {
|
||||
fn check_preload_key(&self, key: &MoeWeightDescriptor) -> InputResult<(MoeMatrixRole, u32)> {
|
||||
let role = preload_matrix_role(key.role)?;
|
||||
let expert = key.expert.ok_or(E::Range)?;
|
||||
if self.moe_preload_descriptor(key.layer, expert, role)? != key {
|
||||
if self.moe_preload_descriptor(key.layer, expert, role)? != *key {
|
||||
return Err(E::Geometry);
|
||||
}
|
||||
Ok((role, expert))
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(crate) fn moe_preload_block(&self, key: MoeWeightDescriptor) -> InputResult<Box<[u8]>> {
|
||||
let (role, expert) = self.check_preload_key(&key)?;
|
||||
let tensor_role =
|
||||
TensorRole::Layer { layer: u8::try_from(key.layer).map_err(|_| E::Range)?, role: routed_source_role(role) };
|
||||
let row_bytes = key.bytes.checked_div(key.rows).ok_or(E::Geometry)?;
|
||||
|
||||
+16
-6
@@ -107,6 +107,21 @@ impl ModelBinding {
|
||||
}
|
||||
Ok(scalar.into_boxed_slice())
|
||||
}
|
||||
/// The admitted matrix and selected expert of a block request, checked before the artifact is borrowed.
|
||||
fn block_request(
|
||||
&self,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
role: MoeMatrixRole,
|
||||
(first, count): (usize, usize),
|
||||
) -> InputResult<(Matrix, Option<u32>)> {
|
||||
if !weights.matches(&self.identity(), weights.layer) {
|
||||
return Err(E::Metadata);
|
||||
}
|
||||
let matrix = weights.matrix(selection, role)?;
|
||||
validate_range(first, count, matrix.rows)?;
|
||||
Ok((matrix, selected_expert(weights, selection)))
|
||||
}
|
||||
pub(crate) fn moe_expert_block(
|
||||
&self,
|
||||
weights: &MoeExpertWeights,
|
||||
@@ -115,12 +130,7 @@ impl ModelBinding {
|
||||
first: usize,
|
||||
count: usize,
|
||||
) -> InputResult<MoeExpertBlock> {
|
||||
if !weights.matches(&self.identity(), weights.layer) {
|
||||
return Err(E::Metadata);
|
||||
}
|
||||
let matrix = weights.matrix(selection, role)?;
|
||||
validate_range(first, count, matrix.rows)?;
|
||||
let expert = selected_expert(weights, selection);
|
||||
let (matrix, expert) = self.block_request(weights, selection, role, (first, count))?;
|
||||
let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?;
|
||||
check_matrix_tensor(&artifact, &matrix, (expert.is_some(), role == MoeMatrixRole::Down))?;
|
||||
let limit = count.checked_mul(matrix.row_bytes).ok_or(E::Geometry)?;
|
||||
|
||||
+25
-15
@@ -48,22 +48,32 @@ pub(super) fn index(role: MoeMatrixRole) -> usize {
|
||||
}
|
||||
}
|
||||
pub(super) fn matrix_kind(raw: u32, routed: bool, down: bool) -> InputResult<MoeMatrixKind> {
|
||||
let kind = if routed { routed_matrix_kind(raw, down) } else { shared_matrix_kind(raw, down) };
|
||||
kind.ok_or(E::UnsupportedKind)
|
||||
}
|
||||
fn routed_matrix_kind(raw: u32, down: bool) -> Option<MoeMatrixKind> {
|
||||
use MoeMatrixKind as K;
|
||||
Ok(match (routed, down, raw) {
|
||||
(true, false, 18) => K::Iq3Xxs,
|
||||
(true, false, 21) => K::Iq3S,
|
||||
(true, false, 22) => K::Iq2S,
|
||||
(true, false, 23) => K::RoutedIq4Xs,
|
||||
(true, true, 20) => K::RoutedIq4Nl,
|
||||
(true, true, 42) => K::Q2_0,
|
||||
(false, false, 12) => K::Q4K,
|
||||
(false, false, 13) => K::Q5K,
|
||||
(false, false, 14) => K::Q6K,
|
||||
(false, false, 23) => K::DenseIq4Xs,
|
||||
(false, true, 8) => K::Q8_0,
|
||||
(false, true, 20) => K::DenseIq4Nl,
|
||||
_ => return Err(E::UnsupportedKind),
|
||||
})
|
||||
match (down, raw) {
|
||||
(false, 18) => Some(K::Iq3Xxs),
|
||||
(false, 21) => Some(K::Iq3S),
|
||||
(false, 22) => Some(K::Iq2S),
|
||||
(false, 23) => Some(K::RoutedIq4Xs),
|
||||
(true, 20) => Some(K::RoutedIq4Nl),
|
||||
(true, 42) => Some(K::Q2_0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn shared_matrix_kind(raw: u32, down: bool) -> Option<MoeMatrixKind> {
|
||||
use MoeMatrixKind as K;
|
||||
match (down, raw) {
|
||||
(false, 12) => Some(K::Q4K),
|
||||
(false, 13) => Some(K::Q5K),
|
||||
(false, 14) => Some(K::Q6K),
|
||||
(false, 23) => Some(K::DenseIq4Xs),
|
||||
(true, 8) => Some(K::Q8_0),
|
||||
(true, 20) => Some(K::DenseIq4Nl),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub(super) fn descriptor(
|
||||
raw: u32,
|
||||
|
||||
+38
-17
@@ -13,6 +13,23 @@ impl<'group> MoeRoutedSourceScope<'_, 'group> {
|
||||
/// `with_moe_routed_source` scope applies, without a new source observation. Every descriptor,
|
||||
/// span and admission request afterwards is validated as in a per-expert scope.
|
||||
pub(crate) fn retarget(&mut self, members: &'group [(&'group MoeExpertWeights, usize)]) -> InputResult<()> {
|
||||
let (first, first_slot, expert) = self.check_first_member(members)?;
|
||||
self.check_members(members, expert)?;
|
||||
let source = self.source.as_mut().ok_or(E::Read)?;
|
||||
// Preserve the first Gate geometry check of a fresh scope.
|
||||
let tensor = source.tensor(routed_source_role(MoeMatrixRole::Gate)).map_err(|_| E::Geometry)?;
|
||||
routed_source_descriptor(&self.binding.identity(), first, first_slot, MoeMatrixRole::Gate, tensor)?;
|
||||
source.retarget(expert).map_err(|_| E::Range)?;
|
||||
self.members = members;
|
||||
self.expert = expert;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The first member, its slot and the expert it selects; the count and layer limits of a scope apply.
|
||||
fn check_first_member(
|
||||
&self,
|
||||
members: &'group [(&'group MoeExpertWeights, usize)],
|
||||
) -> InputResult<(&'group MoeExpertWeights, usize, u32)> {
|
||||
let (first, first_slot) = *members.first().ok_or(E::Range)?;
|
||||
if members.len() > 64 || !first.matches(&self.binding.identity(), self.layer) {
|
||||
return Err(E::Metadata);
|
||||
@@ -21,6 +38,11 @@ impl<'group> MoeRoutedSourceScope<'_, 'group> {
|
||||
if expert >= EXPERTS as u32 {
|
||||
return Err(E::Range);
|
||||
}
|
||||
Ok((first, first_slot, expert))
|
||||
}
|
||||
|
||||
/// Every member belongs to this layer and selects `expert` in its slot.
|
||||
fn check_members(&self, members: &[(&MoeExpertWeights, usize)], expert: u32) -> InputResult<()> {
|
||||
for (weights, slot) in members {
|
||||
if !weights.matches(&self.binding.identity(), self.layer) {
|
||||
return Err(E::Metadata);
|
||||
@@ -29,13 +51,6 @@ impl<'group> MoeRoutedSourceScope<'_, 'group> {
|
||||
return Err(E::Metadata);
|
||||
}
|
||||
}
|
||||
let source = self.source.as_mut().ok_or(E::Read)?;
|
||||
// Preserve the first Gate geometry check of a fresh scope.
|
||||
let tensor = source.tensor(routed_source_role(MoeMatrixRole::Gate)).map_err(|_| E::Geometry)?;
|
||||
routed_source_descriptor(&self.binding.identity(), first, first_slot, MoeMatrixRole::Gate, tensor)?;
|
||||
source.retarget(expert).map_err(|_| E::Range)?;
|
||||
self.members = members;
|
||||
self.expert = expert;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -100,16 +115,7 @@ impl ModelBinding {
|
||||
if self.moe_shared_preload_descriptors(key.layer)?[usize::from(key.role)] != key {
|
||||
return Err(E::Geometry);
|
||||
}
|
||||
let role = TensorRole::Layer {
|
||||
layer: u8::try_from(key.layer).map_err(|_| E::Range)?,
|
||||
role: match key.role {
|
||||
0 => LayerRole::FfnGateShared,
|
||||
1 => LayerRole::FfnUpShared,
|
||||
2 => LayerRole::FfnDownShared,
|
||||
3 => LayerRole::FfnGateInpShared,
|
||||
_ => return Err(E::Range),
|
||||
},
|
||||
};
|
||||
let role = shared_tensor_role(&key)?;
|
||||
let mut bytes = Vec::new();
|
||||
bytes.try_reserve_exact(key.bytes).map_err(|_| E::Allocation)?;
|
||||
let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?;
|
||||
@@ -119,6 +125,21 @@ impl ModelBinding {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bound tensor a shared preload descriptor names.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn shared_tensor_role(key: &MoeWeightDescriptor) -> InputResult<TensorRole> {
|
||||
Ok(TensorRole::Layer {
|
||||
layer: u8::try_from(key.layer).map_err(|_| E::Range)?,
|
||||
role: match key.role {
|
||||
0 => LayerRole::FfnGateShared,
|
||||
1 => LayerRole::FfnUpShared,
|
||||
2 => LayerRole::FfnDownShared,
|
||||
3 => LayerRole::FfnGateInpShared,
|
||||
_ => return Err(E::Range),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// The extent of one shared preload tensor: (columns, rows, bytes). Index 3 is the gate scalar.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn shared_preload_extent(
|
||||
|
||||
@@ -131,19 +131,34 @@ fn freeze(source: &mut File, owner_root: &Path, bytes: u64) -> InputResult<File>
|
||||
let mut own = OwnedCopy::create(&root, uid)?;
|
||||
let mut writer = own.writer(uid)?;
|
||||
copy_exact(source, &mut writer, bytes)?;
|
||||
seal_copy(&writer)?;
|
||||
let reader = regular(&own.path, bytes)?;
|
||||
check_sealed_reader(&reader, &own)?;
|
||||
drop(writer);
|
||||
own.detach()?;
|
||||
check_detached(&reader)?;
|
||||
Ok(reader)
|
||||
}
|
||||
/// The copy reaches the disk and becomes read-only for its owner.
|
||||
fn seal_copy(writer: &File) -> InputResult<()> {
|
||||
writer.sync_all().map_err(|_| InputBindingError::Read)?;
|
||||
writer.set_permissions(Permissions::from_mode(0o400)).map_err(|_| InputBindingError::Read)?;
|
||||
let reader = regular(&own.path, bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
/// The reopened copy is the inode this owner created: read-only and linked exactly once.
|
||||
fn check_sealed_reader(reader: &File, own: &OwnedCopy) -> InputResult<()> {
|
||||
let m = reader.metadata().map_err(|_| InputBindingError::Read)?;
|
||||
if Some(inode(&m)) != own.file_inode || m.mode() & 0o7777 != 0o400 || m.nlink() != 1 {
|
||||
return Err(InputBindingError::Metadata);
|
||||
}
|
||||
drop(writer);
|
||||
own.detach()?;
|
||||
Ok(())
|
||||
}
|
||||
/// No name refers to the copy any more.
|
||||
fn check_detached(reader: &File) -> InputResult<()> {
|
||||
if reader.metadata().map_err(|_| InputBindingError::Read)?.nlink() != 0 {
|
||||
return Err(InputBindingError::Metadata);
|
||||
}
|
||||
Ok(reader)
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn freeze_file(source: &Path, owner_root: &Path, pin: (&str, u64, &str)) -> InputResult<File> {
|
||||
let directory = fs::symlink_metadata(source).map_err(|_| InputBindingError::Read)?;
|
||||
|
||||
@@ -120,13 +120,7 @@ impl MtpWeights {
|
||||
) -> InputResult<MtpRows> {
|
||||
self.validate_binding(binding)?;
|
||||
let d = descriptor(role).dense.ok_or(InputBindingError::UnsupportedKind)?;
|
||||
let row = match d.kind {
|
||||
MtpKind::Q8_0 => d.columns.checked_div(32).and_then(|n| n.checked_mul(34)),
|
||||
MtpKind::Bf16 => d.columns.checked_mul(2),
|
||||
MtpKind::F32 => d.columns.checked_mul(4),
|
||||
MtpKind::Q2_0 => None,
|
||||
}
|
||||
.ok_or(InputBindingError::Range)?;
|
||||
let row = dense_row_bytes(d.kind, d.columns)?;
|
||||
let (relative, bytes) = row_range(d.rows, row, first, count)?;
|
||||
let offset = d.offset.checked_add(relative).ok_or(InputBindingError::Range)?;
|
||||
let data = read_exact_range(&self.dense, offset, bytes)?;
|
||||
@@ -159,3 +153,13 @@ fn check_expert_scales(data: &[u8]) -> InputResult<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The byte width of one dense row of `columns` values.
|
||||
fn dense_row_bytes(kind: MtpKind, columns: usize) -> InputResult<usize> {
|
||||
match kind {
|
||||
MtpKind::Q8_0 => columns.checked_div(32).and_then(|n| n.checked_mul(34)),
|
||||
MtpKind::Bf16 => columns.checked_mul(2),
|
||||
MtpKind::F32 => columns.checked_mul(4),
|
||||
MtpKind::Q2_0 => None,
|
||||
}
|
||||
.ok_or(InputBindingError::Range)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user