STRA-338 params p01: control-plane functions to at most 5 parameters (WorkerInbox, TensorSpan, PartLimits, SessionInputs, EnginePipes and other groups)
This commit is contained in:
@@ -54,7 +54,7 @@ use leleka_backend_api::{
|
||||
use serde_json::{Value, json};
|
||||
use strata_control::{
|
||||
app::{AppState, router},
|
||||
backend_worker::{BackendWorkerConfig, run_backend_worker},
|
||||
backend_worker::{BackendWorkerConfig, WorkerInbox, run_backend_worker},
|
||||
stage_trace,
|
||||
tokenizer::Tokenizer,
|
||||
worker::{WorkerState, WorkerStatus},
|
||||
|
||||
@@ -101,8 +101,10 @@ fn spawn_worker(
|
||||
config,
|
||||
status,
|
||||
stop_rx,
|
||||
requests_rx,
|
||||
control_rx,
|
||||
WorkerInbox {
|
||||
requests: requests_rx,
|
||||
control: control_rx,
|
||||
},
|
||||
));
|
||||
(stop, requests, control, worker)
|
||||
}
|
||||
|
||||
@@ -81,6 +81,12 @@ pub struct BackendWorkerConfig {
|
||||
|
||||
type Engine = Arc<Mutex<Box<dyn api::Backend>>>;
|
||||
|
||||
/// What reaches the worker from outside: the generation requests and the control messages.
|
||||
pub struct WorkerInbox {
|
||||
pub requests: mpsc::Receiver<GenerationCommand>,
|
||||
pub control: mpsc::Receiver<Control>,
|
||||
}
|
||||
|
||||
enum Served {
|
||||
Done,
|
||||
/// The engine is gone or violated the contract; attach again.
|
||||
|
||||
@@ -56,16 +56,15 @@ impl AttachLoop {
|
||||
config: BackendWorkerConfig,
|
||||
status: Arc<RwLock<WorkerStatus>>,
|
||||
shutdown: watch::Receiver<bool>,
|
||||
requests: mpsc::Receiver<GenerationCommand>,
|
||||
control: mpsc::Receiver<Control>,
|
||||
inbox: WorkerInbox,
|
||||
) -> Self {
|
||||
Self {
|
||||
engine,
|
||||
config,
|
||||
status,
|
||||
shutdown,
|
||||
requests,
|
||||
control,
|
||||
requests: inbox.requests,
|
||||
control: inbox.control,
|
||||
waiting: Vec::new(),
|
||||
attached_before: false,
|
||||
requests_closed: false,
|
||||
@@ -321,15 +320,12 @@ impl AttachLoop {
|
||||
) -> Option<Flow> {
|
||||
self.status.write().await.last_activity = Some(command.request.obs.now());
|
||||
let _activity = command.activity.take();
|
||||
let served = serve_one(
|
||||
&self.engine,
|
||||
&self.config,
|
||||
&self.status,
|
||||
&mut self.shutdown,
|
||||
&mut command,
|
||||
loaded,
|
||||
)
|
||||
.await;
|
||||
let ctx = Context {
|
||||
engine: &self.engine,
|
||||
config: &self.config,
|
||||
status: &self.status,
|
||||
};
|
||||
let served = serve_one(ctx, &mut self.shutdown, &mut command, loaded).await;
|
||||
self.after_request(served, &command).await
|
||||
}
|
||||
|
||||
|
||||
@@ -9,11 +9,10 @@ pub async fn run_backend_worker(
|
||||
config: BackendWorkerConfig,
|
||||
status: Arc<RwLock<WorkerStatus>>,
|
||||
shutdown: watch::Receiver<bool>,
|
||||
requests: mpsc::Receiver<GenerationCommand>,
|
||||
control: mpsc::Receiver<Control>,
|
||||
inbox: WorkerInbox,
|
||||
) {
|
||||
let engine: Engine = Arc::new(Mutex::new(backend));
|
||||
AttachLoop::new(engine, config, status, shutdown, requests, control)
|
||||
AttachLoop::new(engine, config, status, shutdown, inbox)
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -5,14 +5,12 @@ use super::*;
|
||||
|
||||
/// One generation, from the contract request to the terminal event the HTTP layer sees, plus its record.
|
||||
pub(super) async fn serve_one(
|
||||
engine: &Engine,
|
||||
config: &BackendWorkerConfig,
|
||||
status: &RwLock<WorkerStatus>,
|
||||
ctx: Context<'_>,
|
||||
shutdown: &mut watch::Receiver<bool>,
|
||||
command: &mut GenerationCommand,
|
||||
loaded: &api::LoadedModel,
|
||||
) -> Served {
|
||||
let served = serve_one_inner(engine, config, status, shutdown, command, loaded).await;
|
||||
let served = serve_one_inner(ctx, shutdown, command, loaded).await;
|
||||
let obs = &command.request.obs;
|
||||
match &served {
|
||||
Served::Lost(reason) => {
|
||||
@@ -118,30 +116,24 @@ async fn start_engine(
|
||||
}
|
||||
|
||||
pub(super) async fn serve_one_inner(
|
||||
engine: &Engine,
|
||||
config: &BackendWorkerConfig,
|
||||
status: &RwLock<WorkerStatus>,
|
||||
ctx: Context<'_>,
|
||||
shutdown: &mut watch::Receiver<bool>,
|
||||
command: &mut GenerationCommand,
|
||||
loaded: &api::LoadedModel,
|
||||
) -> Served {
|
||||
let request = match prepare(config, &command.request).await {
|
||||
let request = match prepare(ctx.config, &command.request).await {
|
||||
Ok(request) => request,
|
||||
Err(message) => {
|
||||
fail_command(command, message).await;
|
||||
return Served::Done;
|
||||
}
|
||||
};
|
||||
let (stream, started) = match start_engine(engine, status, command, loaded, request).await {
|
||||
Ok(started) => started,
|
||||
Err(served) => return served,
|
||||
};
|
||||
let (stream, started) =
|
||||
match start_engine(ctx.engine, ctx.status, command, loaded, request).await {
|
||||
Ok(started) => started,
|
||||
Err(served) => return served,
|
||||
};
|
||||
let events = pump_events(stream);
|
||||
let ctx = Context {
|
||||
engine,
|
||||
config,
|
||||
status,
|
||||
};
|
||||
Run::new(ctx, shutdown, command, events, started)
|
||||
.run()
|
||||
.await
|
||||
|
||||
@@ -30,18 +30,20 @@ pub(super) struct Surface {
|
||||
pub(super) mcp_settings: crate::mcp::Settings,
|
||||
}
|
||||
|
||||
/// The checked sections of the file, each read once before the `Config` is built.
|
||||
pub(super) struct Sections {
|
||||
pub(super) limits: Limits,
|
||||
pub(super) engine: EngineSection,
|
||||
pub(super) side: EngineSide,
|
||||
pub(super) identity: Identity,
|
||||
pub(super) surface: Surface,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// The `Config` of a checked file; every field is named once, in the order of the struct.
|
||||
#[rustfmt::skip]
|
||||
pub(super) fn assemble(
|
||||
file: FileConfig,
|
||||
limits: Limits,
|
||||
engine: EngineSection,
|
||||
side: EngineSide,
|
||||
identity: Identity,
|
||||
surface: Surface,
|
||||
tool_call_recovery: bool,
|
||||
) -> Self {
|
||||
pub(super) fn assemble(file: FileConfig, sections: Sections, tool_call_recovery: bool) -> Self {
|
||||
let Sections { limits, engine, side, identity, surface } = sections;
|
||||
Self {
|
||||
queue_timeout: limits.queue_timeout_s.map(Duration::from_secs),
|
||||
response_history_dir: identity.response_history_dir,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! `Config::load_with_path`: the file, the environment, and the cross-checks between the sections.
|
||||
|
||||
use super::load_checks as check;
|
||||
use super::load_parts::Sections;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -15,14 +16,13 @@ impl Config {
|
||||
let surface = check::resolve_surface(&file, config_path.as_deref())?;
|
||||
check::check_vision(&file, engine.worker.as_ref())?;
|
||||
let tool_call_recovery = check::tool_call_recovery(file.tool_call_recovery)?;
|
||||
Ok(Self::assemble(
|
||||
file,
|
||||
let sections = Sections {
|
||||
limits,
|
||||
engine,
|
||||
side,
|
||||
identity,
|
||||
surface,
|
||||
tool_call_recovery,
|
||||
))
|
||||
};
|
||||
Ok(Self::assemble(file, sections, tool_call_recovery))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,17 +22,33 @@ pub fn copy_verified(
|
||||
digest: &str,
|
||||
revision: &str,
|
||||
) -> io::Result<u64> {
|
||||
copy_with_limit(source, destination, arch, digest, revision, MAX_BYTES)
|
||||
let payload = Payload {
|
||||
arch,
|
||||
digest,
|
||||
revision,
|
||||
};
|
||||
copy_with_limit(source, destination, payload, MAX_BYTES)
|
||||
}
|
||||
|
||||
/// What the payload is claimed to be: its target architecture, SHA256 and source revision.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Payload<'a> {
|
||||
arch: &'a str,
|
||||
digest: &'a str,
|
||||
revision: &'a str,
|
||||
}
|
||||
|
||||
fn copy_with_limit(
|
||||
mut source: impl Read,
|
||||
mut destination: impl Write,
|
||||
arch: &str,
|
||||
digest: &str,
|
||||
revision: &str,
|
||||
payload: Payload<'_>,
|
||||
limit: u64,
|
||||
) -> io::Result<u64> {
|
||||
let Payload {
|
||||
arch,
|
||||
digest,
|
||||
revision,
|
||||
} = payload;
|
||||
check_provenance(digest, revision)?;
|
||||
let machine = elf_machine(arch)?;
|
||||
let header = read_header(&mut source, machine)?;
|
||||
@@ -156,23 +172,20 @@ mod tests {
|
||||
let rev = "a".repeat(40);
|
||||
let mut output = Vec::new();
|
||||
let mut input = io::Cursor::new(&elf);
|
||||
let payload = Payload {
|
||||
arch: "x86_64",
|
||||
digest: &digest,
|
||||
revision: &rev,
|
||||
};
|
||||
assert_eq!(
|
||||
copy_with_limit(
|
||||
&mut input,
|
||||
&mut output,
|
||||
"x86_64",
|
||||
&digest,
|
||||
&rev,
|
||||
elf.len() as u64
|
||||
)
|
||||
.unwrap(),
|
||||
copy_with_limit(&mut input, &mut output, payload, elf.len() as u64).unwrap(),
|
||||
elf.len() as u64
|
||||
);
|
||||
assert_eq!(output, elf);
|
||||
output.clear();
|
||||
input.set_position(0);
|
||||
let cap = BUFFER_BYTES as u64;
|
||||
assert!(copy_with_limit(&mut input, &mut output, "x86_64", &digest, &rev, cap).is_err());
|
||||
assert!(copy_with_limit(&mut input, &mut output, payload, cap).is_err());
|
||||
assert_eq!(input.position(), cap + 1);
|
||||
assert!(output.len() as u64 <= cap);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,15 @@ use crate::{ggml_bridge, gguf, iq3_s, kar_codec};
|
||||
|
||||
pub const SOURCE_CHUNK_BYTES: usize = 256 * iq3_s::BLOCK_BYTES;
|
||||
|
||||
/// Where one tensor's source bytes sit in a reader, how they are quantized, and how many elements they decode to.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct TensorSpan {
|
||||
pub absolute_offset: u64,
|
||||
pub source_kind: u32,
|
||||
pub source_bytes: u64,
|
||||
pub elements: u64,
|
||||
}
|
||||
|
||||
#[repr(align(16))]
|
||||
struct AlignedSource([u8; SOURCE_CHUNK_BYTES]);
|
||||
|
||||
|
||||
@@ -11,7 +11,10 @@ use std::{
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::{gguf, kar, kar_codec, kar_sample, kar_stream_encode, kar_writer, model::Manifest};
|
||||
use crate::{
|
||||
gguf, gguf_f32_stream, kar, kar_codec, kar_sample, kar_stream_encode, kar_writer,
|
||||
model::Manifest,
|
||||
};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Candidates {
|
||||
|
||||
@@ -12,6 +12,26 @@ pub(super) struct Encoder<'a> {
|
||||
pub(super) staging: &'a Staging,
|
||||
}
|
||||
|
||||
/// One candidate tensor being encoded: its policy record, its source, and the checked element count and digest.
|
||||
struct Job<'a> {
|
||||
candidate: &'a Candidate,
|
||||
selected: &'a CandidateSource<'a>,
|
||||
elements: u64,
|
||||
source_sha256: [u8; 32],
|
||||
}
|
||||
|
||||
impl Job<'_> {
|
||||
fn span(&self) -> gguf_f32_stream::TensorSpan {
|
||||
let location = &self.selected.location;
|
||||
gguf_f32_stream::TensorSpan {
|
||||
absolute_offset: location.absolute,
|
||||
source_kind: location.kind,
|
||||
source_bytes: location.source_bytes,
|
||||
elements: self.elements,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Encoder<'_> {
|
||||
pub(super) fn encode_all(&self) -> Result<Vec<Prepared>, String> {
|
||||
let mut prepared = Vec::with_capacity(self.candidates.records.len());
|
||||
@@ -35,8 +55,13 @@ impl Encoder<'_> {
|
||||
let source_sha256 = parse_digest(selected.source_sha256)?;
|
||||
let f32_sha256 = parse_digest(selected.f32_sha256)?;
|
||||
let section_path = self.staging.0.join(format!("{ordinal:06}.section"));
|
||||
let section =
|
||||
self.encode_selected(candidate, &selected, elements, source_sha256, §ion_path)?;
|
||||
let job = Job {
|
||||
candidate,
|
||||
selected: &selected,
|
||||
elements,
|
||||
source_sha256,
|
||||
};
|
||||
let section = self.encode_selected(&job, §ion_path)?;
|
||||
if section.source_digest != source_sha256 || section.derived_digest != f32_sha256 {
|
||||
return Err(format!("{}: candidate source changed", candidate.name));
|
||||
}
|
||||
@@ -78,47 +103,28 @@ impl Encoder<'_> {
|
||||
|
||||
fn encode_selected(
|
||||
&self,
|
||||
candidate: &Candidate,
|
||||
selected: &CandidateSource,
|
||||
elements: u64,
|
||||
source_sha256: [u8; 32],
|
||||
job: &Job<'_>,
|
||||
section_path: &Path,
|
||||
) -> Result<kar_stream_encode::SectionResult, String> {
|
||||
let location = &selected.location;
|
||||
let mut source = File::open(&location.path).map_err(|error| error.to_string())?;
|
||||
let calibration =
|
||||
self.fit_calibration(&mut source, candidate, selected, elements, source_sha256)?;
|
||||
kar_stream_encode::encode_section(
|
||||
&mut source,
|
||||
location.absolute,
|
||||
location.kind,
|
||||
location.source_bytes,
|
||||
elements,
|
||||
&calibration,
|
||||
section_path,
|
||||
)
|
||||
let mut source =
|
||||
File::open(&job.selected.location.path).map_err(|error| error.to_string())?;
|
||||
let calibration = self.fit_calibration(&mut source, job)?;
|
||||
kar_stream_encode::encode_section(&mut source, job.span(), &calibration, section_path)
|
||||
}
|
||||
|
||||
fn fit_calibration(
|
||||
&self,
|
||||
source: &mut File,
|
||||
candidate: &Candidate,
|
||||
selected: &CandidateSource,
|
||||
elements: u64,
|
||||
source_sha256: [u8; 32],
|
||||
job: &Job<'_>,
|
||||
) -> Result<kar_codec::Calibration, String> {
|
||||
let location = &selected.location;
|
||||
let sample = kar_sample::sample_normalized(
|
||||
source,
|
||||
location.absolute,
|
||||
location.kind,
|
||||
location.source_bytes,
|
||||
elements,
|
||||
source_sha256,
|
||||
job.span(),
|
||||
job.source_sha256,
|
||||
kar_sample::MAX_SAMPLE_VALUES,
|
||||
)?;
|
||||
kar_codec::fit_topdown(&sample, self.candidates.proposed_levels)
|
||||
.map_err(|error| format!("{}: {error}", candidate.name))
|
||||
.map_err(|error| format!("{}: {error}", job.candidate.name))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,10 +17,13 @@ pub fn analyze(
|
||||
return Err("KAR source digest changed after verification".into());
|
||||
}
|
||||
let parts = stream_parts::plan_shards(&identity, source_dir)?;
|
||||
let source = SourceShards {
|
||||
dir: source_dir,
|
||||
identity: &identity,
|
||||
parts: &parts,
|
||||
};
|
||||
sample_records(
|
||||
source_dir,
|
||||
&identity,
|
||||
&parts,
|
||||
source,
|
||||
VerifiedRangeDecoder::open(archive_path)?,
|
||||
levels,
|
||||
archive_sha256,
|
||||
@@ -48,10 +51,13 @@ pub fn analyze_previously_verified(
|
||||
levels: u8,
|
||||
) -> Result<Report, String> {
|
||||
let checked = previous::load(manifest, source_dir, archive_path, levels)?;
|
||||
let source = SourceShards {
|
||||
dir: source_dir,
|
||||
identity: &checked.identity,
|
||||
parts: &checked.parts,
|
||||
};
|
||||
sample_records(
|
||||
source_dir,
|
||||
&checked.identity,
|
||||
&checked.parts,
|
||||
source,
|
||||
VerifiedRangeDecoder::open_previously_verified(archive_path)?,
|
||||
levels,
|
||||
checked.provenance.archive_sha256,
|
||||
|
||||
@@ -10,13 +10,24 @@ pub(super) fn parse_digest(value: &str) -> Result<[u8; 32], String> {
|
||||
.map_err(|_| "SHA-256 digest is not 32 bytes".into())
|
||||
}
|
||||
|
||||
/// The verified source of an analysis: its directory, its fingerprint and the planned parts of every tensor.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct SourceShards<'a> {
|
||||
pub(super) dir: &'a Path,
|
||||
pub(super) identity: &'a derived_mixed::ShardedIdentity,
|
||||
pub(super) parts: &'a [Vec<stream_parts::PartIdentity>],
|
||||
}
|
||||
|
||||
fn sample_all(
|
||||
source_dir: &Path,
|
||||
identity: &derived_mixed::ShardedIdentity,
|
||||
parts: &[Vec<stream_parts::PartIdentity>],
|
||||
source: SourceShards<'_>,
|
||||
decoder: &mut VerifiedRangeDecoder,
|
||||
levels: u8,
|
||||
) -> Result<Vec<RecordError>, String> {
|
||||
let SourceShards {
|
||||
dir: source_dir,
|
||||
identity,
|
||||
parts,
|
||||
} = source;
|
||||
let mut records = Vec::with_capacity(parts.iter().map(Vec::len).sum());
|
||||
let mut number = 0usize;
|
||||
for shard in &identity.shards {
|
||||
@@ -38,19 +49,17 @@ fn sample_all(
|
||||
}
|
||||
|
||||
pub(super) fn sample_records(
|
||||
source_dir: &Path,
|
||||
identity: &derived_mixed::ShardedIdentity,
|
||||
parts: &[Vec<stream_parts::PartIdentity>],
|
||||
source: SourceShards<'_>,
|
||||
mut decoder: VerifiedRangeDecoder,
|
||||
levels: u8,
|
||||
archive_sha256: String,
|
||||
verification: &'static str,
|
||||
) -> Result<Report, String> {
|
||||
let records = sample_all(source_dir, identity, parts, &mut decoder, levels)?;
|
||||
let records = sample_all(source, &mut decoder, levels)?;
|
||||
Ok(Report {
|
||||
schema: "strata-next/kar-sampled-distortion-v1",
|
||||
archive_sha256,
|
||||
derived_f32_sha256: hex::encode(identity.derived_sha256),
|
||||
derived_f32_sha256: hex::encode(source.identity.derived_sha256),
|
||||
levels,
|
||||
method: "nonoverlapping-first-middle-last-aligned-4096-v2",
|
||||
verification,
|
||||
|
||||
@@ -3,19 +3,17 @@
|
||||
|
||||
use std::io::{Read, Seek};
|
||||
|
||||
use crate::{gguf_f32_stream, kar_codec};
|
||||
use crate::{gguf_f32_stream, gguf_f32_stream::TensorSpan, kar_codec};
|
||||
|
||||
pub const MAX_SAMPLE_VALUES: usize = 65_536;
|
||||
|
||||
pub fn sample_normalized<R: Read + Seek>(
|
||||
reader: &mut R,
|
||||
absolute_offset: u64,
|
||||
source_kind: u32,
|
||||
source_bytes: u64,
|
||||
elements: u64,
|
||||
span: TensorSpan,
|
||||
source_digest: [u8; 32],
|
||||
max_samples: usize,
|
||||
) -> Result<Vec<f32>, String> {
|
||||
let elements = span.elements;
|
||||
if elements == 0 || max_samples == 0 || max_samples > MAX_SAMPLE_VALUES {
|
||||
return Err("invalid KAR sample size or tensor element count".into());
|
||||
}
|
||||
@@ -24,43 +22,19 @@ pub fn sample_normalized<R: Read + Seek>(
|
||||
.checked_mul(32)
|
||||
.ok_or("KAR sampled tensor size overflow")?;
|
||||
let targets = sample_targets(padded, max_samples, source_digest);
|
||||
sample_by_size(
|
||||
reader,
|
||||
absolute_offset,
|
||||
source_kind,
|
||||
source_bytes,
|
||||
elements,
|
||||
&targets,
|
||||
)
|
||||
sample_by_size(reader, span, &targets)
|
||||
}
|
||||
|
||||
/// Large tensors are sampled sparsely, seeking to the sampled groups only.
|
||||
fn sample_by_size<R: Read + Seek>(
|
||||
reader: &mut R,
|
||||
absolute_offset: u64,
|
||||
source_kind: u32,
|
||||
source_bytes: u64,
|
||||
elements: u64,
|
||||
span: TensorSpan,
|
||||
targets: &[u64],
|
||||
) -> Result<Vec<f32>, String> {
|
||||
if elements > 1_048_576 {
|
||||
sample_sparse(
|
||||
reader,
|
||||
absolute_offset,
|
||||
source_kind,
|
||||
source_bytes,
|
||||
elements,
|
||||
targets,
|
||||
)
|
||||
if span.elements > 1_048_576 {
|
||||
sample_sparse(reader, span, targets)
|
||||
} else {
|
||||
sample_dense(
|
||||
reader,
|
||||
absolute_offset,
|
||||
source_kind,
|
||||
source_bytes,
|
||||
elements,
|
||||
targets,
|
||||
)
|
||||
sample_dense(reader, span, targets)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,18 +57,16 @@ fn sample_targets(padded: u64, max_samples: usize, source_digest: [u8; 32]) -> V
|
||||
|
||||
fn sample_dense<R: Read + Seek>(
|
||||
reader: &mut R,
|
||||
absolute_offset: u64,
|
||||
source_kind: u32,
|
||||
source_bytes: u64,
|
||||
elements: u64,
|
||||
span: TensorSpan,
|
||||
targets: &[u64],
|
||||
) -> Result<Vec<f32>, String> {
|
||||
let elements = span.elements;
|
||||
let mut collector = Collector::new(targets);
|
||||
let decoded_bytes = gguf_f32_stream::visit(
|
||||
reader,
|
||||
absolute_offset,
|
||||
source_kind,
|
||||
source_bytes,
|
||||
span.absolute_offset,
|
||||
span.source_kind,
|
||||
span.source_bytes,
|
||||
|_, f32_bytes| collector.push_words(f32_bytes, elements),
|
||||
)?;
|
||||
if collector.seen != elements
|
||||
@@ -169,12 +141,15 @@ impl<'a> Collector<'a> {
|
||||
|
||||
fn sample_sparse<R: Read + Seek>(
|
||||
reader: &mut R,
|
||||
absolute_offset: u64,
|
||||
source_kind: u32,
|
||||
source_bytes: u64,
|
||||
elements: u64,
|
||||
span: TensorSpan,
|
||||
targets: &[u64],
|
||||
) -> Result<Vec<f32>, String> {
|
||||
let TensorSpan {
|
||||
absolute_offset,
|
||||
source_kind,
|
||||
source_bytes,
|
||||
elements,
|
||||
} = span;
|
||||
let geometry = checked_geometry(source_kind, elements, source_bytes)?;
|
||||
let mut sampled = Vec::with_capacity(targets.len());
|
||||
let mut normalized = [0.0f32; 32];
|
||||
@@ -271,16 +246,13 @@ mod tests {
|
||||
.iter()
|
||||
.flat_map(|value| value.to_le_bytes())
|
||||
.collect::<Vec<_>>();
|
||||
let sample = sample_normalized(
|
||||
&mut Cursor::new(bytes.clone()),
|
||||
0,
|
||||
0,
|
||||
bytes.len() as u64,
|
||||
weights.len() as u64,
|
||||
[7; 32],
|
||||
64,
|
||||
)
|
||||
.unwrap();
|
||||
let span = TensorSpan {
|
||||
absolute_offset: 0,
|
||||
source_kind: 0,
|
||||
source_bytes: bytes.len() as u64,
|
||||
elements: weights.len() as u64,
|
||||
};
|
||||
let sample = sample_normalized(&mut Cursor::new(bytes.clone()), span, [7; 32], 64).unwrap();
|
||||
assert_eq!(
|
||||
sample,
|
||||
kar_codec::normalize_for_calibration(&weights, 32)
|
||||
@@ -298,18 +270,13 @@ mod tests {
|
||||
.iter()
|
||||
.flat_map(|value| value.to_le_bytes())
|
||||
.collect::<Vec<_>>();
|
||||
let run = || {
|
||||
sample_normalized(
|
||||
&mut Cursor::new(&bytes),
|
||||
0,
|
||||
0,
|
||||
bytes.len() as u64,
|
||||
2048,
|
||||
[3; 32],
|
||||
32,
|
||||
)
|
||||
.unwrap()
|
||||
let span = TensorSpan {
|
||||
absolute_offset: 0,
|
||||
source_kind: 0,
|
||||
source_bytes: bytes.len() as u64,
|
||||
elements: 2048,
|
||||
};
|
||||
let run = || sample_normalized(&mut Cursor::new(&bytes), span, [3; 32], 32).unwrap();
|
||||
assert_eq!(run(), run());
|
||||
assert_eq!(run().len(), 32);
|
||||
}
|
||||
@@ -319,16 +286,13 @@ mod tests {
|
||||
let mut block = [0u8; iq3_s::BLOCK_BYTES];
|
||||
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
|
||||
let source = block.repeat(257);
|
||||
let sample = sample_normalized(
|
||||
&mut Cursor::new(&source),
|
||||
0,
|
||||
21,
|
||||
source.len() as u64,
|
||||
(257 * iq3_s::BLOCK_ELEMENTS) as u64,
|
||||
[9; 32],
|
||||
64,
|
||||
)
|
||||
.unwrap();
|
||||
let span = TensorSpan {
|
||||
absolute_offset: 0,
|
||||
source_kind: 21,
|
||||
source_bytes: source.len() as u64,
|
||||
elements: (257 * iq3_s::BLOCK_ELEMENTS) as u64,
|
||||
};
|
||||
let sample = sample_normalized(&mut Cursor::new(&source), span, [9; 32], 64).unwrap();
|
||||
assert_eq!(sample.len(), 64);
|
||||
assert!(sample.iter().all(|value| *value == 1.0));
|
||||
}
|
||||
@@ -353,25 +317,14 @@ mod tests {
|
||||
|
||||
fn assert_sparse_matches_full(kind: u32, bytes: &[u8], elements: u64) {
|
||||
let targets = sparse_targets(elements, 11);
|
||||
let full = sample_normalized(
|
||||
&mut Cursor::new(bytes),
|
||||
0,
|
||||
kind,
|
||||
bytes.len() as u64,
|
||||
let span = TensorSpan {
|
||||
absolute_offset: 0,
|
||||
source_kind: kind,
|
||||
source_bytes: bytes.len() as u64,
|
||||
elements,
|
||||
[11; 32],
|
||||
64,
|
||||
)
|
||||
.unwrap();
|
||||
let sparse = sample_sparse(
|
||||
&mut Cursor::new(bytes),
|
||||
0,
|
||||
kind,
|
||||
bytes.len() as u64,
|
||||
elements,
|
||||
&targets,
|
||||
)
|
||||
.unwrap();
|
||||
};
|
||||
let full = sample_normalized(&mut Cursor::new(bytes), span, [11; 32], 64).unwrap();
|
||||
let sparse = sample_sparse(&mut Cursor::new(bytes), span, &targets).unwrap();
|
||||
assert_eq!(sparse, full);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::{
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::{gguf_f32_stream, kar_codec};
|
||||
use crate::{gguf_f32_stream, gguf_f32_stream::TensorSpan, kar_codec};
|
||||
|
||||
pub struct SectionResult {
|
||||
pub bytes: u64,
|
||||
@@ -21,22 +21,19 @@ pub struct SectionResult {
|
||||
|
||||
pub fn encode_section<R: Read + Seek>(
|
||||
reader: &mut R,
|
||||
absolute_offset: u64,
|
||||
source_kind: u32,
|
||||
source_bytes: u64,
|
||||
elements: u64,
|
||||
span: TensorSpan,
|
||||
calibration: &kar_codec::Calibration,
|
||||
destination: &Path,
|
||||
) -> Result<SectionResult, String> {
|
||||
layout::check_calibration(calibration, elements)?;
|
||||
let layout = layout::section_layout(elements, calibration.books.len())?;
|
||||
layout::check_calibration(calibration, span.elements)?;
|
||||
let layout = layout::section_layout(span.elements, calibration.books.len())?;
|
||||
let section = create_section(destination)?;
|
||||
let source = Source {
|
||||
reader,
|
||||
absolute_offset,
|
||||
source_kind,
|
||||
source_bytes,
|
||||
elements,
|
||||
absolute_offset: span.absolute_offset,
|
||||
source_kind: span.source_kind,
|
||||
source_bytes: span.source_bytes,
|
||||
elements: span.elements,
|
||||
};
|
||||
let result = fill_section(§ion, &layout, source, calibration, destination);
|
||||
drop(section);
|
||||
|
||||
@@ -109,12 +109,15 @@ fn square_wave_bytes(weights: &[f32]) -> Vec<u8> {
|
||||
|
||||
/// Encodes `source` through the streamed encoder as `kind` with `elements` weights.
|
||||
fn encode_bytes(source: &[u8], kind: u32, elements: u64, output: &Path) -> SectionResult {
|
||||
let span = TensorSpan {
|
||||
absolute_offset: 0,
|
||||
source_kind: kind,
|
||||
source_bytes: source.len() as u64,
|
||||
elements,
|
||||
};
|
||||
encode_section(
|
||||
&mut Cursor::new(source),
|
||||
0,
|
||||
kind,
|
||||
source.len() as u64,
|
||||
elements,
|
||||
span,
|
||||
&two_level_calibration(),
|
||||
output,
|
||||
)
|
||||
|
||||
@@ -267,9 +267,20 @@ fn nested_geometry(
|
||||
let TensorData::Nested { group, nesting, planes_min, planes_max, scales, books, planes } =
|
||||
&tensor.data else { unreachable!() };
|
||||
let levels = u8::try_from(planes.len()).map_err(|_| "too many KAR planes")?;
|
||||
#[rustfmt::skip]
|
||||
let layout = nested_layout(cursor, n_elements, *group, *nesting, *planes_min, *planes_max, levels)?;
|
||||
validate_nested_slices(tensor.name, &layout, *group, scales, books, planes)?;
|
||||
let params = NestedParams {
|
||||
group: *group,
|
||||
nesting: *nesting,
|
||||
planes_min: *planes_min,
|
||||
planes_max: *planes_max,
|
||||
levels,
|
||||
};
|
||||
let layout = nested_layout(cursor, n_elements, params)?;
|
||||
let slices = NestedSlices {
|
||||
scales,
|
||||
books,
|
||||
planes,
|
||||
};
|
||||
validate_nested_slices(tensor.name, &layout, *group, slices)?;
|
||||
totals.absorb(&layout, *planes_min, *planes_max)?;
|
||||
Ok(Geometry::from(&layout))
|
||||
}
|
||||
@@ -283,8 +294,14 @@ fn nested_file_geometry(
|
||||
#[rustfmt::skip]
|
||||
let TensorData::NestedFile { group, nesting, planes_min, planes_max, levels, bytes, .. } =
|
||||
&tensor.data else { unreachable!() };
|
||||
#[rustfmt::skip]
|
||||
let layout = nested_layout(cursor, n_elements, *group, *nesting, *planes_min, *planes_max, *levels)?;
|
||||
let params = NestedParams {
|
||||
group: *group,
|
||||
nesting: *nesting,
|
||||
planes_min: *planes_min,
|
||||
planes_max: *planes_max,
|
||||
levels: *levels,
|
||||
};
|
||||
let layout = nested_layout(cursor, n_elements, params)?;
|
||||
if *bytes != layout.section_bytes {
|
||||
return Err(format!(
|
||||
"{}: nested file section size mismatch",
|
||||
|
||||
@@ -4,6 +4,24 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The nesting parameters of one tensor: its group size, nesting flag, plane range and level count.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct NestedParams {
|
||||
pub(super) group: u16,
|
||||
pub(super) nesting: u8,
|
||||
pub(super) planes_min: u8,
|
||||
pub(super) planes_max: u8,
|
||||
pub(super) levels: u8,
|
||||
}
|
||||
|
||||
/// The in-memory parts of a NESTED tensor: its scales, the books of its levels and its bit planes.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct NestedSlices<'a> {
|
||||
pub(super) scales: &'a [u16],
|
||||
pub(super) books: &'a [&'a [u16]],
|
||||
pub(super) planes: &'a [&'a [u32]],
|
||||
}
|
||||
|
||||
/// Write one canonical NESTED section for later bounded-memory archive assembly.
|
||||
/// The destination must not exist and is meant to live in a private staging dir.
|
||||
pub fn write_nested_section(
|
||||
@@ -42,9 +60,20 @@ fn spool_layout(tensor: &Tensor<'_>, n_elements: u64) -> Result<(NestedLayout, (
|
||||
return Err("KAR section spool requires in-memory NESTED tensor".into());
|
||||
};
|
||||
let levels = u8::try_from(planes.len()).map_err(|_| "too many KAR planes")?;
|
||||
let (min, max) = (*planes_min, *planes_max);
|
||||
let layout = nested_layout(0, n_elements, *group, *nesting, min, max, levels)?;
|
||||
validate_nested_slices(tensor.name, &layout, *group, scales, books, planes)?;
|
||||
let params = NestedParams {
|
||||
group: *group,
|
||||
nesting: *nesting,
|
||||
planes_min: *planes_min,
|
||||
planes_max: *planes_max,
|
||||
levels,
|
||||
};
|
||||
let layout = nested_layout(0, n_elements, params)?;
|
||||
let slices = NestedSlices {
|
||||
scales,
|
||||
books,
|
||||
planes,
|
||||
};
|
||||
validate_nested_slices(tensor.name, &layout, *group, slices)?;
|
||||
Ok((layout, (*group, levels)))
|
||||
}
|
||||
|
||||
@@ -143,10 +172,13 @@ pub(super) fn validate_nested_slices(
|
||||
name: &str,
|
||||
layout: &NestedLayout,
|
||||
group: u16,
|
||||
scales: &[u16],
|
||||
books: &[&[u16]],
|
||||
planes: &[&[u32]],
|
||||
slices: NestedSlices<'_>,
|
||||
) -> Result<(), String> {
|
||||
let NestedSlices {
|
||||
scales,
|
||||
books,
|
||||
planes,
|
||||
} = slices;
|
||||
if books.len() != planes.len() {
|
||||
return Err(format!("{name}: level book count mismatch"));
|
||||
}
|
||||
@@ -206,14 +238,12 @@ fn check_nested_parameters(
|
||||
pub(super) fn nested_layout(
|
||||
cursor: u64,
|
||||
n_elements: u64,
|
||||
group: u16,
|
||||
nesting: u8,
|
||||
planes_min: u8,
|
||||
planes_max: u8,
|
||||
levels: u8,
|
||||
params: NestedParams,
|
||||
) -> Result<NestedLayout, String> {
|
||||
let group = u64::from(group);
|
||||
check_nested_parameters(group, nesting, (planes_min, planes_max), levels)?;
|
||||
let levels = params.levels;
|
||||
let group = u64::from(params.group);
|
||||
let planes = (params.planes_min, params.planes_max);
|
||||
check_nested_parameters(group, params.nesting, planes, levels)?;
|
||||
let n_padded = padded_elements(n_elements, group)?;
|
||||
let groups = n_padded / group;
|
||||
let scales_bytes = groups.checked_mul(2).ok_or("KAR scales overflow")?;
|
||||
|
||||
@@ -255,12 +255,16 @@ impl Rebuild {
|
||||
if t.kind != bt.kind
|
||||
|| t.dimensions != bt.dimensions
|
||||
|| !same_bytes(
|
||||
&mut self.new_file,
|
||||
self.new_start + t.offset,
|
||||
&mut self.old_file,
|
||||
self.old_start + bt.offset,
|
||||
t.bytes,
|
||||
bt.bytes,
|
||||
FileRun {
|
||||
file: &mut self.new_file,
|
||||
at: self.new_start + t.offset,
|
||||
len: t.bytes,
|
||||
},
|
||||
FileRun {
|
||||
file: &mut self.old_file,
|
||||
at: self.old_start + bt.offset,
|
||||
len: bt.bytes,
|
||||
},
|
||||
)?
|
||||
{
|
||||
return Err(format!(
|
||||
|
||||
@@ -3,17 +3,23 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// A tensor to convert and the shard it is read from.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct SourceTensor<'a> {
|
||||
pub(super) shard: &'a Shard,
|
||||
pub(super) tensor: &'a gguf::TensorInfo,
|
||||
}
|
||||
|
||||
/// The pack form of one tensor the engine reads from `dense.bin` when it is stored otherwise. Mirrors
|
||||
/// `tools/iq_pack.py::convert` for every source kind: same accept/reject decision, same bytes, same record.
|
||||
pub(super) fn convert_tensor(
|
||||
input: &mut File,
|
||||
shard: &Shard,
|
||||
tensor: &gguf::TensorInfo,
|
||||
source: SourceTensor<'_>,
|
||||
target: u32,
|
||||
compat_bf16: bool,
|
||||
dense: &mut File,
|
||||
) -> Result<Converted> {
|
||||
let mut conv = Conv::new(shard, tensor, target, compat_bf16);
|
||||
let mut conv = Conv::new(source.shard, source.tensor, target, compat_bf16);
|
||||
match target {
|
||||
30 => conv.convert_bf16(input, dense),
|
||||
1 => conv.convert_f16(input, dense),
|
||||
|
||||
@@ -77,7 +77,7 @@ impl Dense<'_> {
|
||||
let (index_kind, written, dst) = if target == tensor.kind {
|
||||
copy_verbatim(input, shard, tensor, &mut self.file)?
|
||||
} else {
|
||||
self.convert(input, shard, shard_name, tensor, target)?
|
||||
self.convert(input, SourceTensor { shard, tensor }, shard_name, target)?
|
||||
};
|
||||
self.rows.push(format!(
|
||||
"{} 0 {index_kind} {} {written} {} {dst} {ne0} {ne1} 0 0 1 0 0 0 0 0 0 0\n",
|
||||
@@ -106,15 +106,14 @@ impl Dense<'_> {
|
||||
fn convert(
|
||||
&mut self,
|
||||
input: &mut File,
|
||||
shard: &Shard,
|
||||
source: SourceTensor<'_>,
|
||||
shard_name: &str,
|
||||
tensor: &gguf::TensorInfo,
|
||||
target: u32,
|
||||
) -> Result<(u32, u64, u64)> {
|
||||
let tensor = source.tensor;
|
||||
let converted = convert_tensor(
|
||||
input,
|
||||
shard,
|
||||
tensor,
|
||||
source,
|
||||
target,
|
||||
self.options.compat_bf16,
|
||||
&mut self.file,
|
||||
@@ -272,7 +271,12 @@ pub async fn prepare_with(
|
||||
// Validate tokenizer before writing any pack files.
|
||||
tokenizer_assets_preflight(&shards[0].path)?;
|
||||
let (parent, stage) = create_stage(output)?;
|
||||
let result = build_and_publish(manifest, &shards, &layout, options, &stage, output, &parent);
|
||||
let paths = PackPaths {
|
||||
stage: &stage,
|
||||
output,
|
||||
parent: &parent,
|
||||
};
|
||||
let result = build_and_publish(manifest, &shards, &layout, options, paths);
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_dir_all(&stage);
|
||||
}
|
||||
@@ -317,21 +321,28 @@ fn create_stage(output: &Path) -> Result<(PathBuf, PathBuf)> {
|
||||
Ok((parent.to_owned(), stage))
|
||||
}
|
||||
|
||||
/// Where a pack is built and published: the stage directory, the final `output` and the parent holding both.
|
||||
#[derive(Clone, Copy)]
|
||||
struct PackPaths<'a> {
|
||||
stage: &'a Path,
|
||||
output: &'a Path,
|
||||
parent: &'a Path,
|
||||
}
|
||||
|
||||
/// Write every pack file into the stage, then publish it as `output`; returns whether a conversion was lossy.
|
||||
fn build_and_publish(
|
||||
manifest: &model::Manifest,
|
||||
shards: &[Shard],
|
||||
layout: &Layout,
|
||||
options: &Options,
|
||||
stage: &Path,
|
||||
output: &Path,
|
||||
parent: &Path,
|
||||
paths: PackPaths<'_>,
|
||||
) -> Result<bool> {
|
||||
let stage = paths.stage;
|
||||
let lossy = write_stage_files(shards, layout, options, stage)?;
|
||||
write_source_json(manifest, stage, lossy)?;
|
||||
crate::native_model::write_receipt(manifest, stage)?;
|
||||
File::open(stage)?.sync_all()?;
|
||||
publish_stage(stage, output, parent)?;
|
||||
publish_stage(stage, paths.output, paths.parent)?;
|
||||
Ok(lossy)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,26 +3,27 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
pub(super) fn same_bytes(
|
||||
a: &mut File,
|
||||
a_at: u64,
|
||||
b: &mut File,
|
||||
b_at: u64,
|
||||
a_len: u64,
|
||||
b_len: u64,
|
||||
) -> Result<bool> {
|
||||
if a_len != b_len {
|
||||
/// A byte run of a file: where it starts and how long it is.
|
||||
pub(super) struct FileRun<'a> {
|
||||
pub(super) file: &'a mut File,
|
||||
pub(super) at: u64,
|
||||
pub(super) len: u64,
|
||||
}
|
||||
|
||||
pub(super) fn same_bytes(a: FileRun<'_>, b: FileRun<'_>) -> Result<bool> {
|
||||
if a.len != b.len {
|
||||
return Ok(false);
|
||||
}
|
||||
let len = a.len;
|
||||
let mut left = vec![0u8; 1 << 20];
|
||||
let mut right = vec![0u8; 1 << 20];
|
||||
let mut done = 0u64;
|
||||
while done < a_len {
|
||||
let n = (a_len - done).min(left.len() as u64) as usize;
|
||||
a.seek(SeekFrom::Start(a_at + done))?;
|
||||
a.read_exact(&mut left[..n])?;
|
||||
b.seek(SeekFrom::Start(b_at + done))?;
|
||||
b.read_exact(&mut right[..n])?;
|
||||
while done < len {
|
||||
let n = (len - done).min(left.len() as u64) as usize;
|
||||
a.file.seek(SeekFrom::Start(a.at + done))?;
|
||||
a.file.read_exact(&mut left[..n])?;
|
||||
b.file.seek(SeekFrom::Start(b.at + done))?;
|
||||
b.file.read_exact(&mut right[..n])?;
|
||||
if left[..n] != right[..n] {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
@@ -72,11 +72,11 @@ impl Quantized {
|
||||
|
||||
/// Identity of the source tensor a section is derived from.
|
||||
#[derive(Clone, Copy)]
|
||||
struct SourceTensorRef<'a> {
|
||||
name: &'a str,
|
||||
dimensions: &'a [u64],
|
||||
digest: [u8; 32],
|
||||
offset: u64,
|
||||
pub(super) struct SourceTensorRef<'a> {
|
||||
pub(super) name: &'a str,
|
||||
pub(super) dimensions: &'a [u64],
|
||||
pub(super) digest: [u8; 32],
|
||||
pub(super) offset: u64,
|
||||
}
|
||||
|
||||
fn relative_l2_error(weights: &[f32], decoded: &[f32]) -> f64 {
|
||||
@@ -114,11 +114,8 @@ fn prepared_tensor(
|
||||
}
|
||||
|
||||
pub(super) fn encode_preview_tensor(
|
||||
name: &str,
|
||||
dimensions: &[u64],
|
||||
source: SourceTensorRef<'_>,
|
||||
weights: &[f32],
|
||||
source_digest: [u8; 32],
|
||||
source_offset: u64,
|
||||
section_path: &Path,
|
||||
levels: u8,
|
||||
) -> Result<(PreparedTensor, f64), String> {
|
||||
@@ -126,12 +123,6 @@ pub(super) fn encode_preview_tensor(
|
||||
let plane_refs = quantized.plane_refs();
|
||||
let relative_l2 = quantized.relative_l2(weights, &plane_refs)?;
|
||||
let books = quantized.book_refs();
|
||||
let source = SourceTensorRef {
|
||||
name,
|
||||
dimensions,
|
||||
digest: source_digest,
|
||||
offset: source_offset,
|
||||
};
|
||||
let coded_tensor = quantized.tensor(source, &books, &plane_refs);
|
||||
let section = kar_writer::write_nested_section(section_path, &coded_tensor)?;
|
||||
let prepared = prepared_tensor(source, section_path, §ion);
|
||||
@@ -151,14 +142,11 @@ pub fn verify_sharded(
|
||||
source_dir: &Path,
|
||||
archive_path: &Path,
|
||||
) -> Result<kar::Summary, String> {
|
||||
verify_sharded_inner(
|
||||
manifest,
|
||||
source_dir,
|
||||
archive_path,
|
||||
None,
|
||||
stream_parts::MAX_PART_ELEMENTS,
|
||||
None,
|
||||
)
|
||||
let limits = PartLimits {
|
||||
max_part_elements: stream_parts::MAX_PART_ELEMENTS,
|
||||
ple_part_elements: None,
|
||||
};
|
||||
verify_sharded_inner(manifest, source_dir, archive_path, None, limits)
|
||||
}
|
||||
|
||||
pub fn verify_sharded_streamed(
|
||||
@@ -170,14 +158,11 @@ pub fn verify_sharded_streamed(
|
||||
if !(1..=8).contains(&levels) {
|
||||
return Err("streamed sharded verification requires 1..=8 KAR levels".into());
|
||||
}
|
||||
verify_sharded_inner(
|
||||
manifest,
|
||||
source_dir,
|
||||
archive_path,
|
||||
Some(levels),
|
||||
stream_parts::MAX_PART_ELEMENTS,
|
||||
None,
|
||||
)
|
||||
let limits = PartLimits {
|
||||
max_part_elements: stream_parts::MAX_PART_ELEMENTS,
|
||||
ple_part_elements: None,
|
||||
};
|
||||
verify_sharded_inner(manifest, source_dir, archive_path, Some(levels), limits)
|
||||
}
|
||||
|
||||
pub fn verify_sharded_streamed_ple(
|
||||
@@ -191,14 +176,11 @@ pub fn verify_sharded_streamed_ple(
|
||||
if !(1..=8).contains(&levels) {
|
||||
return Err("streamed sharded verification requires 1..=8 KAR levels".into());
|
||||
}
|
||||
verify_sharded_inner(
|
||||
manifest,
|
||||
source_dir,
|
||||
archive_path,
|
||||
Some(levels),
|
||||
stream_parts::MAX_PART_ELEMENTS,
|
||||
Some(ple_part_elements),
|
||||
)
|
||||
let limits = PartLimits {
|
||||
max_part_elements: stream_parts::MAX_PART_ELEMENTS,
|
||||
ple_part_elements: Some(ple_part_elements),
|
||||
};
|
||||
verify_sharded_inner(manifest, source_dir, archive_path, Some(levels), limits)
|
||||
}
|
||||
|
||||
pub(super) fn verify_sharded_inner(
|
||||
@@ -206,12 +188,11 @@ pub(super) fn verify_sharded_inner(
|
||||
source_dir: &Path,
|
||||
archive_path: &Path,
|
||||
streamed_levels: Option<u8>,
|
||||
max_part_elements: u64,
|
||||
ple_part_elements: Option<u64>,
|
||||
limits: PartLimits,
|
||||
) -> Result<kar::Summary, String> {
|
||||
let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?;
|
||||
let archive_parts = streamed_levels
|
||||
.map(|_| plan_verified_parts(&identity, source_dir, max_part_elements, ple_part_elements))
|
||||
.map(|_| plan_verified_parts(&identity, source_dir, limits))
|
||||
.transpose()?;
|
||||
let (summary, sources) = kar::verify_with_sources(archive_path)?;
|
||||
let parts = archive_parts.as_deref();
|
||||
@@ -219,7 +200,7 @@ pub(super) fn verify_sharded_inner(
|
||||
require_sharded_sources(&identity, parts, &sources)?;
|
||||
let policy = StreamPolicy {
|
||||
levels: streamed_levels,
|
||||
ple_part_elements,
|
||||
ple_part_elements: limits.ple_part_elements,
|
||||
};
|
||||
require_sharded_provenance(&identity, parts, archive_path, &summary, policy)?;
|
||||
Ok(summary)
|
||||
|
||||
@@ -33,6 +33,13 @@ struct StagedTensors {
|
||||
maximum_relative_l2: f64,
|
||||
}
|
||||
|
||||
/// A tensor's raw source bytes, its element count and the absolute offset they were read from.
|
||||
struct RawTensor {
|
||||
bytes: Vec<u8>,
|
||||
elements: u64,
|
||||
absolute: u64,
|
||||
}
|
||||
|
||||
fn require_source_limits(index: &gguf::TensorIndex) -> Result<(), String> {
|
||||
if index.summary.file_size > MAX_SOURCE_BYTES
|
||||
|| index.tensors.is_empty()
|
||||
@@ -180,18 +187,21 @@ impl PreviewPlan {
|
||||
let data_start = self.index.summary.data_start;
|
||||
let absolute = checked_offset(data_start, tensor.offset, "GGUF tensor offset overflow")?;
|
||||
let raw = read_raw_tensor(source_file, absolute, tensor.bytes)?;
|
||||
let (weights, tensor_digest, source_offset) =
|
||||
self.source_weights(number, tensor, raw, elements, absolute)?;
|
||||
let raw = RawTensor {
|
||||
bytes: raw,
|
||||
elements,
|
||||
absolute,
|
||||
};
|
||||
let (weights, tensor_digest, source_offset) = self.source_weights(number, tensor, raw)?;
|
||||
let section_path = staged.staging.0.join(format!("{number:06}.section"));
|
||||
let (coded, relative_l2) = encode_preview_tensor(
|
||||
&tensor.name,
|
||||
&tensor.dimensions,
|
||||
&weights,
|
||||
tensor_digest,
|
||||
source_offset,
|
||||
§ion_path,
|
||||
self.levels,
|
||||
)?;
|
||||
let source_tensor = SourceTensorRef {
|
||||
name: &tensor.name,
|
||||
dimensions: &tensor.dimensions,
|
||||
digest: tensor_digest,
|
||||
offset: source_offset,
|
||||
};
|
||||
let (coded, relative_l2) =
|
||||
encode_preview_tensor(source_tensor, &weights, §ion_path, self.levels)?;
|
||||
staged.maximum_relative_l2 = staged.maximum_relative_l2.max(relative_l2);
|
||||
staged.prepared.push(coded);
|
||||
Ok(())
|
||||
@@ -202,10 +212,13 @@ impl PreviewPlan {
|
||||
&self,
|
||||
number: usize,
|
||||
tensor: &gguf::TensorInfo,
|
||||
raw: Vec<u8>,
|
||||
elements: u64,
|
||||
absolute: u64,
|
||||
raw: RawTensor,
|
||||
) -> Result<(Vec<f32>, [u8; 32], u64), String> {
|
||||
let RawTensor {
|
||||
bytes: raw,
|
||||
elements,
|
||||
absolute,
|
||||
} = raw;
|
||||
let Some(identity) = &self.derived_identity else {
|
||||
let digest = Sha256::digest(&raw).into();
|
||||
return Ok((f32_from_le(&raw), digest, absolute));
|
||||
|
||||
@@ -102,8 +102,10 @@ pub fn prepare_sharded_streamed_ple(
|
||||
source_dir,
|
||||
destination,
|
||||
levels,
|
||||
stream_parts::MAX_PART_ELEMENTS,
|
||||
Some(ple_part_elements),
|
||||
PartLimits {
|
||||
max_part_elements: stream_parts::MAX_PART_ELEMENTS,
|
||||
ple_part_elements: Some(ple_part_elements),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -119,7 +121,9 @@ pub(super) fn prepare_sharded_streamed_with_limit(
|
||||
source_dir,
|
||||
destination,
|
||||
levels,
|
||||
max_part_elements,
|
||||
None,
|
||||
PartLimits {
|
||||
max_part_elements,
|
||||
ple_part_elements: None,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,8 +8,7 @@ pub(super) fn prepare_sharded_streamed_with_policy(
|
||||
source_dir: &Path,
|
||||
destination: &Path,
|
||||
levels: u8,
|
||||
max_part_elements: u64,
|
||||
ple_part_elements: Option<u64>,
|
||||
limits: PartLimits,
|
||||
) -> Result<PreviewSummary, String> {
|
||||
require_levels(
|
||||
levels,
|
||||
@@ -17,8 +16,7 @@ pub(super) fn prepare_sharded_streamed_with_policy(
|
||||
)?;
|
||||
require_free_destination(destination)?;
|
||||
let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?;
|
||||
let archive_parts =
|
||||
plan_stream_parts(&identity, source_dir, max_part_elements, ple_part_elements)?;
|
||||
let archive_parts = plan_stream_parts(&identity, source_dir, limits)?;
|
||||
let archive_tensor_count = archive_parts.iter().map(Vec::len).sum::<usize>();
|
||||
require_stream_budget(&archive_parts, archive_tensor_count, destination, levels)?;
|
||||
let staging = staging_dir(destination, "stream-parts")?;
|
||||
@@ -30,7 +28,7 @@ pub(super) fn prepare_sharded_streamed_with_policy(
|
||||
levels,
|
||||
};
|
||||
let encoding = run.encode(archive_tensor_count)?;
|
||||
write_streamed_preview(destination, &run, ple_part_elements, encoding)
|
||||
write_streamed_preview(destination, &run, limits.ple_part_elements, encoding)
|
||||
}
|
||||
|
||||
fn require_free_destination(destination: &Path) -> Result<(), String> {
|
||||
@@ -45,13 +43,12 @@ fn require_free_destination(destination: &Path) -> Result<(), String> {
|
||||
fn plan_stream_parts(
|
||||
identity: &derived_mixed::ShardedIdentity,
|
||||
source_dir: &Path,
|
||||
max_part_elements: u64,
|
||||
ple_part_elements: Option<u64>,
|
||||
limits: PartLimits,
|
||||
) -> Result<Vec<Vec<stream_parts::PartIdentity>>, String> {
|
||||
if let Some(limit) = ple_part_elements {
|
||||
if let Some(limit) = limits.ple_part_elements {
|
||||
stream_parts::plan_shards_with_ple_limit(identity, source_dir, limit)
|
||||
} else {
|
||||
stream_parts::plan_shards_with_limit(identity, source_dir, max_part_elements)
|
||||
stream_parts::plan_shards_with_limit(identity, source_dir, limits.max_part_elements)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -111,13 +111,11 @@ fn encode_sharded_tensor(
|
||||
)?;
|
||||
let raw = read_raw_tensor(source, absolute, tensor.bytes)?;
|
||||
let weights = decode_sharded_tensor(tensor, derived, &raw, elements)?;
|
||||
encode_preview_tensor(
|
||||
&tensor.name,
|
||||
&tensor.dimensions,
|
||||
&weights,
|
||||
derived.f32_sha256,
|
||||
derived.derived_offset,
|
||||
section_path,
|
||||
levels,
|
||||
)
|
||||
let source_tensor = SourceTensorRef {
|
||||
name: &tensor.name,
|
||||
dimensions: &tensor.dimensions,
|
||||
digest: derived.f32_sha256,
|
||||
offset: derived.derived_offset,
|
||||
};
|
||||
encode_preview_tensor(source_tensor, &weights, section_path, levels)
|
||||
}
|
||||
|
||||
@@ -127,6 +127,16 @@ impl StreamedRun<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the part's source bytes sit in the shard file, and how many elements they decode to.
|
||||
fn part_span(absolute: u64, part: &stream_parts::PartIdentity) -> gguf_f32_stream::TensorSpan {
|
||||
gguf_f32_stream::TensorSpan {
|
||||
absolute_offset: absolute,
|
||||
source_kind: part.source_kind,
|
||||
source_bytes: part.source_bytes,
|
||||
elements: part.derived_bytes / 4,
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_part(
|
||||
source: &mut File,
|
||||
absolute: u64,
|
||||
@@ -134,12 +144,10 @@ fn encode_part(
|
||||
section_path: &Path,
|
||||
levels: u8,
|
||||
) -> Result<EncodedPart, String> {
|
||||
let span = part_span(absolute, part);
|
||||
let sample = kar_sample::sample_normalized(
|
||||
source,
|
||||
absolute,
|
||||
part.source_kind,
|
||||
part.source_bytes,
|
||||
part.derived_bytes / 4,
|
||||
span,
|
||||
part.source_sha256,
|
||||
kar_sample::MAX_SAMPLE_VALUES,
|
||||
)?;
|
||||
@@ -158,10 +166,7 @@ fn encode_nested_part(
|
||||
) -> Result<EncodedPart, String> {
|
||||
let result = kar_stream_encode::encode_section(
|
||||
source,
|
||||
absolute,
|
||||
part.source_kind,
|
||||
part.source_bytes,
|
||||
part.derived_bytes / 4,
|
||||
part_span(absolute, part),
|
||||
calibration,
|
||||
section_path,
|
||||
)?;
|
||||
|
||||
@@ -228,8 +228,11 @@ fn streamed_sharded_archive_roundtrips_partitioned_tensor_records() {
|
||||
prepare_sharded_streamed_with_limit(&manifest, &directory, &archive, 2, 256).unwrap();
|
||||
assert_eq!(result.archive.tensor_count, 3);
|
||||
assert_distortions_match(&result);
|
||||
let verified =
|
||||
verify_sharded_inner(&manifest, &directory, &archive, Some(2), 256, None).unwrap();
|
||||
let limits = PartLimits {
|
||||
max_part_elements: 256,
|
||||
ple_part_elements: None,
|
||||
};
|
||||
let verified = verify_sharded_inner(&manifest, &directory, &archive, Some(2), limits).unwrap();
|
||||
assert_eq!(verified, result.archive);
|
||||
assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err());
|
||||
assert_partition_records(&archive, &dense, result.provenance_path.unwrap());
|
||||
|
||||
@@ -12,16 +12,22 @@ pub(super) struct StreamPolicy {
|
||||
pub(super) ple_part_elements: Option<u64>,
|
||||
}
|
||||
|
||||
/// How the tensors of a sharded source are split into parts: the general limit, and the PLE limit when one is set.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct PartLimits {
|
||||
pub(super) max_part_elements: u64,
|
||||
pub(super) ple_part_elements: Option<u64>,
|
||||
}
|
||||
|
||||
pub(super) fn plan_verified_parts(
|
||||
identity: &derived_mixed::ShardedIdentity,
|
||||
source_dir: &Path,
|
||||
max_part_elements: u64,
|
||||
ple_part_elements: Option<u64>,
|
||||
limits: PartLimits,
|
||||
) -> Result<Vec<Vec<stream_parts::PartIdentity>>, String> {
|
||||
if let Some(limit) = ple_part_elements {
|
||||
if let Some(limit) = limits.ple_part_elements {
|
||||
stream_parts::plan_shards_with_ple_limit(identity, source_dir, limit)
|
||||
} else {
|
||||
stream_parts::plan_shards_with_limit(identity, source_dir, max_part_elements)
|
||||
stream_parts::plan_shards_with_limit(identity, source_dir, limits.max_part_elements)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -84,22 +84,27 @@ fn profile_from_env() -> Option<String> {
|
||||
.filter(|p| !p.is_empty())
|
||||
}
|
||||
|
||||
/// Who a request is: its id, the endpoint it asked for, its session tag and the model it was sent to.
|
||||
pub struct ReqIdentity {
|
||||
pub id: String,
|
||||
pub endpoint: usize,
|
||||
pub sid: Option<String>,
|
||||
pub model: Option<String>,
|
||||
}
|
||||
|
||||
impl ReqCtx {
|
||||
pub fn new(
|
||||
id: String,
|
||||
endpoint: usize,
|
||||
sid: Option<String>,
|
||||
model: Option<String>,
|
||||
identity: ReqIdentity,
|
||||
memory: Option<Arc<crate::memory_view::MemoryView>>,
|
||||
clock: crate::ports::SharedClock,
|
||||
) -> Self {
|
||||
Self {
|
||||
state: Mutex::new(Live {
|
||||
id,
|
||||
sid,
|
||||
endpoint,
|
||||
id: identity.id,
|
||||
sid: identity.sid,
|
||||
endpoint: identity.endpoint,
|
||||
stream: None,
|
||||
model,
|
||||
model: identity.model,
|
||||
profile: profile_from_env(),
|
||||
admitted: clock.now(),
|
||||
engine_start: None,
|
||||
|
||||
@@ -60,11 +60,14 @@ impl ObsHandle {
|
||||
/// is recorded here.
|
||||
pub async fn observe(State(observe): State<Observe>, request: Request, next: Next) -> Response {
|
||||
let endpoint = endpoint_index(request.uri().path());
|
||||
let ctx = Arc::new(ReqCtx::new(
|
||||
uuid::Uuid::new_v4().to_string(),
|
||||
let identity = ReqIdentity {
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
endpoint,
|
||||
session_tag(request.headers()),
|
||||
observe.model.clone(),
|
||||
sid: session_tag(request.headers()),
|
||||
model: observe.model.clone(),
|
||||
};
|
||||
let ctx = Arc::new(ReqCtx::new(
|
||||
identity,
|
||||
Some(observe.memory.clone()),
|
||||
observe.clock.clone(),
|
||||
));
|
||||
|
||||
@@ -38,20 +38,25 @@ fn line(record: &Record) -> String {
|
||||
}
|
||||
|
||||
fn ctx() -> ReqCtx {
|
||||
ReqCtx::new(
|
||||
"0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d".into(),
|
||||
0,
|
||||
Some("s-0123456789".into()),
|
||||
Some("qwen-iq3".into()),
|
||||
None,
|
||||
crate::adapters::SystemClock::shared(),
|
||||
)
|
||||
let identity = ReqIdentity {
|
||||
id: "0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d".into(),
|
||||
endpoint: 0,
|
||||
sid: Some("s-0123456789".into()),
|
||||
model: Some("qwen-iq3".into()),
|
||||
};
|
||||
ReqCtx::new(identity, None, crate::adapters::SystemClock::shared())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_record_stamps_come_from_the_injected_clock() {
|
||||
let clock = crate::ports::fakes::ManualClock::new(1_700_000_000);
|
||||
let c = ReqCtx::new("rid".into(), 0, None, None, None, clock.clone());
|
||||
let identity = ReqIdentity {
|
||||
id: "rid".into(),
|
||||
endpoint: 0,
|
||||
sid: None,
|
||||
model: None,
|
||||
};
|
||||
let c = ReqCtx::new(identity, None, clock.clone());
|
||||
clock.advance(std::time::Duration::from_millis(40));
|
||||
c.engine_start();
|
||||
clock.advance(std::time::Duration::from_millis(60));
|
||||
|
||||
@@ -18,6 +18,15 @@ pub struct ResponseHistory {
|
||||
pub(super) store: Option<Arc<crate::history_store::Store>>,
|
||||
}
|
||||
|
||||
/// A response to store: its id, the model it came from, the input that asked for it and its body.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Exchange<'a> {
|
||||
pub(super) id: &'a str,
|
||||
pub(super) model: &'a str,
|
||||
pub(super) input: &'a Value,
|
||||
pub(super) response: &'a Value,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct StoredResponse {
|
||||
@@ -111,11 +120,17 @@ impl ResponseHistory {
|
||||
input: &Value,
|
||||
response: &Value,
|
||||
) -> Result<(), &'static str> {
|
||||
let exchange = Exchange {
|
||||
id,
|
||||
model,
|
||||
input,
|
||||
response,
|
||||
};
|
||||
if self.store.is_none() {
|
||||
return self.insert_with_limit(id, model, input, response, MAX_HISTORY_BYTES);
|
||||
return self.insert_with_limit(exchange, MAX_HISTORY_BYTES);
|
||||
}
|
||||
let mut candidate = self.clone();
|
||||
candidate.insert_with_limit(id, model, input, response, MAX_HISTORY_BYTES)?;
|
||||
candidate.insert_with_limit(exchange, MAX_HISTORY_BYTES)?;
|
||||
candidate.persist()?;
|
||||
*self = candidate;
|
||||
Ok(())
|
||||
@@ -123,12 +138,15 @@ impl ResponseHistory {
|
||||
|
||||
pub(super) fn insert_with_limit(
|
||||
&mut self,
|
||||
id: &str,
|
||||
model: &str,
|
||||
input: &Value,
|
||||
response: &Value,
|
||||
exchange: Exchange<'_>,
|
||||
limit: usize,
|
||||
) -> Result<(), &'static str> {
|
||||
let Exchange {
|
||||
id,
|
||||
model,
|
||||
input,
|
||||
response,
|
||||
} = exchange;
|
||||
if response["id"] != id || response["model"] != model {
|
||||
return Err("stored response identity mismatch");
|
||||
}
|
||||
|
||||
@@ -123,7 +123,12 @@ impl ToolStream {
|
||||
) -> Result<(), String> {
|
||||
request.validate_tool_count(self.call_count() + 1)?;
|
||||
let call_id = format!("call_{}_{}", &self.response_id[5..], self.items.len());
|
||||
self.validate_call(request, &name, &call_id, &arguments, created_at)?;
|
||||
let parts = CallParts {
|
||||
name: &name,
|
||||
call_id: &call_id,
|
||||
arguments: &arguments,
|
||||
};
|
||||
self.validate_call(request, parts, created_at)?;
|
||||
self.finish_text(false).await?;
|
||||
self.emit_call(request, &name, &call_id, &arguments).await?;
|
||||
self.items.push(OutputItem::FunctionCall {
|
||||
@@ -138,15 +143,13 @@ impl ToolStream {
|
||||
fn validate_call(
|
||||
&self,
|
||||
request: &CreateRequest,
|
||||
name: &str,
|
||||
call_id: &str,
|
||||
arguments: &str,
|
||||
parts: CallParts<'_>,
|
||||
created_at: u64,
|
||||
) -> Result<(), String> {
|
||||
let item = OutputItem::FunctionCall {
|
||||
name: name.to_owned(),
|
||||
call_id: call_id.to_owned(),
|
||||
argument_deltas: vec![arguments.to_owned()],
|
||||
name: parts.name.to_owned(),
|
||||
call_id: parts.call_id.to_owned(),
|
||||
argument_deltas: vec![parts.arguments.to_owned()],
|
||||
};
|
||||
ResponseTrace::build(
|
||||
request,
|
||||
@@ -217,6 +220,14 @@ impl ToolStream {
|
||||
}
|
||||
}
|
||||
|
||||
/// The name, id and complete arguments of a call.
|
||||
#[derive(Clone, Copy)]
|
||||
struct CallParts<'a> {
|
||||
name: &'a str,
|
||||
call_id: &'a str,
|
||||
arguments: &'a str,
|
||||
}
|
||||
|
||||
/// What the events of a call publish: where it sits, its id, whether it is a custom tool and its two forms.
|
||||
struct CallEvents<'a> {
|
||||
index: usize,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Stored response history: durable round trip, eviction, counting and the bounded store.
|
||||
|
||||
use super::super::history::Exchange;
|
||||
use super::super::*;
|
||||
|
||||
/// Open the durable history again after a handle was dropped. `flock` belongs to the open file
|
||||
@@ -190,15 +191,15 @@ fn history_counts_response_and_transcript_and_reclaims_deleted_entries() {
|
||||
assert_eq!(history.bytes, expected);
|
||||
assert_eq!(history.entries["resp_a"].response, first);
|
||||
let second = json!({"id":"resp_b", "model":"model","output":[],"metadata":{"tag":"kept"}});
|
||||
assert!(
|
||||
history
|
||||
.insert_with_limit("resp_b", "model", &input, &second, expected - 1)
|
||||
.is_err()
|
||||
);
|
||||
let exchange = Exchange {
|
||||
id: "resp_b",
|
||||
model: "model",
|
||||
input: &input,
|
||||
response: &second,
|
||||
};
|
||||
assert!(history.insert_with_limit(exchange, expected - 1).is_err());
|
||||
assert!(history.get("resp_a", "model").is_some());
|
||||
history
|
||||
.insert_with_limit("resp_b", "model", &input, &second, expected)
|
||||
.unwrap();
|
||||
history.insert_with_limit(exchange, expected).unwrap();
|
||||
assert!(history.get("resp_a", "model").is_none());
|
||||
assert!(history.remove("resp_b"));
|
||||
assert!(!history.remove("resp_b"));
|
||||
|
||||
@@ -95,8 +95,10 @@ pub(super) async fn start_runtime_worker(
|
||||
worker_config,
|
||||
state.engine.worker.clone(),
|
||||
shutdown.clone(),
|
||||
receiver,
|
||||
control_receiver,
|
||||
strata_control::backend_worker::WorkerInbox {
|
||||
requests: receiver,
|
||||
control: control_receiver,
|
||||
},
|
||||
),
|
||||
)))
|
||||
}
|
||||
|
||||
@@ -98,21 +98,22 @@ impl<'a> Planner<'a> {
|
||||
return Err("GGUF tensor differs from virtual source".into());
|
||||
}
|
||||
let layouts = self.tensor_layouts(tensor, original.derived_offset)?;
|
||||
let parts = self.plan_parts(index, tensor, original, layouts, source)?;
|
||||
let parts = self.plan_parts(index, tensor, layouts, source)?;
|
||||
self.result.push(parts);
|
||||
self.number += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The identities of one tensor's parts; split tensors are re-read and their hashes must add up.
|
||||
/// The tensor's identity in the virtual source is the one `plan_tensor` already matched at `self.number`.
|
||||
fn plan_parts(
|
||||
&mut self,
|
||||
index: &gguf::TensorIndex,
|
||||
tensor: &gguf::TensorInfo,
|
||||
original: &derived_mixed::TensorIdentity,
|
||||
layouts: Vec<Layout>,
|
||||
source: &mut File,
|
||||
) -> Result<Vec<PartIdentity>, String> {
|
||||
let original = &self.identity.tensors[self.number];
|
||||
let split = layouts.len() > 1;
|
||||
let mut parent = ParentHashes::new();
|
||||
let mut parts = Vec::with_capacity(layouts.len());
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Moved out of the parent module by STRA-338: fn combine_done, fn generate, fn deliver.
|
||||
|
||||
use super::engine_io::EnginePipes;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -36,8 +37,7 @@ pub(super) fn combine_done(
|
||||
}
|
||||
|
||||
pub(super) async fn generate(
|
||||
stdin: &mut Option<ChildStdin>,
|
||||
lines: &mut tokio::io::Lines<BufReader<tokio::process::ChildStdout>>,
|
||||
pipes: EnginePipes<'_>,
|
||||
command: &mut GenerationCommand,
|
||||
max_context: usize,
|
||||
status: &RwLock<WorkerStatus>,
|
||||
@@ -48,12 +48,12 @@ pub(super) async fn generate(
|
||||
};
|
||||
status.write().await.metrics.start();
|
||||
command.request.obs.engine_start();
|
||||
let pipe = stdin.as_mut().ok_or("engine stdin is closed")?;
|
||||
let pipe = pipes.stdin.as_mut().ok_or("engine stdin is closed")?;
|
||||
write_frame(pipe, request.as_bytes()).await?;
|
||||
let stop_deadline = tokio::time::sleep(STOP_DRAIN_TIMEOUT);
|
||||
tokio::pin!(stop_deadline);
|
||||
Generation::new(command, status, stall_timeout)
|
||||
.pump(pipe, lines, stop_deadline.as_mut())
|
||||
.pump(pipe, pipes.lines, stop_deadline.as_mut())
|
||||
.await
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,12 @@ use super::*;
|
||||
|
||||
pub(super) type EngineLines = tokio::io::Lines<BufReader<tokio::process::ChildStdout>>;
|
||||
|
||||
/// The two pipes to the engine process: the stdin frames go into and the stdout lines come from.
|
||||
pub(super) struct EnginePipes<'a> {
|
||||
pub(super) stdin: &'a mut Option<ChildStdin>,
|
||||
pub(super) lines: &'a mut EngineLines,
|
||||
}
|
||||
|
||||
/// `Err` when the supervisor is shutting down before the engine process exists.
|
||||
pub(super) async fn refuse_if_shutting_down(
|
||||
status: &RwLock<WorkerStatus>,
|
||||
@@ -66,21 +72,13 @@ pub(super) async fn spawn_engine(
|
||||
|
||||
/// Run one generation under the configured execution deadline; `true` when the deadline ended it.
|
||||
pub(super) async fn generate_within_deadline(
|
||||
stdin: &mut Option<ChildStdin>,
|
||||
lines: &mut EngineLines,
|
||||
pipes: EnginePipes<'_>,
|
||||
command: &mut GenerationCommand,
|
||||
max_context: usize,
|
||||
status: &RwLock<WorkerStatus>,
|
||||
config: &WorkerConfig,
|
||||
) -> (bool, Result<(), String>) {
|
||||
let generation = generate(
|
||||
stdin,
|
||||
lines,
|
||||
command,
|
||||
max_context,
|
||||
status,
|
||||
config.stall_timeout,
|
||||
);
|
||||
let generation = generate(pipes, command, max_context, status, config.stall_timeout);
|
||||
match config.generation_timeout {
|
||||
Some(duration) => match timeout(duration, generation).await {
|
||||
Ok(result) => (false, result),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! One engine process from spawn to exit: start, wait for READY, then serve requests and control messages.
|
||||
|
||||
use super::engine_io::{EngineLines, generate_within_deadline, spawn_engine};
|
||||
use super::engine_io::{EngineLines, EnginePipes, generate_within_deadline, spawn_engine};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -31,20 +31,25 @@ struct Session<'a> {
|
||||
control_closed: bool,
|
||||
}
|
||||
|
||||
/// What a supervised session listens on besides its engine: the shutdown signal, the request queue, the control
|
||||
/// messages, the command parked for the next session and the `Load` requests that wait for READY.
|
||||
pub(super) struct SessionInputs<'a> {
|
||||
pub(super) shutdown: &'a mut watch::Receiver<bool>,
|
||||
pub(super) requests: &'a mut mpsc::Receiver<GenerationCommand>,
|
||||
pub(super) control: &'a mut mpsc::Receiver<Control>,
|
||||
pub(super) inbox: &'a mut Option<GenerationCommand>,
|
||||
pub(super) waiting: &'a mut Vec<LoadReply>,
|
||||
}
|
||||
|
||||
pub(super) async fn run_session(
|
||||
config: &WorkerConfig,
|
||||
status: &RwLock<WorkerStatus>,
|
||||
shutdown: &mut watch::Receiver<bool>,
|
||||
requests: &mut mpsc::Receiver<GenerationCommand>,
|
||||
control: &mut mpsc::Receiver<Control>,
|
||||
inbox: &mut Option<GenerationCommand>,
|
||||
waiting: &mut Vec<LoadReply>,
|
||||
inputs: SessionInputs<'_>,
|
||||
) -> SessionExit {
|
||||
let mut session =
|
||||
match Session::open(config, status, shutdown, requests, control, inbox, waiting).await {
|
||||
Ok(session) => session,
|
||||
Err(exit) => return exit,
|
||||
};
|
||||
let mut session = match Session::open(config, status, inputs).await {
|
||||
Ok(session) => session,
|
||||
Err(exit) => return exit,
|
||||
};
|
||||
match session.wait_ready().await {
|
||||
Ok(max_context) => session.serve(max_context).await,
|
||||
Err(exit) => exit,
|
||||
@@ -56,13 +61,9 @@ impl<'a> Session<'a> {
|
||||
async fn open(
|
||||
config: &'a WorkerConfig,
|
||||
status: &'a RwLock<WorkerStatus>,
|
||||
shutdown: &'a mut watch::Receiver<bool>,
|
||||
requests: &'a mut mpsc::Receiver<GenerationCommand>,
|
||||
control: &'a mut mpsc::Receiver<Control>,
|
||||
inbox: &'a mut Option<GenerationCommand>,
|
||||
waiting: &'a mut Vec<LoadReply>,
|
||||
inputs: SessionInputs<'a>,
|
||||
) -> Result<Self, SessionExit> {
|
||||
let mut child = spawn_engine(config, status, shutdown).await?;
|
||||
let mut child = spawn_engine(config, status, inputs.shutdown).await?;
|
||||
// Keep stdin outside Child: Child::wait closes any stdin it still owns.
|
||||
let stdin = child.stdin.take();
|
||||
let stdout = child.stdout.take().expect("piped engine stdout");
|
||||
@@ -70,11 +71,11 @@ impl<'a> Session<'a> {
|
||||
Ok(Self {
|
||||
config,
|
||||
status,
|
||||
shutdown,
|
||||
requests,
|
||||
control,
|
||||
inbox,
|
||||
waiting,
|
||||
shutdown: inputs.shutdown,
|
||||
requests: inputs.requests,
|
||||
control: inputs.control,
|
||||
inbox: inputs.inbox,
|
||||
waiting: inputs.waiting,
|
||||
child,
|
||||
stdin,
|
||||
lines,
|
||||
@@ -316,8 +317,10 @@ impl Session<'_> {
|
||||
) -> Option<SessionExit> {
|
||||
tokio::select! {
|
||||
(timed_out, result) = generate_within_deadline(
|
||||
&mut self.stdin,
|
||||
&mut self.lines,
|
||||
EnginePipes {
|
||||
stdin: &mut self.stdin,
|
||||
lines: &mut self.lines,
|
||||
},
|
||||
&mut command,
|
||||
max_context,
|
||||
self.status,
|
||||
|
||||
@@ -159,16 +159,14 @@ impl SessionSupervisor {
|
||||
}
|
||||
|
||||
async fn run_one_session(&mut self) -> AfterSession {
|
||||
let exit = run_session(
|
||||
&self.config,
|
||||
&self.status,
|
||||
&mut self.shutdown,
|
||||
&mut self.requests,
|
||||
&mut self.control,
|
||||
&mut self.inbox,
|
||||
&mut self.waiting,
|
||||
)
|
||||
.await;
|
||||
let inputs = SessionInputs {
|
||||
shutdown: &mut self.shutdown,
|
||||
requests: &mut self.requests,
|
||||
control: &mut self.control,
|
||||
inbox: &mut self.inbox,
|
||||
waiting: &mut self.waiting,
|
||||
};
|
||||
let exit = run_session(&self.config, &self.status, inputs).await;
|
||||
match exit {
|
||||
SessionExit::Stopped => AfterSession::Finish,
|
||||
SessionExit::StartupFailed => {
|
||||
|
||||
@@ -7,7 +7,7 @@ use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use strata_control::app::{AppState, EngineLink, ModelView, Services, router};
|
||||
use strata_control::backend_worker::{BackendWorkerConfig, run_backend_worker};
|
||||
use strata_control::backend_worker::{BackendWorkerConfig, WorkerInbox, run_backend_worker};
|
||||
use strata_control::tokenizer::Tokenizer;
|
||||
use strata_control::worker::{Control, GenerationCommand, WorkerState, WorkerStatus};
|
||||
use tokio::sync::{RwLock, mpsc, watch};
|
||||
@@ -142,8 +142,10 @@ fn spawn_worker(
|
||||
config,
|
||||
status,
|
||||
stop_rx,
|
||||
requests_rx,
|
||||
control_rx,
|
||||
WorkerInbox {
|
||||
requests: requests_rx,
|
||||
control: control_rx,
|
||||
},
|
||||
));
|
||||
(stop, requests, control, worker)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::harness::{Stack, runtime_config};
|
||||
use leleka_backend_api::scripted::{ScriptedEngine, ScriptedHandle};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use strata_control::backend_worker::{BackendWorkerConfig, run_backend_worker};
|
||||
use strata_control::backend_worker::{BackendWorkerConfig, WorkerInbox, run_backend_worker};
|
||||
use strata_control::wire::{Event, Generate};
|
||||
use strata_control::worker::{
|
||||
Control, GenerationCommand, GenerationResult, WorkerState, WorkerStatus,
|
||||
@@ -49,8 +49,10 @@ pub(super) async fn start(stack: &Stack) -> SecondWorker {
|
||||
worker_config(stack),
|
||||
status.clone(),
|
||||
stop_rx,
|
||||
requests_rx,
|
||||
control_rx,
|
||||
WorkerInbox {
|
||||
requests: requests_rx,
|
||||
control: control_rx,
|
||||
},
|
||||
));
|
||||
while status.read().await.state != WorkerState::Ready {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
|
||||
@@ -7,7 +7,7 @@ use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use strata_control::app::{AppState, EngineLink, ModelView, router};
|
||||
use strata_control::backend_worker::{BackendWorkerConfig, run_backend_worker};
|
||||
use strata_control::backend_worker::{BackendWorkerConfig, WorkerInbox, run_backend_worker};
|
||||
use strata_control::memory_view::MemoryView;
|
||||
use strata_control::tokenizer::Tokenizer;
|
||||
use strata_control::worker::{Control, GenerationCommand, WorkerState, WorkerStatus};
|
||||
@@ -102,8 +102,10 @@ fn spawn_worker(
|
||||
config,
|
||||
status,
|
||||
stop_rx,
|
||||
requests_rx,
|
||||
control_rx,
|
||||
WorkerInbox {
|
||||
requests: requests_rx,
|
||||
control: control_rx,
|
||||
},
|
||||
));
|
||||
(stop, requests, control, worker)
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use strata_control::app::{AppState, EngineLink, ModelView, router};
|
||||
use strata_control::backend_worker::{BackendWorkerConfig, run_backend_worker};
|
||||
use strata_control::backend_worker::{BackendWorkerConfig, WorkerInbox, run_backend_worker};
|
||||
use strata_control::tokenizer::Tokenizer;
|
||||
use strata_control::worker::{WorkerState, WorkerStatus};
|
||||
use strata_desktop_core::runtime_rpc::RuntimeServer;
|
||||
@@ -175,8 +175,10 @@ impl Stack {
|
||||
config,
|
||||
status.clone(),
|
||||
stop_rx,
|
||||
requests_rx,
|
||||
control_rx,
|
||||
WorkerInbox {
|
||||
requests: requests_rx,
|
||||
control: control_rx,
|
||||
},
|
||||
));
|
||||
let state = app_state(&status, requests, control, tokenizer, prefix_view);
|
||||
let (base, server) = serve_router(state).await;
|
||||
|
||||
Reference in New Issue
Block a user