Files
leleka/control-plane/src/prepare_preview/streamed_sharded_prepare.rs
T

163 lines
6.3 KiB
Rust

//! The streamed sharded preparation under a part-size policy: plans the parts, checks the size budget, encodes part by
//! part and writes the archive with its provenance. Separate from `prepare_sharded` because no whole tensor is held.
use super::{
Manifest, PartLimits, Path, PreviewSummary, StreamedEncoding, StreamedRun, StreamedTensor, apply_stream_policy,
derived_mixed, fs, hash_file, kar, kar_shard_plan, kar_writer, minimum_part_payload_bytes, model, nested_file_data,
provenance_path, require_architecture, require_levels, sharded_provenance_value, staging_dir,
write_sibling_provenance,
};
pub(super) fn prepare_sharded_streamed_with_policy(
manifest: &Manifest,
source_dir: &Path,
destination: &Path,
levels: u8,
limits: PartLimits,
) -> Result<PreviewSummary, String> {
require_levels(
levels,
"streamed sharded preparation requires 1..=8 KAR levels",
)?;
require_free_destination(destination)?;
let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?;
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")?;
let run = StreamedRun {
identity: &identity,
archive_parts: &archive_parts,
source_dir,
staging: &staging,
levels,
};
let encoding = run.encode(archive_tensor_count)?;
write_streamed_preview(destination, &run, limits.ple_part_elements, encoding)
}
fn require_free_destination(destination: &Path) -> Result<(), String> {
if fs::symlink_metadata(destination).is_ok()
|| fs::symlink_metadata(provenance_path(destination)?).is_ok()
{
return Err("KAR archive or provenance destination already exists".into());
}
Ok(())
}
fn plan_stream_parts(
identity: &derived_mixed::ShardedIdentity,
source_dir: &Path,
limits: PartLimits,
) -> Result<Vec<Vec<kar_shard_plan::PartIdentity>>, String> {
if let Some(limit) = limits.ple_part_elements {
kar_shard_plan::plan_shards_with_ple_limit(identity, source_dir, limit)
} else {
kar_shard_plan::plan_shards_with_limit(identity, source_dir, limits.max_part_elements)
}
}
fn require_stream_budget(
archive_parts: &[Vec<kar_shard_plan::PartIdentity>],
archive_tensor_count: usize,
destination: &Path,
levels: u8,
) -> Result<(), String> {
if archive_tensor_count == 0 || archive_tensor_count > 100_000 {
return Err("streamed sharded tensor count exceeds KAR-2 limits".into());
}
// Every nested part stores at least `levels` four-byte plane words per
// 32 values; a RAW fallback stores four bytes per value. The smaller of
// these is a safe lower bound before section files are created. Passing
// this gate does not guarantee enough space for scales and metadata.
let minimum_payload_bytes = archive_parts
.iter()
.flat_map(|parts| parts.iter())
.try_fold(0u64, |sum, part| {
sum.checked_add(minimum_part_payload_bytes(part.derived_bytes, levels)?)
.ok_or_else(|| "KAR minimum payload size overflow".to_string())
})?;
let destination_parent = destination
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or(Path::new("."));
model::require_space(destination_parent, minimum_payload_bytes)
.map_err(|error| format!("KAR minimum payload does not fit: {error}"))
}
fn streamed_tensors(prepared: &[StreamedTensor], levels: u8) -> Vec<kar_writer::Tensor<'_>> {
prepared
.iter()
.map(|entry| {
let tensor = &entry.prepared;
kar_writer::Tensor {
name: &tensor.name,
dims: &tensor.dims,
source_dtype: 0,
source_digest: tensor.source_digest,
source_offset: tensor.source_offset,
data: if entry.nested {
nested_file_data(tensor, levels)
} else {
kar_writer::TensorData::RawFile {
path: &tensor.section_path,
offset: 0,
bytes: tensor.section_bytes,
}
},
}
})
.collect()
}
fn stream_builder(levels: u8, ple_part_elements: Option<u64>) -> String {
if let Some(limit) = ple_part_elements {
format!(
"leleka-api/experimental-sharded-stream-v5:g32:l{levels}:sample65536:plepart{limit}"
)
} else {
format!("leleka-api/experimental-sharded-stream-v4:g32:l{levels}:sample65536")
}
}
fn write_streamed_archive(
destination: &Path,
run: &StreamedRun<'_>,
ple_part_elements: Option<u64>,
encoding: &StreamedEncoding,
) -> Result<kar::Summary, String> {
let identity = run.identity;
let tensors = streamed_tensors(&encoding.prepared, run.levels);
let builder = stream_builder(run.levels, ple_part_elements);
let source_identity = kar_writer::SourceIdentity {
name: "gguf-shards#derived-f32-le-v4",
architecture: require_architecture(&encoding.architecture)?,
builder: &builder,
digest: identity.derived_sha256,
total_elements: identity.derived_bytes / 4,
bytes: identity.derived_bytes,
};
kar_writer::write_archive_consuming_files(destination, &source_identity, &tensors)
}
fn write_streamed_preview(
destination: &Path,
run: &StreamedRun<'_>,
ple_part_elements: Option<u64>,
encoding: StreamedEncoding,
) -> Result<PreviewSummary, String> {
let archive = write_streamed_archive(destination, run, ple_part_elements, &encoding)?;
let archive_digest = hash_file(destination)?;
let mut provenance = sharded_provenance_value(run.identity, archive_digest);
let parts = run.archive_parts;
apply_stream_policy(&mut provenance, run.levels, parts, ple_part_elements);
let provenance_path = write_sibling_provenance(destination, &provenance)?;
Ok(PreviewSummary {
archive,
archive_digest,
maximum_relative_l2: encoding.maximum_relative_l2,
tensor_distortions: encoding.tensor_distortions,
provenance_path: Some(provenance_path),
})
}