Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1082 lines
57 KiB
Rust
1082 lines
57 KiB
Rust
use std::{env, io::Read, path::Path, sync::Arc, time::Duration};
|
|
|
|
use tokio::sync::{mpsc, watch};
|
|
|
|
use strata_control::{
|
|
app, config::Config, derived_iq3, derived_mixed, doctor, gguf, kar, kar_fixture, kar_memory,
|
|
kar_overlay, kar_quality, model, model_pipeline, prepare_preview, tokenizer, tokenizer_assets,
|
|
worker,
|
|
};
|
|
|
|
#[tokio::main]
|
|
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|
let args: Vec<String> = env::args().skip(1).collect();
|
|
match args.as_slice() {
|
|
[command, sub, rest @ ..] if command == "tools" && sub == "mtp-fetch" => {
|
|
let code = strata_control::mtp_fetch::cli(rest).await?;
|
|
if code != 0 {
|
|
std::process::exit(code);
|
|
}
|
|
Ok(())
|
|
}
|
|
[command, rest @ ..] if command == "tools" => {
|
|
print!("{}", leleka_offline_tools::cli::run(rest)?);
|
|
Ok(())
|
|
}
|
|
[command, rest @ ..] if command == "api-key" => {
|
|
println!("{}", strata_control::key_init::run(rest)?);
|
|
Ok(())
|
|
}
|
|
[model, action, spec, source_flag, source, output_flag, output, options @ ..]
|
|
if model == "model" && action == "prepare-native-pack"
|
|
&& source_flag == "--source-dir" && output_flag == "--output" => {
|
|
let manifest = strata_control::model::Manifest::from_spec(spec).await?;
|
|
let mut pack = strata_control::native_pack::Options::default();
|
|
let mut options = options.iter();
|
|
while let Some(flag) = options.next() {
|
|
match flag.as_str() {
|
|
"--compat-bf16" => pack.compat_bf16 = true,
|
|
"--experts-bin" => pack.experts_bin = true,
|
|
"--base" => pack.base = Some(options.next().ok_or("--base needs a pack directory")?.into()),
|
|
_ => return Err(format!("unknown prepare-native-pack option {flag}").into()),
|
|
}
|
|
}
|
|
println!("{}", strata_control::native_pack::prepare_with(&manifest, Path::new(source), Path::new(output), &pack).await?);
|
|
Ok(())
|
|
}
|
|
[command, flag, path, defer]
|
|
if command == "provision" && flag == "--config" && defer == "--defer-memory-check" => {
|
|
let mut config = Config::load_with_path(Some(Path::new(path)))?;
|
|
config.prepare_for_switch().await?;
|
|
println!("{}", serde_json::json!({"assets_verified": config.assets.len(), "native_model_prepared":config.native_model.is_some(), "mtp_pack_structurally_validated":config.mtp_pack.is_some(), "worker_started": false, "memory_admission": "deferred_until_serve"}));
|
|
Ok(())
|
|
}
|
|
[command, flag, path] if command == "provision" && flag == "--config" => {
|
|
let mut config = Config::load_with_path(Some(Path::new(path)))?;
|
|
config.provision().await?;
|
|
println!("{}", serde_json::json!({"assets_verified": config.assets.len(), "native_model_prepared":config.native_model.is_some(), "mtp_pack_structurally_validated":config.mtp_pack.is_some(), "worker_started": false}));
|
|
Ok(())
|
|
}
|
|
[command] if command == "check-config" => {
|
|
println!("{}", strata_control::preflight::check(None)?);
|
|
Ok(())
|
|
}
|
|
[command, flag, config] if command == "check-config" && flag == "--config" => {
|
|
println!("{}", strata_control::preflight::check(Some(Path::new(config)))?);
|
|
Ok(())
|
|
}
|
|
[command] if command == "engine-info" => {
|
|
println!("{}", strata_control::embedded_engine::info());
|
|
Ok(())
|
|
}
|
|
[command] if command == "engine-help" => strata_control::embedded_engine::help(),
|
|
[command] if command == "--engine-license" => {
|
|
print!("{}", include_str!("../../engine/strata/LICENSE"));
|
|
Ok(())
|
|
}
|
|
[model, action, source, tensor, flag, output]
|
|
if model == "model" && action == "export-tensor-f32" && flag == "--output" =>
|
|
{
|
|
let report = strata_control::tensor_export::export(Path::new(source), tensor, Path::new(output))?;
|
|
println!("{}", serde_json::to_string(&report)?);
|
|
Ok(())
|
|
}
|
|
[] => serve(None).await,
|
|
[command] if command == "serve" => serve(None).await,
|
|
[command, flag, config] if command == "serve" && flag == "--config" => {
|
|
serve(Some(Path::new(config))).await
|
|
}
|
|
[command, rest @ ..] if command == "wait-ready" => {
|
|
println!("{}", strata_control::wait_ready::run(rest).await?);
|
|
Ok(())
|
|
}
|
|
[command, rest @ ..] if command == "service-switch" => {
|
|
println!("{}", strata_control::service_switch::run(rest).await?);
|
|
Ok(())
|
|
}
|
|
[command, rest @ ..] if command == "service-control" => {
|
|
println!("{}", strata_control::service_install::control(rest).await?);
|
|
Ok(())
|
|
}
|
|
[command, rest @ ..] if command == "service-install" => {
|
|
println!("{}", strata_control::service_install::run(rest).await?);
|
|
Ok(())
|
|
}
|
|
[command, rest @ ..] if command == "service-unit" => {
|
|
let (config, working_dir, env_file) = match rest {
|
|
[config_flag, config, work_flag, working_dir]
|
|
if config_flag == "--config" && work_flag == "--working-dir" =>
|
|
(config, working_dir, None),
|
|
[config_flag, config, work_flag, working_dir, env_flag, env_file]
|
|
if config_flag == "--config" && work_flag == "--working-dir" && env_flag == "--env-file" =>
|
|
(config, working_dir, Some(Path::new(env_file))),
|
|
_ => return Err("usage: strata-next service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]".into()),
|
|
};
|
|
print!("{}", strata_control::service_unit::render(
|
|
&env::current_exe()?, Path::new(config), Path::new(working_dir), env_file,
|
|
)?);
|
|
Ok(())
|
|
}
|
|
[doctor] if doctor == "doctor" => {
|
|
doctor::report().await?;
|
|
Ok(())
|
|
}
|
|
[model, action, flag, output]
|
|
if model == "model" && action == "smoke-fixture" && flag == "--output" =>
|
|
{
|
|
let result = kar_fixture::write(Path::new(output))?;
|
|
println!("KAR-2 smoke fixture: {output}");
|
|
println!("tensor=smoke.expert elements=32 level=2");
|
|
println!("archive_sha256={}", hex::encode(result.archive_digest));
|
|
println!("output_fnv1a64={:x}", result.decoded_fnv1a64);
|
|
Ok(())
|
|
}
|
|
[model, action, flag, output]
|
|
if model == "model" && action == "ple-smoke-fixture" && flag == "--output" =>
|
|
{
|
|
let result = kar_fixture::write_ple(Path::new(output))?;
|
|
println!("KAR-2 PLE smoke fixture: {output}");
|
|
println!("archive_sha256={}", hex::encode(result.archive_digest));
|
|
for (row, checksum) in result.row_fnv1a64.iter().enumerate() {
|
|
println!("row={row} fnv1a64={checksum:016x}");
|
|
}
|
|
Ok(())
|
|
}
|
|
[model, action, manifest, flag, output]
|
|
if model == "model" && flag == "--output" && action == "fetch" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest).await?;
|
|
model::fetch(&manifest, Path::new(output)).await?;
|
|
Ok(())
|
|
}
|
|
[model, action, manifest, flag, output]
|
|
if model == "model" && flag == "--output" && action == "verify" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest).await?;
|
|
model::verify(&manifest, Path::new(output)).await?;
|
|
Ok(())
|
|
}
|
|
[model, action, manifest_spec, source_flag, source_dir, output_flag, destination, levels_flag, levels]
|
|
if model == "model"
|
|
&& action == "ensure-sharded-preview"
|
|
&& source_flag == "--source-dir"
|
|
&& output_flag == "--output"
|
|
&& levels_flag == "--levels" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest_spec).await?;
|
|
let outcome = model_pipeline::ensure_sharded_preview(
|
|
&manifest,
|
|
Path::new(source_dir),
|
|
Path::new(destination),
|
|
levels.parse()?,
|
|
).await?;
|
|
match outcome {
|
|
model_pipeline::PreviewOutcome::Created(result) => {
|
|
println!("created and verified experimental KAR-2: {destination}");
|
|
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
|
|
println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2);
|
|
}
|
|
model_pipeline::PreviewOutcome::Reused(summary) => {
|
|
println!("reused verified experimental KAR-2: {destination}");
|
|
println!("tensors: {}", summary.tensor_count);
|
|
}
|
|
}
|
|
println!("not eligible for serving without a full-model quality gate");
|
|
Ok(())
|
|
}
|
|
[model, action, manifest_spec, source_flag, source_dir, output_flag, destination, levels_flag, levels]
|
|
if model == "model"
|
|
&& action == "ensure-sharded-streamed"
|
|
&& source_flag == "--source-dir"
|
|
&& output_flag == "--output"
|
|
&& levels_flag == "--levels" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest_spec).await?;
|
|
let outcome = model_pipeline::ensure_sharded_streamed(
|
|
&manifest, Path::new(source_dir), Path::new(destination), levels.parse()?,
|
|
).await?;
|
|
let source_bytes = manifest.files.iter().try_fold(0u64, |sum, file| sum.checked_add(file.size))
|
|
.ok_or("sharded source byte count overflow")?;
|
|
match outcome {
|
|
model_pipeline::PreviewOutcome::Created(result) => {
|
|
println!("created and verified experimental streamed KAR-2: {destination}");
|
|
println!("archive bytes: {}", result.archive.archive_bytes);
|
|
println!("source GGUF bytes: {source_bytes}");
|
|
println!("archive/source ratio: {:.6}", result.archive.archive_bytes as f64 / source_bytes as f64);
|
|
println!("accounted bits per weight: {:.6}", result.archive.accounted_bpw);
|
|
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
|
|
println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2);
|
|
print_top_tensor_distortions(&result.tensor_distortions);
|
|
}
|
|
model_pipeline::PreviewOutcome::Reused(summary) => {
|
|
println!("reused verified experimental streamed KAR-2: {destination}");
|
|
println!("archive bytes: {}", summary.archive_bytes);
|
|
println!("source GGUF bytes: {source_bytes}");
|
|
println!("archive/source ratio: {:.6}", summary.archive_bytes as f64 / source_bytes as f64);
|
|
println!("accounted bits per weight: {:.6}", summary.accounted_bpw);
|
|
println!("tensors: {}", summary.tensor_count);
|
|
}
|
|
}
|
|
println!("not eligible for serving without a full-model quality gate");
|
|
Ok(())
|
|
}
|
|
[model, action, manifest_spec, source_flag, source_dir, output_flag, destination, levels_flag, levels, ple_flag, ple_limit]
|
|
if model == "model"
|
|
&& action == "ensure-sharded-streamed"
|
|
&& source_flag == "--source-dir"
|
|
&& output_flag == "--output"
|
|
&& levels_flag == "--levels"
|
|
&& ple_flag == "--ple-part-elements" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest_spec).await?;
|
|
let limit: u64 = ple_limit.parse()?;
|
|
let outcome = model_pipeline::ensure_sharded_streamed_ple(
|
|
&manifest, Path::new(source_dir), Path::new(destination), levels.parse()?, limit,
|
|
).await?;
|
|
match outcome {
|
|
model_pipeline::PreviewOutcome::Created(result) => {
|
|
println!("created and verified experimental PLE-partitioned KAR-2: {destination}");
|
|
println!("archive bytes: {}", result.archive.archive_bytes);
|
|
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
|
|
println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2);
|
|
print_top_tensor_distortions(&result.tensor_distortions);
|
|
}
|
|
model_pipeline::PreviewOutcome::Reused(summary) => {
|
|
println!("reused verified experimental PLE-partitioned KAR-2: {destination}");
|
|
println!("archive bytes: {}", summary.archive_bytes);
|
|
println!("tensors: {}", summary.tensor_count);
|
|
}
|
|
}
|
|
println!("PLE maximum part elements: {limit}");
|
|
println!("not eligible for serving without a full-model quality gate");
|
|
Ok(())
|
|
}
|
|
[model, action, path] if model == "model" && action == "inspect-metadata" => {
|
|
// Every key/value as one JSON object; non-finite floats are the strings "nan", "inf", "-inf".
|
|
let entries = gguf::metadata_entries(Path::new(path))?;
|
|
println!("{}", strata_control::gguf_json::metadata_json(entries));
|
|
Ok(())
|
|
}
|
|
[model, action, path] if model == "model" && action == "inspect" => {
|
|
let summary = gguf::inspect(Path::new(path))?;
|
|
println!("GGUF v3: {path}");
|
|
println!("size: {} bytes", summary.file_size);
|
|
println!("tensors: {}; metadata: {}", summary.tensors, summary.metadata);
|
|
println!("data starts at byte {}", summary.data_start);
|
|
if let Some(architecture) = summary.architecture {
|
|
println!("architecture: {architecture}");
|
|
}
|
|
if let (Some(no), Some(count)) = (summary.split_no, summary.split_count) {
|
|
println!("split: {}/{}", no + 1, count);
|
|
}
|
|
println!("tensor types: {:?}", summary.types);
|
|
Ok(())
|
|
}
|
|
[model, action, path] if model == "model" && action == "index" => {
|
|
print_tensor_index(Path::new(path), false)
|
|
}
|
|
[model, action, path, hash_flag]
|
|
if model == "model" && action == "index" && hash_flag == "--hash" =>
|
|
{
|
|
print_tensor_index(Path::new(path), true)
|
|
}
|
|
[model, action, path] if model == "model" && action == "derive-iq3-identity" => {
|
|
let identity = derived_iq3::fingerprint(Path::new(path))?;
|
|
println!("{}", serde_json::to_string_pretty(&serde_json::json!({
|
|
"derivation": "strata-next/iq3_s-to-f32-le-v1",
|
|
"gguf_sha256": hex::encode(identity.gguf_sha256),
|
|
"derived_f32_sha256": hex::encode(identity.derived_sha256),
|
|
"derived_f32_bytes": identity.derived_bytes,
|
|
"tensors": identity.tensors.iter().map(|tensor| serde_json::json!({
|
|
"name": tensor.name,
|
|
"derived_offset": tensor.derived_offset,
|
|
"derived_bytes": tensor.derived_bytes,
|
|
"iq3_sha256": hex::encode(tensor.iq3_sha256),
|
|
"f32_sha256": hex::encode(tensor.f32_sha256),
|
|
})).collect::<Vec<_>>(),
|
|
}))?);
|
|
Ok(())
|
|
}
|
|
[model, action, path] if model == "model" && action == "derive-mixed-identity" => {
|
|
let identity = derived_mixed::fingerprint(Path::new(path))?;
|
|
println!("{}", serde_json::to_string_pretty(&serde_json::json!({
|
|
"derivation": "strata-next/gguf-mixed-to-f32-le-v1",
|
|
"gguf_sha256": hex::encode(identity.gguf_sha256),
|
|
"derived_f32_sha256": hex::encode(identity.derived_sha256),
|
|
"derived_f32_bytes": identity.derived_bytes,
|
|
"tensors": identity.tensors.iter().map(|tensor| serde_json::json!({
|
|
"name": tensor.name,
|
|
"source_kind": tensor.source_kind,
|
|
"source_sha256": hex::encode(tensor.source_sha256),
|
|
"derived_offset": tensor.derived_offset,
|
|
"derived_bytes": tensor.derived_bytes,
|
|
"f32_sha256": hex::encode(tensor.f32_sha256),
|
|
})).collect::<Vec<_>>(),
|
|
}))?);
|
|
Ok(())
|
|
}
|
|
[model, action, manifest_spec, source_flag, source_dir]
|
|
if model == "model"
|
|
&& action == "derive-sharded-identity"
|
|
&& source_flag == "--source-dir" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest_spec).await?;
|
|
let identity = derived_mixed::fingerprint_shards(&manifest, Path::new(source_dir))?;
|
|
println!("{}", serde_json::to_string_pretty(&serde_json::json!({
|
|
"derivation": "strata-next/gguf-shards-to-f32-le-v1",
|
|
"derived_f32_sha256": hex::encode(identity.derived_sha256),
|
|
"derived_f32_bytes": identity.derived_bytes,
|
|
"shards": identity.shards.iter().map(|shard| serde_json::json!({
|
|
"name": shard.name,
|
|
"gguf_sha256": hex::encode(shard.gguf_sha256),
|
|
"gguf_bytes": shard.gguf_bytes,
|
|
"tensor_count": shard.tensor_count,
|
|
})).collect::<Vec<_>>(),
|
|
"tensors": identity.tensors.iter().map(|tensor| serde_json::json!({
|
|
"name": tensor.name,
|
|
"source_kind": tensor.source_kind,
|
|
"source_sha256": hex::encode(tensor.source_sha256),
|
|
"derived_offset": tensor.derived_offset,
|
|
"derived_bytes": tensor.derived_bytes,
|
|
"f32_sha256": hex::encode(tensor.f32_sha256),
|
|
})).collect::<Vec<_>>(),
|
|
}))?);
|
|
Ok(())
|
|
}
|
|
[model, action, source, output_flag, destination, levels_flag, levels]
|
|
if model == "model"
|
|
&& action == "prepare-f32-preview"
|
|
&& output_flag == "--output"
|
|
&& levels_flag == "--levels" =>
|
|
{
|
|
let result = prepare_preview::prepare_f32(
|
|
Path::new(source),
|
|
Path::new(destination),
|
|
levels.parse()?,
|
|
)?;
|
|
println!("EXPERIMENTAL F32 preview KAR-2: {destination}");
|
|
println!("tensors: {}", result.archive.tensor_count);
|
|
println!("source SHA-256: {}", hex::encode(result.archive.source_digest));
|
|
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
|
|
println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2);
|
|
println!("not eligible for serving without a full-model quality gate");
|
|
Ok(())
|
|
}
|
|
[model, action, source, output_flag, destination, levels_flag, levels]
|
|
if model == "model"
|
|
&& action == "prepare-iq3-preview"
|
|
&& output_flag == "--output"
|
|
&& levels_flag == "--levels" =>
|
|
{
|
|
let result = prepare_preview::prepare_iq3(
|
|
Path::new(source),
|
|
Path::new(destination),
|
|
levels.parse()?,
|
|
)?;
|
|
println!("EXPERIMENTAL IQ3_S-derived F32 KAR-2: {destination}");
|
|
println!("tensors: {}", result.archive.tensor_count);
|
|
println!("derived F32 SHA-256: {}", hex::encode(result.archive.source_digest));
|
|
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
|
|
println!("provenance: {}", result.provenance_path.unwrap().display());
|
|
println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2);
|
|
println!("not eligible for serving without a full-model quality gate");
|
|
Ok(())
|
|
}
|
|
[model, action, source, output_flag, destination, levels_flag, levels]
|
|
if model == "model"
|
|
&& action == "prepare-mixed-preview"
|
|
&& output_flag == "--output"
|
|
&& levels_flag == "--levels" =>
|
|
{
|
|
let result = prepare_preview::prepare_mixed(
|
|
Path::new(source),
|
|
Path::new(destination),
|
|
levels.parse()?,
|
|
)?;
|
|
println!("EXPERIMENTAL mixed GGUF-derived F32 KAR-2: {destination}");
|
|
println!("tensors: {}", result.archive.tensor_count);
|
|
println!("derived F32 SHA-256: {}", hex::encode(result.archive.source_digest));
|
|
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
|
|
println!("provenance: {}", result.provenance_path.unwrap().display());
|
|
println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2);
|
|
println!("not eligible for serving without a full-model quality gate");
|
|
Ok(())
|
|
}
|
|
[model, action, manifest_spec, source_flag, source_dir, output_flag, destination, levels_flag, levels]
|
|
if model == "model"
|
|
&& action == "prepare-sharded-preview"
|
|
&& source_flag == "--source-dir"
|
|
&& output_flag == "--output"
|
|
&& levels_flag == "--levels" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest_spec).await?;
|
|
let result = prepare_preview::prepare_sharded(
|
|
&manifest,
|
|
Path::new(source_dir),
|
|
Path::new(destination),
|
|
levels.parse()?,
|
|
)?;
|
|
println!("EXPERIMENTAL sharded GGUF-derived F32 KAR-2: {destination}");
|
|
println!("tensors: {}", result.archive.tensor_count);
|
|
println!("derived F32 SHA-256: {}", hex::encode(result.archive.source_digest));
|
|
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
|
|
println!("provenance: {}", result.provenance_path.unwrap().display());
|
|
println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2);
|
|
println!("not eligible for serving without a full-model quality gate");
|
|
Ok(())
|
|
}
|
|
[model, action, manifest_spec, source_flag, source_dir, output_flag, destination, levels_flag, levels]
|
|
if model == "model"
|
|
&& action == "prepare-sharded-streamed"
|
|
&& source_flag == "--source-dir"
|
|
&& output_flag == "--output"
|
|
&& levels_flag == "--levels" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest_spec).await?;
|
|
let result = prepare_preview::prepare_sharded_streamed(
|
|
&manifest, Path::new(source_dir), Path::new(destination), levels.parse()?,
|
|
)?;
|
|
let source_bytes = manifest.files.iter().try_fold(0u64, |sum, file| sum.checked_add(file.size))
|
|
.ok_or("sharded source byte count overflow")?;
|
|
println!("EXPERIMENTAL streamed sharded GGUF-derived F32 KAR-2: {destination}");
|
|
println!("tensors: {}", result.archive.tensor_count);
|
|
println!("archive bytes: {}", result.archive.archive_bytes);
|
|
println!("source GGUF bytes: {source_bytes}");
|
|
println!("archive/source ratio: {:.6}", result.archive.archive_bytes as f64 / source_bytes as f64);
|
|
println!("accounted bits per weight: {:.6}", result.archive.accounted_bpw);
|
|
println!("derived F32 SHA-256: {}", hex::encode(result.archive.source_digest));
|
|
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
|
|
println!("provenance: {}", result.provenance_path.unwrap().display());
|
|
println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2);
|
|
print_top_tensor_distortions(&result.tensor_distortions);
|
|
println!("not eligible for serving without a full-model quality gate");
|
|
Ok(())
|
|
}
|
|
[model, action, manifest_spec, source_flag, source_dir, output_flag, destination, levels_flag, levels, ple_flag, ple_limit]
|
|
if model == "model"
|
|
&& action == "prepare-sharded-streamed"
|
|
&& source_flag == "--source-dir"
|
|
&& output_flag == "--output"
|
|
&& levels_flag == "--levels"
|
|
&& ple_flag == "--ple-part-elements" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest_spec).await?;
|
|
let limit: u64 = ple_limit.parse()?;
|
|
let result = prepare_preview::prepare_sharded_streamed_ple(
|
|
&manifest, Path::new(source_dir), Path::new(destination), levels.parse()?, limit,
|
|
)?;
|
|
println!("EXPERIMENTAL PLE-partitioned KAR-2: {destination}");
|
|
println!("tensors: {}", result.archive.tensor_count);
|
|
println!("archive bytes: {}", result.archive.archive_bytes);
|
|
println!("archive SHA-256: {}", hex::encode(result.archive_digest));
|
|
println!("PLE maximum part elements: {limit}");
|
|
println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2);
|
|
print_top_tensor_distortions(&result.tensor_distortions);
|
|
println!("not eligible for serving without a full-model quality gate");
|
|
Ok(())
|
|
}
|
|
[model, action, path, tensor, level]
|
|
if model == "model" && action == "checksum-kar-preview" =>
|
|
{
|
|
let values = kar::decode_preview_tensor(Path::new(path), tensor, level.parse()?)?;
|
|
println!("tensor={tensor} elements={} level={level}", values.len());
|
|
println!("output_fnv1a64={:x}", kar::f32_fnv1a64(&values));
|
|
println!("first={} last={}", values[0], values[values.len() - 1]);
|
|
Ok(())
|
|
}
|
|
[model, action, path, tensor, level, row_flag, row_id]
|
|
if model == "model" && action == "checksum-kar-row" && row_flag == "--row" =>
|
|
{
|
|
let row_id: u32 = row_id.parse()?;
|
|
let values = kar::decode_tensor_row(Path::new(path), tensor, level.parse()?, row_id)?;
|
|
println!("tensor={tensor} row_id={row_id} elements={} level={level}", values.len());
|
|
println!("output_fnv1a64={:x}", kar::f32_fnv1a64(&values));
|
|
println!("first={} last={}", values[0], values[values.len() - 1]);
|
|
Ok(())
|
|
}
|
|
[model, action, path] if model == "model" && action == "inspect-kar" => {
|
|
let summary = kar::inspect(Path::new(path))?;
|
|
println!("KAR-2: {path}");
|
|
println!("size: {} bytes", summary.archive_bytes);
|
|
println!("tensors: {}; elements: {}", summary.tensor_count, summary.total_elements);
|
|
println!("source elements: {}", summary.source_total_elements);
|
|
println!("accounted bpw: {}", summary.accounted_bpw);
|
|
println!("source SHA-256: {}", hex::encode(summary.source_digest));
|
|
println!("source bytes: {}", summary.source_bytes);
|
|
println!("bounded metadata checks passed; payload CRCs and padding not checked");
|
|
Ok(())
|
|
}
|
|
[model, action, path, level_flag, level, budget_flag, budget]
|
|
if model == "model" && action == "plan-kar-memory"
|
|
&& level_flag == "--level" && budget_flag == "--budget-mib" =>
|
|
{
|
|
let budget_mib: u64 = budget.parse()?;
|
|
let budget_bytes = budget_mib.checked_mul(1 << 20).ok_or("GPU budget overflow")?;
|
|
let report = kar_memory::plan(Path::new(path), level.parse()?, budget_bytes)?;
|
|
println!("{}", serde_json::to_string_pretty(&report)?);
|
|
Ok(())
|
|
}
|
|
[model, action, base_flag, base, overlay_flag, overlay, base_level_flag, base_level, overlay_level_flag, overlay_level, budget_flag, budget]
|
|
if model == "model" && action == "plan-kar-overlay-memory"
|
|
&& base_flag == "--base" && overlay_flag == "--overlay"
|
|
&& base_level_flag == "--base-level"
|
|
&& overlay_level_flag == "--overlay-level"
|
|
&& budget_flag == "--budget-mib" =>
|
|
{
|
|
let budget_mib: u64 = budget.parse()?;
|
|
let budget_bytes = budget_mib.checked_mul(1 << 20).ok_or("GPU budget overflow")?;
|
|
let report = kar_memory::plan_selected(
|
|
Path::new(base),
|
|
Path::new(overlay),
|
|
base_level.parse()?,
|
|
overlay_level.parse()?,
|
|
budget_bytes,
|
|
)?;
|
|
println!("{}", serde_json::to_string_pretty(&report)?);
|
|
Ok(())
|
|
}
|
|
[model, action, path] if model == "model" && action == "verify-kar" => {
|
|
let summary = kar::verify(Path::new(path))?;
|
|
println!("verified KAR-2 metadata and {} payload CRCs", summary.tensor_count);
|
|
println!("source SHA-256: {}", hex::encode(summary.source_digest));
|
|
println!("source files not checked; use --manifest SPEC --source-dir DIR");
|
|
Ok(())
|
|
}
|
|
[model, action, archive, source_flag, source]
|
|
if model == "model" && action == "verify-iq3-preview" && source_flag == "--source" =>
|
|
{
|
|
let summary = prepare_preview::verify_iq3(Path::new(source), Path::new(archive))?;
|
|
println!("verified IQ3 preview: {archive}");
|
|
println!("tensors: {}", summary.tensor_count);
|
|
println!("derived F32 SHA-256: {}", hex::encode(summary.source_digest));
|
|
println!("original GGUF, provenance, KAR source records, and payload CRCs match");
|
|
println!("not a model quality or GPU execution result");
|
|
Ok(())
|
|
}
|
|
[model, action, archive, source_flag, source]
|
|
if model == "model" && action == "verify-mixed-preview" && source_flag == "--source" =>
|
|
{
|
|
let summary = prepare_preview::verify_mixed(Path::new(source), Path::new(archive))?;
|
|
println!("verified mixed preview: {archive}");
|
|
println!("tensors: {}", summary.tensor_count);
|
|
println!("derived F32 SHA-256: {}", hex::encode(summary.source_digest));
|
|
println!("original GGUF, provenance, KAR source records, and payload CRCs match");
|
|
println!("not a model quality or GPU execution result");
|
|
Ok(())
|
|
}
|
|
[model, action, archive, manifest_flag, manifest_spec, source_flag, source_dir]
|
|
if model == "model"
|
|
&& action == "verify-sharded-preview"
|
|
&& manifest_flag == "--manifest"
|
|
&& source_flag == "--source-dir" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest_spec).await?;
|
|
let summary = prepare_preview::verify_sharded(
|
|
&manifest,
|
|
Path::new(source_dir),
|
|
Path::new(archive),
|
|
)?;
|
|
println!("verified sharded preview: {archive}");
|
|
println!("tensors: {}", summary.tensor_count);
|
|
println!("derived F32 SHA-256: {}", hex::encode(summary.source_digest));
|
|
println!("manifest shards, provenance, KAR source records, and payload CRCs match");
|
|
println!("not a model quality or GPU execution result");
|
|
Ok(())
|
|
}
|
|
[model, action, archive, manifest_flag, manifest_spec, source_flag, source_dir, levels_flag, levels]
|
|
if model == "model"
|
|
&& action == "verify-sharded-streamed"
|
|
&& manifest_flag == "--manifest"
|
|
&& source_flag == "--source-dir"
|
|
&& levels_flag == "--levels" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest_spec).await?;
|
|
let summary = prepare_preview::verify_sharded_streamed(
|
|
&manifest, Path::new(source_dir), Path::new(archive), levels.parse()?,
|
|
)?;
|
|
println!("verified experimental streamed sharded KAR-2: {archive}");
|
|
println!("tensors: {}", summary.tensor_count);
|
|
println!("derived F32 SHA-256: {}", hex::encode(summary.source_digest));
|
|
println!("manifest shards, provenance, KAR source records, and payload CRCs match");
|
|
println!("not a model quality or GPU execution result");
|
|
Ok(())
|
|
}
|
|
[model, action, archive, manifest_flag, manifest_spec, source_flag, source_dir, levels_flag, levels, ple_flag, ple_limit]
|
|
if model == "model"
|
|
&& action == "verify-sharded-streamed"
|
|
&& manifest_flag == "--manifest"
|
|
&& source_flag == "--source-dir"
|
|
&& levels_flag == "--levels"
|
|
&& ple_flag == "--ple-part-elements" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest_spec).await?;
|
|
let limit: u64 = ple_limit.parse()?;
|
|
let summary = prepare_preview::verify_sharded_streamed_ple(
|
|
&manifest, Path::new(source_dir), Path::new(archive), levels.parse()?, limit,
|
|
)?;
|
|
println!("verified experimental PLE-partitioned KAR-2: {archive}");
|
|
println!("tensors: {}", summary.tensor_count);
|
|
println!("derived F32 SHA-256: {}", hex::encode(summary.source_digest));
|
|
println!("PLE maximum part elements: {limit}");
|
|
println!("manifest shards, provenance, KAR source records, and payload CRCs match");
|
|
println!("not a model quality or GPU execution result");
|
|
Ok(())
|
|
}
|
|
[model, action, archive, manifest_flag, manifest_spec, source_flag, source_dir, levels_flag, levels, output_flag, report_path]
|
|
if model == "model"
|
|
&& action == "analyze-sharded-kar"
|
|
&& manifest_flag == "--manifest"
|
|
&& source_flag == "--source-dir"
|
|
&& levels_flag == "--levels"
|
|
&& output_flag == "--output" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest_spec).await?;
|
|
let report = kar_quality::analyze(
|
|
&manifest, Path::new(source_dir), Path::new(archive), levels.parse()?,
|
|
)?;
|
|
kar_quality::write_report(Path::new(report_path), &report)?;
|
|
println!("sampled KAR reconstruction report: {report_path}");
|
|
println!("records: {}", report.records.len());
|
|
println!("archive SHA-256: {}", report.archive_sha256);
|
|
println!("samples are not a full-tensor or model-quality gate");
|
|
Ok(())
|
|
}
|
|
[model, action, archive, manifest_flag, manifest_spec, source_flag, source_dir, levels_flag, levels, output_flag, report_path, assume_flag]
|
|
if model == "model"
|
|
&& action == "analyze-sharded-kar"
|
|
&& manifest_flag == "--manifest"
|
|
&& source_flag == "--source-dir"
|
|
&& levels_flag == "--levels"
|
|
&& output_flag == "--output"
|
|
&& assume_flag == "--assume-verified" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest_spec).await?;
|
|
let report = kar_quality::analyze_previously_verified(
|
|
&manifest, Path::new(source_dir), Path::new(archive), levels.parse()?,
|
|
)?;
|
|
kar_quality::write_report(Path::new(report_path), &report)?;
|
|
println!("sampled KAR reconstruction report: {report_path}");
|
|
println!("records: {}", report.records.len());
|
|
println!("archive SHA-256 from previously verified provenance: {}", report.archive_sha256);
|
|
println!("full archive and source hashes were not recomputed in this run");
|
|
println!("samples are not a full-tensor or model-quality gate");
|
|
Ok(())
|
|
}
|
|
[model, action, manifest_spec, source_flag, source_dir, base_flag, base_archive, candidates_flag, candidates_path, output_flag, destination]
|
|
if model == "model"
|
|
&& action == "prepare-kar-overlay"
|
|
&& source_flag == "--source-dir"
|
|
&& base_flag == "--base"
|
|
&& candidates_flag == "--candidates"
|
|
&& output_flag == "--output" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest_spec).await?;
|
|
let result = kar_overlay::prepare(
|
|
&manifest,
|
|
Path::new(source_dir),
|
|
Path::new(base_archive),
|
|
Path::new(candidates_path),
|
|
Path::new(destination),
|
|
)?;
|
|
println!("EXPERIMENTAL KAR precision overlay: {destination}");
|
|
println!("records: {}; bytes: {}", result.record_count, result.archive_bytes);
|
|
println!("overlay SHA-256: {}", hex::encode(result.archive_sha256));
|
|
println!("maximum selected-record relative L2: {:.8}", result.maximum_relative_l2);
|
|
println!("provenance: {}", result.provenance_path.display());
|
|
println!("not eligible for serving without model-quality and GPU gates");
|
|
Ok(())
|
|
}
|
|
[model, action, manifest_spec, source_flag, source_dir, base_flag, base_archive, overlay_flag, overlay_archive, output_flag, report_path]
|
|
if model == "model"
|
|
&& action == "compare-kar-overlay"
|
|
&& source_flag == "--source-dir"
|
|
&& base_flag == "--base"
|
|
&& overlay_flag == "--overlay"
|
|
&& output_flag == "--output" =>
|
|
{
|
|
let manifest = model::Manifest::from_spec(manifest_spec).await?;
|
|
let comparison = kar_overlay::compare(
|
|
&manifest,
|
|
Path::new(source_dir),
|
|
Path::new(base_archive),
|
|
Path::new(overlay_archive),
|
|
)?;
|
|
kar_overlay::write_comparison(Path::new(report_path), &comparison)?;
|
|
println!("complete selected-tensor L2/L3 comparison: {report_path}");
|
|
println!("records: {}", comparison.records.len());
|
|
println!("not a full-model quality or GPU performance result");
|
|
Ok(())
|
|
}
|
|
[model, action, base_flag, base_archive, overlay_flag, overlay_archive]
|
|
if model == "model"
|
|
&& action == "resolve-kar-overlay"
|
|
&& base_flag == "--base"
|
|
&& overlay_flag == "--overlay" =>
|
|
{
|
|
let resolution = kar_overlay::resolve_verified(
|
|
Path::new(base_archive),
|
|
Path::new(overlay_archive),
|
|
)?;
|
|
println!("{}", serde_json::to_string_pretty(&resolution)?);
|
|
Ok(())
|
|
}
|
|
[model, action, path, manifest_flag, manifest_spec, source_flag, source_dir]
|
|
if model == "model" && action == "verify-kar"
|
|
&& manifest_flag == "--manifest" && source_flag == "--source-dir" => {
|
|
let summary = kar::verify(Path::new(path))?;
|
|
let manifest = model::Manifest::from_spec(manifest_spec).await?;
|
|
kar::verify_source_files(&summary, &manifest, Path::new(source_dir))?;
|
|
println!("verified KAR-2 metadata, {} payload CRCs, and source identity", summary.tensor_count);
|
|
Ok(())
|
|
}
|
|
[model, action, path, flag, output]
|
|
if model == "model" && action == "extract-tokenizer" && flag == "--output" =>
|
|
{
|
|
let destination = tokenizer_assets::extract(Path::new(path), Path::new(output))?;
|
|
println!("extracted {}", destination.display());
|
|
Ok(())
|
|
}
|
|
[model, action, path, input]
|
|
if model == "model" && action == "tokenize" && input != "--stdin" =>
|
|
{
|
|
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
|
|
println!("{}", serde_json::to_string(&tokenizer.encode(input, false)?)?);
|
|
Ok(())
|
|
}
|
|
[model, action, path, input, flag]
|
|
if model == "model" && action == "tokenize" && input != "--stdin" && flag == "--special" =>
|
|
{
|
|
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
|
|
println!("{}", serde_json::to_string(&tokenizer.encode(input, true)?)?);
|
|
Ok(())
|
|
}
|
|
[model, action, path, flag]
|
|
if model == "model" && action == "tokenize" && flag == "--stdin" =>
|
|
{
|
|
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
|
|
let mut input = String::new();
|
|
std::io::stdin().read_to_string(&mut input)?;
|
|
println!("{}", serde_json::to_string(&tokenizer.encode(&input, false)?)?);
|
|
Ok(())
|
|
}
|
|
[model, action, path, stdin_flag, special_flag]
|
|
if model == "model"
|
|
&& action == "tokenize"
|
|
&& stdin_flag == "--stdin"
|
|
&& special_flag == "--special" =>
|
|
{
|
|
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
|
|
let mut input = String::new();
|
|
std::io::stdin().read_to_string(&mut input)?;
|
|
println!("{}", serde_json::to_string(&tokenizer.encode(&input, true)?)?);
|
|
Ok(())
|
|
}
|
|
[model, action, path, ids] if model == "model" && action == "detokenize" => {
|
|
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
|
|
let ids = if ids.is_empty() {
|
|
Vec::new()
|
|
} else {
|
|
ids.split(',')
|
|
.map(str::parse::<u32>)
|
|
.collect::<Result<Vec<_>, _>>()?
|
|
};
|
|
println!("{}", serde_json::to_string(&tokenizer.decode(&ids)?)?);
|
|
Ok(())
|
|
}
|
|
// Batch forms for the differential harness (scripts/offline/diff_tokenizer.py): one JSON value per line.
|
|
[model, action] if model == "model" && action == "pre-tokenize-batch" => {
|
|
for line in std::io::stdin().lines() {
|
|
let text: String = serde_json::from_str(&line?)?;
|
|
let pieces = tokenizer::pre_tokenize(&text);
|
|
println!("{}", serde_json::to_string(&pieces.ok())?);
|
|
}
|
|
Ok(())
|
|
}
|
|
[model, action, path, rest @ ..]
|
|
if model == "model"
|
|
&& action == "tokenize-batch"
|
|
&& rest.iter().all(|flag| flag == "--special") =>
|
|
{
|
|
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
|
|
for line in std::io::stdin().lines() {
|
|
let text: String = serde_json::from_str(&line?)?;
|
|
let ids = tokenizer.encode(&text, !rest.is_empty()).ok();
|
|
println!("{}", serde_json::to_string(&ids)?);
|
|
}
|
|
Ok(())
|
|
}
|
|
// JSON lines {"messages": [...], "tools": [...]|null, "add_generation_prompt": true, "kwargs": {...}} ->
|
|
// {"ok": "<prompt>"} or {"error": "<message>"}: the pinned chat template, for scripts/offline/diff_chat_template.py.
|
|
[model, action] if model == "model" && action == "render-chat" => {
|
|
use strata_control::prompt::{ChatInput, Json, pinned};
|
|
for line in std::io::stdin().lines() {
|
|
let request: Json = serde_json::from_str(&line?)?;
|
|
let array = |key: &str| match request.get(key) {
|
|
Some(Json::Array(items)) => Some(items.as_slice()),
|
|
_ => None,
|
|
};
|
|
let kwargs = match request.get("kwargs") {
|
|
Some(Json::Object(fields)) => fields.iter().map(|(k, v)| (k.as_str(), v.clone())).collect(),
|
|
_ => Vec::new(),
|
|
};
|
|
let rendered = pinned().render(&ChatInput {
|
|
messages: array("messages").unwrap_or(&[]),
|
|
tools: array("tools"),
|
|
add_generation_prompt: !matches!(request.get("add_generation_prompt"), Some(Json::Bool(false))),
|
|
kwargs,
|
|
});
|
|
println!(
|
|
"{}",
|
|
match rendered {
|
|
Ok(text) => serde_json::json!({"ok": text}),
|
|
Err(message) => serde_json::json!({"error": message}),
|
|
}
|
|
);
|
|
}
|
|
Ok(())
|
|
}
|
|
[model, action, path] if model == "model" && action == "detokenize-batch" => {
|
|
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
|
|
for line in std::io::stdin().lines() {
|
|
let ids: Vec<u32> = serde_json::from_str(&line?)?;
|
|
println!("{}", serde_json::to_string(&tokenizer.decode(&ids).ok())?);
|
|
}
|
|
Ok(())
|
|
}
|
|
[version] if version == "--version" || version == "-V" => {
|
|
println!("strata-next {}", env!("CARGO_PKG_VERSION"));
|
|
Ok(())
|
|
}
|
|
[license] if license == "--ggml-license" => {
|
|
println!("ggml IQ3_S grid table — MIT License\n");
|
|
print!("{}", include_str!("../third_party/ggml/LICENSE"));
|
|
Ok(())
|
|
}
|
|
_ => Err("usage: strata-next [service-switch --catalog FILE [--from ID] --to ID --state-dir ABSOLUTE_DIR|service-switch reconcile --catalog FILE --state-dir DIR --expected-journal-sha SHA256|api-key init --file ABSOLUTE_PATH|serve [--config FILE]|provision --config FILE [--defer-memory-check]|check-config [--config FILE]|wait-ready --url LOOPBACK_ORIGIN --model ID [--key-file FILE] [--timeout-s N]|service-control status|start|stop|restart|enable|disable|start-ready|restart-ready|drain-stop|resume --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]|service-install --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--enable] [--start|--start-ready --ready-url ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|doctor|engine-info|engine-help|--ggml-license|model prepare-native-pack MANIFEST --source-dir DIR --output DIR [--compat-bf16] [--experts-bin] [--base BASE_PACK_DIR]|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model export-tensor-f32 FILE.gguf TENSOR --output FILE.f32|model inspect FILE.gguf|model inspect-metadata FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level N --overlay-level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model checksum-kar-row FILE.kar TENSOR LEVEL --row ROW_ID|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N --ple-part-elements E|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model pre-tokenize-batch|model tokenize-batch TOKENIZER_DIR [--special]|model detokenize-batch TOKENIZER_DIR|model render-chat|model detokenize TOKENIZER_DIR IDS|tools embd-bf16-pack --model DIR --out FILE.gguf|tools ple-fp8-pack --model DIR --out FILE.gguf|tools draft-vocab --gguf FIRST.gguf [--base IDS.bin] [--add han,kana,hangul,cjk_punct,cjk,cyrillic] [--out IDS.bin] [--stats]|tools make-profile [TRACE ...] (--base PROFILE.bin | --no-base) --out PROFILE.bin [--n-expert N]|tools mtp-rt --gguf mtp-q2_0.gguf --out DIR [--n-expert N]|tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR] [--repo URL] [--sha256-file FILE]]".into()),
|
|
}
|
|
}
|
|
|
|
fn print_top_tensor_distortions(distortions: &[prepare_preview::TensorDistortion]) {
|
|
let mut ranked = distortions.iter().collect::<Vec<_>>();
|
|
ranked.sort_by(|a, b| b.relative_l2.total_cmp(&a.relative_l2));
|
|
println!(
|
|
"highest relative L2 by KAR record (top 20 of {}):",
|
|
ranked.len()
|
|
);
|
|
for tensor in ranked.into_iter().take(20) {
|
|
println!(
|
|
" {:.8} kind={} bytes={} {}",
|
|
tensor.relative_l2, tensor.source_kind, tensor.section_bytes, tensor.name
|
|
);
|
|
}
|
|
}
|
|
|
|
fn print_tensor_index(path: &Path, hash: bool) -> Result<(), Box<dyn std::error::Error>> {
|
|
let index = gguf::tensor_index(path)?;
|
|
for (number, tensor) in index.tensors.iter().enumerate() {
|
|
let mut row = serde_json::json!({
|
|
"name": tensor.name,
|
|
"dimensions": tensor.dimensions,
|
|
"type": tensor.kind,
|
|
"offset": index.summary.data_start + tensor.offset,
|
|
"bytes": tensor.bytes,
|
|
});
|
|
if hash {
|
|
row["sha256"] = hex::encode(gguf::tensor_sha256(path, &index, number)?).into();
|
|
}
|
|
println!("{row}");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
async fn serve(config_path: Option<&Path>) -> Result<(), Box<dyn std::error::Error>> {
|
|
let mut config = Config::load_with_path(config_path)?;
|
|
let history_dir = config.response_history_dir.clone();
|
|
let response_history = tokio::task::spawn_blocking(move || {
|
|
strata_control::responses::ResponseHistory::open(history_dir.as_deref())
|
|
})
|
|
.await??;
|
|
config.check_host().await?;
|
|
let _embedded = match config.worker.as_mut() {
|
|
Some(worker) => {
|
|
let embedded = strata_control::embedded_engine::resolve(&worker.executable)?;
|
|
if let Some(engine) = &embedded {
|
|
worker.executable = engine.executable.clone().into_os_string();
|
|
}
|
|
embedded
|
|
}
|
|
None => None,
|
|
};
|
|
config.provision().await?;
|
|
let listener = tokio::net::TcpListener::bind(config.bind).await?;
|
|
let mut settings = strata_control::settings::Settings::new(config.sampling.clone())
|
|
.with_reasoning_budget(config.reasoning_budget_tokens.clone());
|
|
if let Some(path) = config.shared_settings_file.clone() {
|
|
settings = settings.with_shared_file(path);
|
|
}
|
|
let mut state = app::AppState {
|
|
queue_timeout: config.queue_timeout,
|
|
lifecycle: strata_control::lifecycle::Lifecycle::new(config.max_in_flight_requests)?,
|
|
response_history: Arc::new(tokio::sync::RwLock::new(response_history)),
|
|
api_key: config.api_key.clone(),
|
|
model: config.model.clone(),
|
|
settings: Arc::new(settings),
|
|
aliases: Arc::new(config.aliases.clone()),
|
|
cors: Arc::new(leleka_serving_policy::cors::Cors::new(
|
|
config.cors_origins.clone(),
|
|
)),
|
|
trusted_origins: Arc::new(config.trusted_origins.clone()),
|
|
..Default::default()
|
|
};
|
|
if !config.mcp_servers.is_empty() {
|
|
let hub = Arc::new(strata_control::mcp::Hub::new(
|
|
std::mem::take(&mut config.mcp_servers),
|
|
config.mcp_settings.clone(),
|
|
));
|
|
state.mcp = Some(hub.clone());
|
|
// Servers start in the background (npx may download a package first); GET /mcp shows progress.
|
|
tokio::spawn(async move { hub.start().await });
|
|
}
|
|
if config.cors_origins.iter().any(|o| o == "*") && config.api_key.is_none() {
|
|
strata_control::elog!(
|
|
"CORS on /v1/*: WARNING: any web page may use the model (no API key)"
|
|
);
|
|
}
|
|
if let Some(path) = config.tokenizer_dir.as_deref() {
|
|
state.tokenizer = Some(Arc::new(tokenizer::Tokenizer::from_assets(path)?));
|
|
state.chat_template = std::fs::read_to_string(path.join("chat_template.jinja"))
|
|
.ok()
|
|
.map(Arc::from);
|
|
}
|
|
// The image encoder starts before the engine: a GPU encoder takes its VRAM first, and the engine sizes its
|
|
// cache from what is left.
|
|
if let Some(vision) = config.vision.take() {
|
|
strata_control::elog!("loading the vision encoder ...");
|
|
state.vision = Some(strata_control::vision::Vision::start(vision).await?);
|
|
}
|
|
let (shutdown_tx, shutdown_rx) = watch::channel(false);
|
|
let runtime_task = match config.runtime.take() {
|
|
Some(runtime) => {
|
|
let tokenizer = state
|
|
.tokenizer
|
|
.clone()
|
|
.ok_or("runtime requires the tokenizer assets (runtime.tokenizer_dir)")?;
|
|
let (sender, receiver) = mpsc::channel(16);
|
|
let (control_sender, control_receiver) = mpsc::channel(16);
|
|
state.generation = Some(sender);
|
|
state.control = Some(control_sender);
|
|
state.worker.write().await.known_max_context = Some(runtime.max_context);
|
|
let backend = leleka_runtime_client::backend::GrpcBackend::new(
|
|
tokio::runtime::Handle::current(),
|
|
runtime.address,
|
|
runtime.token,
|
|
);
|
|
let worker_config = strata_control::backend_worker::BackendWorkerConfig {
|
|
tokenizer,
|
|
model: runtime.model,
|
|
runtime: runtime.runtime,
|
|
max_context: runtime.max_context,
|
|
max_output_tokens: runtime.max_output_tokens,
|
|
generation_timeout: runtime.generation_timeout,
|
|
stall_timeout: runtime.stall_timeout,
|
|
attach_retry: runtime.attach_retry,
|
|
health_interval: runtime.health_interval,
|
|
cancel_drain_timeout: Duration::from_secs(20),
|
|
prefix_view: Some(state.prefix_cache.clone()),
|
|
memory_view: Some(state.memory.clone()),
|
|
};
|
|
Some(tokio::spawn(
|
|
strata_control::backend_worker::run_backend_worker(
|
|
Box::new(backend),
|
|
worker_config,
|
|
state.worker.clone(),
|
|
shutdown_rx.clone(),
|
|
receiver,
|
|
control_receiver,
|
|
),
|
|
))
|
|
}
|
|
None => None,
|
|
};
|
|
let worker_task = config.worker.map(|mut config| {
|
|
config.vision = state.vision.clone();
|
|
let (sender, receiver) = mpsc::channel(16);
|
|
let (control_sender, control_receiver) = mpsc::channel(16);
|
|
state.generation = Some(sender);
|
|
state.control = Some(control_sender);
|
|
tokio::spawn(worker::run_supervised(
|
|
config,
|
|
state.worker.clone(),
|
|
shutdown_rx,
|
|
receiver,
|
|
control_receiver,
|
|
))
|
|
});
|
|
if let (Some(idle), true) = (config.idle_unload, state.control.is_some()) {
|
|
strata_control::elog!(
|
|
"the model unloads after {} s without requests",
|
|
idle.as_secs_f64()
|
|
);
|
|
let poll = Duration::from_secs_f64(leleka_serving_policy::idle::poll_interval_s(
|
|
idle.as_secs_f64(),
|
|
));
|
|
tokio::spawn(strata_control::server_api::idle_unload_loop(
|
|
state.clone(),
|
|
idle,
|
|
poll,
|
|
));
|
|
}
|
|
strata_control::elog!("strata-control listening on {}", listener.local_addr()?);
|
|
let server_shutdown = shutdown_tx.clone();
|
|
let state_mcp = state.mcp.clone();
|
|
let state_vision = state.vision.clone();
|
|
let lifecycle = state.lifecycle.clone();
|
|
let shutdown_grace = config.shutdown_grace;
|
|
// TCP_NODELAY: SSE events and small responses must not wait for the peer's delayed ACK (Nagle's algorithm).
|
|
use axum::serve::ListenerExt as _;
|
|
let listener = listener.tap_io(|tcp| {
|
|
let _ = tcp.set_nodelay(true);
|
|
});
|
|
let result = axum::serve(listener, app::router(state))
|
|
.with_graceful_shutdown(async move {
|
|
shutdown_signal().await;
|
|
lifecycle.begin_shutdown();
|
|
if !shutdown_grace.is_zero() && !lifecycle.wait_drained(shutdown_grace).await {
|
|
strata_control::elog!("Shutdown admission grace expired; stopping worker");
|
|
}
|
|
let _ = server_shutdown.send(true);
|
|
})
|
|
.await;
|
|
let _ = shutdown_tx.send(true);
|
|
if let Some(hub) = &state_mcp {
|
|
hub.close().await;
|
|
}
|
|
if let Some(vision) = &state_vision {
|
|
vision.close().await;
|
|
}
|
|
if let Some(task) = worker_task {
|
|
task.await?;
|
|
}
|
|
if let Some(task) = runtime_task {
|
|
task.await?;
|
|
}
|
|
result?;
|
|
Ok(())
|
|
}
|
|
|
|
async fn shutdown_signal() {
|
|
#[cfg(unix)]
|
|
{
|
|
use tokio::signal::unix::{SignalKind, signal};
|
|
let mut terminate = signal(SignalKind::terminate()).expect("install SIGTERM handler");
|
|
tokio::select! {
|
|
_ = tokio::signal::ctrl_c() => {},
|
|
_ = terminate.recv() => {},
|
|
}
|
|
}
|
|
#[cfg(not(unix))]
|
|
tokio::signal::ctrl_c()
|
|
.await
|
|
.expect("install Ctrl-C handler");
|
|
}
|