mirror of
https://github.com/storytold/craft-ai-integrations.git
synced 2026-11-28 09:22:19 +01:00
feat(burn-setup): prepare SAM 2.1 weights for Burn once, on this computer (#89)
* refactor(engine-rten): let another engine reuse the SAM 2.1 request handling Loaded, Backend, Prediction, read_prompt, prompt_points and best_proposal become public. Visibility only: the click and box mapping, the picture kept between requests, the empty-mask answer and the size checks then live in one place for every SAM 2.1 engine. * feat(burn-setup): prepare SAM 2.1 weights for Burn once, on this computer Brings in craft-ai-burn-setup (feature `conversion`): checks the two published ONNX files by size and SHA-256, converts them to Burn weights with the pinned burn-onnx 0.22.0, and keeps one checked, locked, shared copy. Nothing is hosted or downloaded. Mutation group bp (10 cases). Cargo.lock additions are the optional burn-onnx tree (generated). * fix(burn-setup): sweep the scratch folders a killed run left, and keep craft-ai-features a dev dependency CodeRabbit on #89: tempdir_in(cache) folders hold the two source copies (about 130 MB) and were removed only by Drop, so a killed app leaked them for good. They now carry the cache key and a role in their names, and after the key's lock is taken the same key's leftovers are removed (other keys' folders, the lock file and links are left alone). Red first: leftovers_of_a_killed_run_are_swept_for_this_key_only. Mutation cases burn-killed-run-leftovers-kept and burn-sweep-takes-other-keys, both caught. craft-ai-features is only used by a unit test, so it moves to dev-dependencies. * fix(burn-setup): sweep only the scratch folders, not a renamed copy of the key's folder CodeRabbit on #89 (second round): sweep_stale removed every folder starting with <key>., so a damaged copy a person renamed to <key>.backup would be deleted on the next preparation. It now matches only <key>.work., <key>.conv. and <key>.out., the names the scratch folders are made with (one constant for both). Red first: the sweep test gained a <key>.backup folder that must survive. Mutation group bp 13/13 caught, including the new case burn-sweep-takes-a-renamed-copy.
This commit is contained in:
1 parent
ee83eab4bb
commit
97dc996251
12 files changed
+5919
-71
No files matched your search
Generated
+4845
-70
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "craft-ai-burn-setup"
|
||||
description = "Prepare and cache supported Burn model weights on this computer, without a compiler or hosted converted files."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version = "1.95"
|
||||
repository.workspace = true
|
||||
publish = false
|
||||
|
||||
[features]
|
||||
conversion = ["dep:burn-onnx"]
|
||||
|
||||
[dependencies]
|
||||
craft-ai-core.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2 = "0.11"
|
||||
tempfile = "3"
|
||||
burn-onnx = { version = "=0.22.0", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-ai-features = { path = "../ai-features", package = "craft-ai-features" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[[example]]
|
||||
name = "prepare_sam21"
|
||||
required-features = ["conversion"]
|
||||
@@ -0,0 +1,38 @@
|
||||
//! Explicit local setup probe. Never downloads, changes a binding or contacts a server.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::time::Instant;
|
||||
|
||||
/// Runs one approved preparation and reports its actual checked output paths.
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
let [source, cache] = args.as_slice() else {
|
||||
eprintln!("usage: prepare_sam21 <original-model-folder> <shared-model-cache-folder>");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let start = Instant::now();
|
||||
match craft_ai_burn_setup::prepare_sam21(
|
||||
&PathBuf::from(source),
|
||||
&PathBuf::from(cache),
|
||||
&AtomicBool::new(false),
|
||||
) {
|
||||
Ok(weights) => {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({
|
||||
"preparation": format!("{:?}", weights.preparation),
|
||||
"encoder": weights.encoder,
|
||||
"decoder": weights.decoder,
|
||||
"elapsed_ms": start.elapsed().as_millis(),
|
||||
})
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("{}", error.message);
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
//! Cache lifecycle. Conversion is injected so its filesystem rules need no real model in tests.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::fs::{self, File};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use craft_ai_core::{AiError, ErrorKind};
|
||||
|
||||
/// Whether a completed request prepared weights or reused a checked saved copy.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Preparation {
|
||||
Converted,
|
||||
Reused,
|
||||
}
|
||||
|
||||
/// Checked local weights. This does not register a connection or change any binding.
|
||||
#[derive(Debug)]
|
||||
pub struct PreparedWeights {
|
||||
pub encoder: PathBuf,
|
||||
pub decoder: PathBuf,
|
||||
pub preparation: Preparation,
|
||||
}
|
||||
|
||||
/// Expected original bytes for one component, frozen before setup starts.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct SourceFile {
|
||||
pub name: String,
|
||||
pub size: u64,
|
||||
pub sha256: String,
|
||||
}
|
||||
|
||||
/// One supported architecture and converter revision, not an arbitrary model name.
|
||||
pub(crate) struct Bundle {
|
||||
pub revision: String,
|
||||
pub files: [SourceFile; 2],
|
||||
}
|
||||
|
||||
/// Converts the two checked original files into weights inside the caller-owned work folder.
|
||||
pub(crate) trait Converter {
|
||||
/// Writes both weight components to the private conversion directory, or reports failure.
|
||||
fn convert(&self, source: &Path, output: &Path) -> Result<(), AiError>;
|
||||
}
|
||||
|
||||
/// Saved conversion identity and output checksums. JSON never supplies filesystem paths.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Manifest {
|
||||
key: String,
|
||||
hashes: [String; 2],
|
||||
}
|
||||
|
||||
/// Distinguishes the original checkpoint and converter revision.
|
||||
fn cache_key(bundle: &Bundle) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(bundle.revision.as_bytes());
|
||||
for file in &bundle.files {
|
||||
digest.update([0]);
|
||||
digest.update(file.name.as_bytes());
|
||||
digest.update(file.size.to_le_bytes());
|
||||
digest.update(file.sha256.as_bytes());
|
||||
}
|
||||
hex(&digest.finalize())
|
||||
}
|
||||
|
||||
/// Encodes digest bytes independently of sha2 formatting traits.
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
|
||||
}
|
||||
|
||||
/// Safe local error without paths reaching the screen.
|
||||
fn file_error(_: impl std::fmt::Display) -> AiError {
|
||||
AiError::unsupported(
|
||||
"The saved model files could not be read or written. Check the model folder and try again.",
|
||||
)
|
||||
}
|
||||
|
||||
/// Hashes a file with bounded working memory.
|
||||
fn hash_file(path: &Path) -> Result<String, AiError> {
|
||||
let metadata = fs::symlink_metadata(path).map_err(file_error)?;
|
||||
if !metadata.file_type().is_file() || metadata.len() > 512 * 1024 * 1024 {
|
||||
return Err(file_error("not a bounded plain file"));
|
||||
}
|
||||
let mut file = File::open(path).map_err(file_error)?;
|
||||
let mut hash = Sha256::new();
|
||||
let mut bytes = [0u8; 64 * 1024];
|
||||
loop {
|
||||
let count = file.read(&mut bytes).map_err(file_error)?;
|
||||
if count == 0 {
|
||||
return Ok(hex(&hash.finalize()));
|
||||
}
|
||||
hash.update(&bytes[..count]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a not-yet-created destination through its existing parent without writing anything.
|
||||
fn destination(path: &Path) -> Result<PathBuf, AiError> {
|
||||
let absolute = std::path::absolute(path).map_err(file_error)?;
|
||||
let path = absolute.as_path();
|
||||
if path
|
||||
.components()
|
||||
.any(|c| c == std::path::Component::ParentDir)
|
||||
{
|
||||
return Err(file_error("parent traversal in destination"));
|
||||
}
|
||||
for parent in path.ancestors().take(256) {
|
||||
if let Ok(base) = fs::canonicalize(parent) {
|
||||
return Ok(base.join(path.strip_prefix(parent).map_err(file_error)?));
|
||||
}
|
||||
}
|
||||
Err(file_error("destination has no existing parent"))
|
||||
}
|
||||
|
||||
/// Cancel is checked before any write and again before publishing a complete conversion.
|
||||
pub(super) fn check_cancelled(cancelled: &AtomicBool) -> Result<(), AiError> {
|
||||
if cancelled.load(Ordering::Acquire) {
|
||||
return Err(AiError::new(
|
||||
ErrorKind::Cancelled,
|
||||
"Model preparation was cancelled.",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Fixed component paths from a complete cache directory.
|
||||
fn prepared(dir: &Path, preparation: Preparation) -> PreparedWeights {
|
||||
PreparedWeights {
|
||||
encoder: dir.join("encoder.bpk"),
|
||||
decoder: dir.join("decoder.bpk"),
|
||||
preparation,
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepares a supported bundle without touching the original files or shared settings.
|
||||
pub(crate) fn prepare(
|
||||
bundle: &Bundle,
|
||||
source: &Path,
|
||||
cache: &Path,
|
||||
cancelled: &AtomicBool,
|
||||
converter: &dyn Converter,
|
||||
) -> Result<PreparedWeights, AiError> {
|
||||
check_cancelled(cancelled)?;
|
||||
if let Ok(original) = fs::canonicalize(source)
|
||||
&& destination(cache)?.starts_with(original)
|
||||
{
|
||||
return Err(AiError::unsupported(
|
||||
"Choose a separate folder for the saved model copy, outside the original model folder.",
|
||||
));
|
||||
}
|
||||
fs::create_dir_all(cache).map_err(file_error)?;
|
||||
if !fs::symlink_metadata(cache)
|
||||
.map_err(file_error)?
|
||||
.file_type()
|
||||
.is_dir()
|
||||
{
|
||||
return Err(file_error("cache is not a plain directory"));
|
||||
}
|
||||
let key = cache_key(bundle);
|
||||
let final_dir = cache.join(&key);
|
||||
let lock_path = cache.join(format!("{key}.lock"));
|
||||
if let Ok(metadata) = fs::symlink_metadata(&lock_path)
|
||||
&& !metadata.file_type().is_file()
|
||||
{
|
||||
return Err(file_error("lock is not a plain file"));
|
||||
}
|
||||
let lock = fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(lock_path)
|
||||
.map_err(file_error)?;
|
||||
lock.try_lock().map_err(|_| {
|
||||
AiError::unsupported(
|
||||
"Another app is preparing this model. Wait for it to finish, then try again.",
|
||||
)
|
||||
})?;
|
||||
if let Ok(metadata) = fs::symlink_metadata(&final_dir) {
|
||||
if !metadata.file_type().is_dir() {
|
||||
return Err(file_error("saved copy is not a plain directory"));
|
||||
}
|
||||
let path = final_dir.join("manifest.json");
|
||||
if !fs::symlink_metadata(&path)
|
||||
.map_err(file_error)?
|
||||
.file_type()
|
||||
.is_file()
|
||||
{
|
||||
return Err(file_error("manifest is not a plain file"));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
File::open(path)
|
||||
.map_err(file_error)?
|
||||
.take(4097)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(file_error)?;
|
||||
if bytes.len() > 4096 {
|
||||
return Err(file_error("oversized manifest"));
|
||||
}
|
||||
let manifest: Manifest = serde_json::from_slice(&bytes).map_err(file_error)?;
|
||||
if manifest.key == key {
|
||||
for (name, expected) in ["encoder.bpk", "decoder.bpk"]
|
||||
.into_iter()
|
||||
.zip(&manifest.hashes)
|
||||
{
|
||||
if hash_file(&final_dir.join(name))? != *expected {
|
||||
return Err(file_error("damaged saved weights"));
|
||||
}
|
||||
}
|
||||
check_cancelled(cancelled)?;
|
||||
return Ok(prepared(&final_dir, Preparation::Reused));
|
||||
}
|
||||
return Err(file_error("different conversion"));
|
||||
}
|
||||
sweep_stale(cache, &key);
|
||||
let scratch = |role: &str| {
|
||||
tempfile::Builder::new()
|
||||
.prefix(&format!("{key}.{role}."))
|
||||
.tempdir_in(cache)
|
||||
.map_err(file_error)
|
||||
};
|
||||
let [work_role, conversion_role, output_role] = SCRATCH_ROLES;
|
||||
let work = scratch(work_role)?;
|
||||
let conversion = scratch(conversion_role)?;
|
||||
let output = scratch(output_role)?;
|
||||
for file in &bundle.files {
|
||||
let snapshot = work.path().join(&file.name);
|
||||
let input = File::open(source.join(&file.name)).map_err(file_error)?;
|
||||
let mut target = File::create(&snapshot).map_err(file_error)?;
|
||||
let copied = std::io::copy(&mut input.take(file.size.saturating_add(1)), &mut target)
|
||||
.map_err(file_error)?;
|
||||
drop(target);
|
||||
if copied != file.size || hash_file(&snapshot)? != file.sha256 {
|
||||
return Err(AiError::unsupported(
|
||||
"The original model files do not match this option. Check them in Set up AI first.",
|
||||
));
|
||||
}
|
||||
}
|
||||
check_cancelled(cancelled)?;
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
converter.convert(work.path(), conversion.path())
|
||||
}))
|
||||
.map_err(|_| {
|
||||
AiError::unsupported(
|
||||
"The model could not be prepared. Try again or choose another option in Set up AI.",
|
||||
)
|
||||
})??;
|
||||
check_cancelled(cancelled)?;
|
||||
let mut hashes = [String::new(), String::new()];
|
||||
for (name, hash) in ["encoder.bpk", "decoder.bpk"].into_iter().zip(&mut hashes) {
|
||||
let converted = conversion.path().join(name);
|
||||
let size = fs::metadata(&converted).map_err(file_error)?.len();
|
||||
if size == 0 || size > 512 * 1024 * 1024 {
|
||||
return Err(file_error("invalid converted file size"));
|
||||
}
|
||||
fs::rename(&converted, output.path().join(name)).map_err(file_error)?;
|
||||
*hash = hash_file(&output.path().join(name))?;
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(output.path().join(name))
|
||||
.map_err(file_error)?
|
||||
.sync_all()
|
||||
.map_err(file_error)?;
|
||||
}
|
||||
let manifest = serde_json::to_vec(&Manifest { key, hashes }).map_err(file_error)?;
|
||||
let mut file = File::create(output.path().join("manifest.json")).map_err(file_error)?;
|
||||
file.write_all(&manifest).map_err(file_error)?;
|
||||
file.sync_all().map_err(file_error)?;
|
||||
drop(file);
|
||||
check_cancelled(cancelled)?;
|
||||
fs::rename(output.path(), &final_dir).map_err(file_error)?;
|
||||
Ok(prepared(&final_dir, Preparation::Converted))
|
||||
}
|
||||
|
||||
/// The roles of the scratch folders one preparation makes: the copy of the originals, the
|
||||
/// converter's output and the folder that becomes the published copy.
|
||||
const SCRATCH_ROLES: [&str; 3] = ["work", "conv", "out"];
|
||||
|
||||
/// Removes the scratch folders a killed run left for this cache key. The caller holds this key's
|
||||
/// lock, so no live run owns them. Only plain folders named `<key>.<role>.` followed by anything,
|
||||
/// for the roles above, are removed: another key's folders, a damaged copy renamed to `<key>.backup`,
|
||||
/// the lock file and any link are left alone.
|
||||
fn sweep_stale(cache: &Path, key: &str) {
|
||||
let prefixes = SCRATCH_ROLES.map(|role| format!("{key}.{role}."));
|
||||
let Ok(entries) = fs::read_dir(cache) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let ours = entry
|
||||
.file_name()
|
||||
.to_str()
|
||||
.is_some_and(|n| prefixes.iter().any(|p| n.starts_with(p.as_str())));
|
||||
if ours && entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
let _ = fs::remove_dir_all(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
//! Extra coverage for cache identity, malformed state and filesystem boundaries.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A relative destination is resolved against the host's current directory, without creating it.
|
||||
#[test]
|
||||
fn a_relative_cache_destination_is_supported() {
|
||||
assert_eq!(
|
||||
destination(Path::new("new-burn-cache")).unwrap(),
|
||||
std::env::current_dir()
|
||||
.unwrap()
|
||||
.canonicalize()
|
||||
.unwrap()
|
||||
.join("new-burn-cache")
|
||||
);
|
||||
}
|
||||
|
||||
/// A changed expected checkpoint must not silently pick up weights from an older checkpoint.
|
||||
#[test]
|
||||
fn a_new_expected_source_never_reuses_previous_weights() {
|
||||
let mut r = Rig::new();
|
||||
let fake = Fake::default();
|
||||
r.prepare(&fake).unwrap();
|
||||
r.bundle.files[0].sha256 = "0".repeat(64);
|
||||
assert!(r.prepare(&fake).is_err());
|
||||
assert_eq!(fake.0.get(), 1);
|
||||
}
|
||||
|
||||
/// A bounded manifest read must not accept arbitrarily padded, otherwise valid JSON.
|
||||
#[test]
|
||||
fn an_oversized_manifest_is_refused() {
|
||||
let r = Rig::new();
|
||||
let fake = Fake::default();
|
||||
let first = r.prepare(&fake).unwrap();
|
||||
let manifest = first.encoder.parent().unwrap().join("manifest.json");
|
||||
let mut bytes = fs::read(&manifest).unwrap();
|
||||
bytes.resize(8192, b' ');
|
||||
fs::write(manifest, bytes).unwrap();
|
||||
assert!(r.prepare(&fake).is_err());
|
||||
}
|
||||
|
||||
/// A reused conversion is self-contained and does not need its original download present.
|
||||
#[test]
|
||||
fn a_complete_conversion_can_be_reused_after_originals_are_removed() {
|
||||
let r = Rig::new();
|
||||
let fake = Fake::default();
|
||||
let first = r.prepare(&fake).unwrap();
|
||||
fs::remove_dir_all(&r.source).unwrap();
|
||||
let second = r.prepare(&fake).unwrap();
|
||||
assert_eq!(second.preparation, Preparation::Reused);
|
||||
assert_eq!(second.encoder, first.encoder);
|
||||
assert_eq!(fake.0.get(), 1);
|
||||
}
|
||||
|
||||
/// A new conversion or compiled architecture revision must not reuse earlier tensors.
|
||||
#[test]
|
||||
fn a_new_converter_revision_has_its_own_saved_copy() {
|
||||
let mut r = Rig::new();
|
||||
let fake = Fake::default();
|
||||
let first = r.prepare(&fake).unwrap();
|
||||
r.bundle.revision.push_str("-next");
|
||||
let second = r.prepare(&fake).unwrap();
|
||||
assert_eq!(second.preparation, Preparation::Converted);
|
||||
assert_ne!(second.encoder, first.encoder);
|
||||
assert_eq!(fake.0.get(), 2);
|
||||
assert!(first.encoder.is_file());
|
||||
}
|
||||
|
||||
/// Checking a truncated source must fail before entering the converter.
|
||||
#[test]
|
||||
fn a_wrong_source_size_is_refused() {
|
||||
let mut r = Rig::new();
|
||||
r.bundle.files[1].size += 1;
|
||||
let fake = Fake::default();
|
||||
assert!(r.prepare(&fake).is_err());
|
||||
assert_eq!(fake.0.get(), 0);
|
||||
}
|
||||
|
||||
/// A converter failure must leave no partially published directory or loose temporary files.
|
||||
#[test]
|
||||
fn conversion_failure_cleans_temporary_files() {
|
||||
let r = Rig::new();
|
||||
struct Fails;
|
||||
impl Converter for Fails {
|
||||
/// Writes half a bundle and reports failure.
|
||||
fn convert(&self, _: &Path, output: &Path) -> Result<(), AiError> {
|
||||
fs::write(output.join("encoder.bpk"), b"partial").unwrap();
|
||||
Err(AiError::unsupported("Could not prepare the model."))
|
||||
}
|
||||
}
|
||||
assert!(r.prepare(&Fails).is_err());
|
||||
assert!(!r.cache.join(cache_key(&r.bundle)).exists());
|
||||
assert!(
|
||||
fs::read_dir(&r.cache).unwrap().all(|e| e
|
||||
.unwrap()
|
||||
.path()
|
||||
.extension()
|
||||
.is_some_and(|x| x == "lock"))
|
||||
);
|
||||
}
|
||||
|
||||
/// A library must never place conversion by-products inside the person's source directory.
|
||||
#[test]
|
||||
fn the_original_folder_cannot_be_used_as_the_cache() {
|
||||
let r = Rig::new();
|
||||
assert!(
|
||||
prepare(
|
||||
&r.bundle,
|
||||
&r.source,
|
||||
&r.source,
|
||||
&r.cancelled,
|
||||
&Fake::default()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let mut names: Vec<_> = fs::read_dir(&r.source)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name())
|
||||
.collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["decoder.onnx", "encoder.onnx"]);
|
||||
}
|
||||
|
||||
/// On Unix, a saved component linked outside the managed directory is not a cache entry.
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_linked_saved_component_is_refused() {
|
||||
let r = Rig::new();
|
||||
let fake = Fake::default();
|
||||
let first = r.prepare(&fake).unwrap();
|
||||
let elsewhere = r._dir.path().join("elsewhere.bpk");
|
||||
fs::rename(&first.encoder, &elsewhere).unwrap();
|
||||
std::os::unix::fs::symlink(&elsewhere, &first.encoder).unwrap();
|
||||
assert!(r.prepare(&fake).is_err());
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
//! Negative lifecycle checks for a local, cross-app cache.
|
||||
|
||||
use super::*;
|
||||
use craft_ai_core::ErrorKind;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
/// Cancellation already given must leave even the destination directory absent.
|
||||
#[test]
|
||||
fn cancel_before_start_writes_nothing() {
|
||||
let r = Rig::new();
|
||||
r.cancelled.store(true, Ordering::Release);
|
||||
let fake = Fake::default();
|
||||
assert_eq!(r.prepare(&fake).unwrap_err().kind, ErrorKind::Cancelled);
|
||||
assert!(!r.cache.exists());
|
||||
assert_eq!(fake.0.get(), 0);
|
||||
}
|
||||
|
||||
/// Conversion may finish after Cancel, but its files must never become a saved ready copy.
|
||||
#[test]
|
||||
fn cancel_during_conversion_does_not_publish_a_result() {
|
||||
let r = Rig::new();
|
||||
struct Cancel<'a>(&'a AtomicBool);
|
||||
impl Converter for Cancel<'_> {
|
||||
/// Simulates Cancel arriving during the synchronous third-party converter.
|
||||
fn convert(&self, source: &Path, output: &Path) -> Result<(), AiError> {
|
||||
Fake::default().convert(source, output)?;
|
||||
self.0.store(true, Ordering::Release);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
r.prepare(&Cancel(&r.cancelled)).unwrap_err().kind,
|
||||
ErrorKind::Cancelled
|
||||
);
|
||||
assert!(!r.cache.join(cache_key(&r.bundle)).exists());
|
||||
assert!(
|
||||
fs::read_dir(&r.cache).unwrap().all(|e| e
|
||||
.unwrap()
|
||||
.path()
|
||||
.extension()
|
||||
.is_some_and(|x| x == "lock"))
|
||||
);
|
||||
}
|
||||
|
||||
/// Two apps cannot convert the same identity at the same time.
|
||||
#[test]
|
||||
fn another_apps_conversion_lock_is_respected() {
|
||||
let r = Rig::new();
|
||||
fs::create_dir(&r.cache).unwrap();
|
||||
let lock = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.write(true)
|
||||
.open(r.cache.join(format!("{}.lock", cache_key(&r.bundle))))
|
||||
.unwrap();
|
||||
lock.try_lock().unwrap();
|
||||
let fake = Fake::default();
|
||||
let error = r.prepare(&fake).unwrap_err();
|
||||
assert!(error.message.contains("Another app"), "{error:?}");
|
||||
assert_eq!(fake.0.get(), 0);
|
||||
drop(lock);
|
||||
assert_eq!(
|
||||
r.prepare(&fake).unwrap().preparation,
|
||||
Preparation::Converted
|
||||
);
|
||||
}
|
||||
|
||||
/// Generated source is not something to compile or retain on the person's machine.
|
||||
#[test]
|
||||
fn only_weights_and_the_manifest_are_kept() {
|
||||
let r = Rig::new();
|
||||
struct Extra;
|
||||
impl Converter for Extra {
|
||||
/// A converter can emit source as well, but it is a temporary by-product only.
|
||||
fn convert(&self, source: &Path, output: &Path) -> Result<(), AiError> {
|
||||
Fake::default().convert(source, output)?;
|
||||
fs::write(output.join("encoder.rs"), b"not compiled").unwrap();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
let weights = r.prepare(&Extra).unwrap();
|
||||
let mut names: Vec<_> = fs::read_dir(weights.encoder.parent().unwrap())
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["decoder.bpk", "encoder.bpk", "manifest.json"]);
|
||||
}
|
||||
|
||||
/// A third-party converter panic is reported, not propagated into a host app.
|
||||
#[test]
|
||||
fn a_converter_panic_leaves_no_ready_copy() {
|
||||
let r = Rig::new();
|
||||
struct Crashes;
|
||||
impl Converter for Crashes {
|
||||
/// Simulates a dependency that panics instead of returning a result.
|
||||
fn convert(&self, _: &Path, _: &Path) -> Result<(), AiError> {
|
||||
panic!("converter failed");
|
||||
}
|
||||
}
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| r.prepare(&Crashes)));
|
||||
assert!(result.is_ok(), "the dependency panic escaped");
|
||||
let error = result.unwrap().unwrap_err();
|
||||
assert!(error.message.contains("prepare"));
|
||||
assert!(!r.cache.join(cache_key(&r.bundle)).exists());
|
||||
}
|
||||
|
||||
/// An empty component cannot be published even when the converter reports success.
|
||||
#[test]
|
||||
fn empty_converted_weights_are_refused() {
|
||||
let r = Rig::new();
|
||||
struct Empty;
|
||||
impl Converter for Empty {
|
||||
/// A successful return with an empty file is not a successful conversion.
|
||||
fn convert(&self, source: &Path, output: &Path) -> Result<(), AiError> {
|
||||
Fake::default().convert(source, output)?;
|
||||
fs::write(output.join("encoder.bpk"), b"").unwrap();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
assert!(r.prepare(&Empty).is_err());
|
||||
assert!(!r.cache.join(cache_key(&r.bundle)).exists());
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
//! Tiny fake conversions prove cache behaviour, never real model execution.
|
||||
|
||||
use super::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::cell::Cell;
|
||||
use std::fs;
|
||||
use tempfile::TempDir;
|
||||
|
||||
/// A converter whose call count distinguishes a fresh conversion from reuse.
|
||||
#[derive(Default)]
|
||||
struct Fake(Cell<usize>);
|
||||
|
||||
impl Converter for Fake {
|
||||
/// Writes tiny distinguishable weights to the same output shape as the actual converter.
|
||||
fn convert(&self, source: &Path, output: &Path) -> Result<(), AiError> {
|
||||
self.0.set(self.0.get() + 1);
|
||||
assert_eq!(fs::read(source.join("encoder.onnx")).unwrap(), b"encoder");
|
||||
assert_eq!(fs::read(source.join("decoder.onnx")).unwrap(), b"decoder");
|
||||
fs::write(output.join("encoder.bpk"), b"encoder weights").unwrap();
|
||||
fs::write(output.join("decoder.bpk"), b"decoder weights").unwrap();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A supported test bundle and original files, separate from the cache folder.
|
||||
struct Rig {
|
||||
_dir: TempDir,
|
||||
source: PathBuf,
|
||||
cache: PathBuf,
|
||||
bundle: Bundle,
|
||||
cancelled: AtomicBool,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
/// Builds small source files and freezes their actual hashes.
|
||||
fn new() -> Self {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let source = dir.path().join("originals");
|
||||
fs::create_dir(&source).unwrap();
|
||||
let files = ["encoder", "decoder"].map(|name| {
|
||||
let bytes = name.as_bytes();
|
||||
let filename = format!("{name}.onnx");
|
||||
fs::write(source.join(&filename), bytes).unwrap();
|
||||
SourceFile {
|
||||
name: filename,
|
||||
size: bytes.len() as u64,
|
||||
sha256: Sha256::digest(bytes)
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect(),
|
||||
}
|
||||
});
|
||||
Self {
|
||||
cache: dir.path().join("cache"),
|
||||
_dir: dir,
|
||||
source,
|
||||
bundle: Bundle {
|
||||
revision: "test-v1".into(),
|
||||
files,
|
||||
},
|
||||
cancelled: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the production cache lifecycle with the supplied tiny converter.
|
||||
fn prepare(&self, converter: &dyn Converter) -> Result<PreparedWeights, AiError> {
|
||||
prepare(
|
||||
&self.bundle,
|
||||
&self.source,
|
||||
&self.cache,
|
||||
&self.cancelled,
|
||||
converter,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// An original file with the wrong bytes must be refused before conversion.
|
||||
#[test]
|
||||
fn a_source_hash_mismatch_never_reaches_the_converter() {
|
||||
let mut r = Rig::new();
|
||||
r.bundle.files[0].sha256 = "0".repeat(64);
|
||||
let fake = Fake::default();
|
||||
let error = r.prepare(&fake).unwrap_err();
|
||||
assert!(error.message.contains("original model files"), "{error:?}");
|
||||
assert_eq!(fake.0.get(), 0);
|
||||
}
|
||||
|
||||
/// A saved file changed without changing its size must not be reused.
|
||||
#[test]
|
||||
fn damaged_saved_weights_are_refused_without_overwriting_them() {
|
||||
let r = Rig::new();
|
||||
let fake = Fake::default();
|
||||
let first = r.prepare(&fake).unwrap();
|
||||
fs::write(&first.encoder, b"Encoder weights").unwrap();
|
||||
let error = r.prepare(&fake).unwrap_err();
|
||||
assert!(error.message.contains("saved model files"));
|
||||
assert_eq!(fake.0.get(), 1);
|
||||
assert_eq!(fs::read(first.encoder).unwrap(), b"Encoder weights");
|
||||
}
|
||||
|
||||
/// A published directory that has lost a component is not ready.
|
||||
#[test]
|
||||
fn a_missing_saved_decoder_is_not_a_complete_conversion() {
|
||||
let r = Rig::new();
|
||||
let fake = Fake::default();
|
||||
let first = r.prepare(&fake).unwrap();
|
||||
fs::remove_file(first.decoder).unwrap();
|
||||
assert!(r.prepare(&fake).is_err());
|
||||
assert_eq!(fake.0.get(), 1);
|
||||
}
|
||||
|
||||
/// Preparing once saves checked weights and the second request reuses them without converting.
|
||||
#[test]
|
||||
fn choosing_burn_again_reuses_the_local_weights() {
|
||||
let r = Rig::new();
|
||||
let fake = Fake::default();
|
||||
let first = r.prepare(&fake).unwrap();
|
||||
assert_eq!(first.preparation, Preparation::Converted);
|
||||
assert_eq!(fs::read(&first.encoder).unwrap(), b"encoder weights");
|
||||
assert_eq!(fs::read(&first.decoder).unwrap(), b"decoder weights");
|
||||
let second = r.prepare(&fake).unwrap();
|
||||
assert_eq!(second.preparation, Preparation::Reused);
|
||||
assert_eq!(second.encoder, first.encoder);
|
||||
assert_eq!(fake.0.get(), 1);
|
||||
assert_eq!(fs::read(r.source.join("encoder.onnx")).unwrap(), b"encoder");
|
||||
assert_eq!(fs::read(r.source.join("decoder.onnx")).unwrap(), b"decoder");
|
||||
}
|
||||
|
||||
/// A run that was killed leaves its scratch folders behind. The next preparation of the same files
|
||||
/// removes them, and leaves alone the scratch folders of any other cache key and any other folder
|
||||
/// that merely starts with this key (a damaged copy a person renamed to `<key>.backup`).
|
||||
#[test]
|
||||
fn leftovers_of_a_killed_run_are_swept_for_this_key_only() {
|
||||
let r = Rig::new();
|
||||
let key = cache_key(&r.bundle);
|
||||
fs::create_dir_all(&r.cache).unwrap();
|
||||
let mine = r.cache.join(format!("{key}.work.killed"));
|
||||
let other = r
|
||||
.cache
|
||||
.join(format!("{}.work.killed", "f".repeat(key.len())));
|
||||
for dir in [&mine, &other] {
|
||||
fs::create_dir(dir).unwrap();
|
||||
fs::write(dir.join("encoder.onnx"), b"leftover").unwrap();
|
||||
}
|
||||
let backup = r.cache.join(format!("{key}.backup"));
|
||||
fs::create_dir(&backup).unwrap();
|
||||
fs::write(backup.join("encoder.bpk"), b"kept").unwrap();
|
||||
r.prepare(&Fake::default()).unwrap();
|
||||
assert!(!mine.exists(), "this key's leftovers are removed");
|
||||
assert!(backup.exists(), "a renamed copy is not scratch");
|
||||
assert!(
|
||||
other.exists(),
|
||||
"another key's leftovers are not ours to remove"
|
||||
);
|
||||
}
|
||||
|
||||
#[path = "boundaries.rs"]
|
||||
mod boundaries;
|
||||
#[path = "safety.rs"]
|
||||
mod safety;
|
||||
@@ -0,0 +1,18 @@
|
||||
//! One-time, local preparation of supported Burn weights.
|
||||
//!
|
||||
//! The host calls this only after the person chooses this engine and approves setup. Original
|
||||
//! model files stay untouched. Converted weights belong in the shared model cache, not an app
|
||||
//! install. This is weight preparation for a model whose Rust architecture ships in the app,
|
||||
//! not a loader for arbitrary ONNX graphs and not proof that an app can execute the model.
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
#[cfg(any(test, feature = "conversion"))]
|
||||
mod cache;
|
||||
#[cfg(feature = "conversion")]
|
||||
mod sam21;
|
||||
|
||||
#[cfg(any(test, feature = "conversion"))]
|
||||
pub use cache::{Preparation, PreparedWeights};
|
||||
#[cfg(feature = "conversion")]
|
||||
pub use sam21::prepare_sam21;
|
||||
@@ -0,0 +1,131 @@
|
||||
//! The exact supported SAM 2.1 tiny export. A different graph needs a compiled architecture too.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use crate::cache::{self, Bundle, Converter, PreparedWeights, SourceFile};
|
||||
use craft_ai_core::AiError;
|
||||
|
||||
/// Bump when the compiled architecture, tensor mapping or converter changes.
|
||||
const REVISION: &str = "sam21-tiny-burn-0.22.1-onnx-0.22.0-v1";
|
||||
|
||||
/// Only these reviewed source bytes can be converted for the shipped architecture.
|
||||
fn bundle() -> Bundle {
|
||||
let source = |name: &str, size, sha256: &str| SourceFile {
|
||||
name: name.into(),
|
||||
size,
|
||||
sha256: sha256.into(),
|
||||
};
|
||||
Bundle {
|
||||
revision: REVISION.into(),
|
||||
files: [
|
||||
source(
|
||||
"encoder.onnx",
|
||||
109_473_919,
|
||||
"4fda6e68561e27808cedffa8689749a622bba5f11ba66f4ca4e3a8a9f6360db5",
|
||||
),
|
||||
source(
|
||||
"decoder.onnx",
|
||||
20_655_795,
|
||||
"0ae944e08e55814c19afa4d143ef07b1a3dbad2decd77c15ec3ab220b9f57247",
|
||||
),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepares SAM 2.1 tiny weights once, or checks and reuses its saved conversion.
|
||||
///
|
||||
/// Call on a worker only after the person explicitly chooses this engine and approves setup.
|
||||
/// `source` holds the two publisher ONNX files. `cache` is a host-selected, shared, app-owned
|
||||
/// model-cache folder, never the source folder. Nothing is downloaded, compiled or registered.
|
||||
/// The synchronous converter cannot be interrupted mid-component: Cancel discards its result
|
||||
/// when it returns. This does not make arbitrary ONNX graphs executable in Burn.
|
||||
pub fn prepare_sam21(
|
||||
source: &Path,
|
||||
cache: &Path,
|
||||
cancelled: &AtomicBool,
|
||||
) -> Result<PreparedWeights, AiError> {
|
||||
cache::prepare(
|
||||
&bundle(),
|
||||
source,
|
||||
cache,
|
||||
cancelled,
|
||||
&OnnxConverter(cancelled),
|
||||
)
|
||||
}
|
||||
|
||||
/// Uses a bundled library, not Cargo, rustc, rustfmt, Python or a separate installed converter.
|
||||
struct OnnxConverter<'a>(&'a AtomicBool);
|
||||
|
||||
impl Converter for OnnxConverter<'_> {
|
||||
/// Converts only the already-checked private copy of the known source files.
|
||||
fn convert(&self, source: &Path, output: &Path) -> Result<(), AiError> {
|
||||
for name in ["encoder.onnx", "decoder.onnx"] {
|
||||
cache::check_cancelled(self.0)?;
|
||||
let input = source.join(name);
|
||||
let input = input.to_str().ok_or_else(|| {
|
||||
AiError::unsupported(
|
||||
"Choose a model folder whose name uses standard text characters.",
|
||||
)
|
||||
})?;
|
||||
let output = output.to_str().ok_or_else(|| {
|
||||
AiError::unsupported(
|
||||
"Choose a saved-model folder whose name uses standard text characters.",
|
||||
)
|
||||
})?;
|
||||
burn_onnx::ModelGen::new()
|
||||
.input(input)
|
||||
.out_dir(output)
|
||||
.run_from_cli();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Preparation;
|
||||
|
||||
/// The starter download and compiled architecture must agree on the exact original files.
|
||||
#[test]
|
||||
fn the_supported_source_bytes_match_the_catalogue() {
|
||||
let feature = craft_ai_features::builtin()
|
||||
.into_iter()
|
||||
.find(|f| f.id == "select-subject")
|
||||
.unwrap();
|
||||
let route = feature
|
||||
.engine_recipe("rten")
|
||||
.unwrap()
|
||||
.native
|
||||
.iter()
|
||||
.find(|r| r.provider == "rten")
|
||||
.unwrap();
|
||||
for expected in bundle().files {
|
||||
let offered = route
|
||||
.models
|
||||
.iter()
|
||||
.find(|f| f.filename == expected.name)
|
||||
.unwrap();
|
||||
assert_eq!(offered.sha256, expected.sha256);
|
||||
assert_eq!(offered.size_bytes, expected.size);
|
||||
}
|
||||
}
|
||||
|
||||
/// Real conversion followed by verified reuse, using existing checked model files only.
|
||||
#[test]
|
||||
#[ignore = "requires CRAFT_TEST_SAM21_ONNX_DIR pointing at the two original files"]
|
||||
fn the_real_model_is_prepared_once_and_reused() {
|
||||
let source =
|
||||
std::env::var_os("CRAFT_TEST_SAM21_ONNX_DIR").expect("set the original file folder");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cancelled = AtomicBool::new(false);
|
||||
let first = prepare_sam21(Path::new(&source), dir.path(), &cancelled).unwrap();
|
||||
assert_eq!(first.preparation, Preparation::Converted);
|
||||
assert!(std::fs::metadata(&first.encoder).unwrap().len() > 100_000_000);
|
||||
assert!(std::fs::metadata(&first.decoder).unwrap().len() > 10_000_000);
|
||||
let second = prepare_sam21(Path::new(&source), dir.path(), &cancelled).unwrap();
|
||||
assert_eq!(second.preparation, Preparation::Reused);
|
||||
assert_eq!(first.encoder, second.encoder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
# Local Burn weight preparation
|
||||
|
||||
The person chooses the graphics-card engine. Setup prepares its model weights once on this
|
||||
computer, saves them in the shared model cache, and reuses that copy in every app. We do not host
|
||||
converted weights. The original publisher files stay unchanged and remain usable by rten.
|
||||
|
||||
`craft-ai-burn-setup`, feature `conversion`, implements the local preparation step for the exact
|
||||
SAM 2.1 tiny export already pinned in the catalogue. It does not yet register a Burn runner or add
|
||||
a Burn option to the starter recipe. It never downloads a model or changes a connection or binding.
|
||||
|
||||
## What ships, and what happens locally
|
||||
|
||||
A Burn model has two parts:
|
||||
|
||||
1. Its Rust architecture is generated, reviewed and compiled by us when building the engine.
|
||||
2. The person's original ONNX files are converted to `.bpk` weights on their machine, on demand.
|
||||
|
||||
The converter is the bundled `burn-onnx` library. It needs no Cargo, Rust compiler, rustfmt,
|
||||
Python, installed converter, service, or network call when it runs. Source emitted as a conversion
|
||||
by-product is discarded, not compiled locally. This supports an architecture shipped with the
|
||||
engine. It does not let Burn run an arbitrary ONNX graph. A different architecture still needs a
|
||||
new runner, or an engine such as rten that loads ONNX graphs directly.
|
||||
|
||||
The matching compiled production Burn runner remains to be built. The existing spike contains
|
||||
the compiled model used for the real local weight proof. Its five code-generation corrections
|
||||
still need reproducible generation and splitting into small source files before engine delivery.
|
||||
|
||||
## Host API
|
||||
|
||||
```rust,ignore
|
||||
// On a worker, only after the person chooses this engine and approves setup.
|
||||
let weights = craft_ai_burn_setup::prepare_sam21(
|
||||
original_model_folder,
|
||||
shared_burn_cache_folder,
|
||||
&cancelled,
|
||||
)?;
|
||||
// weights.encoder and weights.decoder identify the complete saved copy.
|
||||
// Bind only after the host's separate, explicit Use action and executable-runner checks.
|
||||
```
|
||||
|
||||
The cache folder is chosen by the host. It must be outside the original-model folder. Put it in
|
||||
the shared model area, not an app installation, so other Craft apps reuse it. This slice does not
|
||||
choose a new global folder policy or migrate existing data.
|
||||
|
||||
## Rules
|
||||
|
||||
- Only the exact source sizes and SHA-256 hashes supported by the compiled architecture enter
|
||||
conversion. Private copies prevent source edits during conversion from changing its input.
|
||||
- The cache key includes source identity and the converter/architecture revision. Bump the
|
||||
revision whenever the architecture, tensor mapping, or converter changes.
|
||||
- A cross-process file lock prevents two apps preparing the same copy together.
|
||||
- Only two nonempty, bounded weight files and a bounded manifest are published. Temporary source,
|
||||
generated code and failed conversions are cleaned up. If the app is killed in the middle, the next preparation of the same files removes the scratch folders it left (they carry the cache key in their name), and never touches another key's. A final directory appears only after both
|
||||
files and the manifest are complete and flushed.
|
||||
- Reuse checks both saved file hashes. These checks detect changed files, not hostile replacement
|
||||
of both a manifest and weights by another process with the same account permissions.
|
||||
- Damaged saved files are refused, not overwritten or silently repaired. The host can offer an
|
||||
explicit removal/rebuild of that derived copy. Originals are never removed or repaired.
|
||||
- Cancel before starting writes nothing. Cancel during a synchronous converter call takes effect
|
||||
when that component finishes, and its late result is discarded. Do not promise immediate Cancel.
|
||||
- Preparation is not inference, readiness in an app, or permission to bind. Host UI and the generic
|
||||
engine registration remain separate work.
|
||||
|
||||
## Exercise it
|
||||
|
||||
```sh
|
||||
cargo test -p craft-ai-burn-setup --features conversion -j 8
|
||||
cargo clippy -p craft-ai-burn-setup --features conversion --all-targets -j 8 -- -D warnings
|
||||
cargo run -p craft-ai-burn-setup --features conversion --example prepare_sam21 -- <original-folder> <cache-folder>
|
||||
# Repeat: preparation is Reused, with the same two paths.
|
||||
# Real conversion test, only with the existing publisher files:
|
||||
# Set CRAFT_TEST_SAM21_ONNX_DIR, then:
|
||||
cargo test -p craft-ai-burn-setup --features conversion -j 8 -- --ignored
|
||||
python tools/mutation/mutation_check.py bp
|
||||
```
|
||||
|
||||
Evidence on Windows, 21/10/2026: real files converted and then reused by a standalone executable
|
||||
with PATH empty and developer-tool locations absent. The saved weights ran through the existing
|
||||
release Burn/wgpu spike and produced best-mask IoU 1.0 against the stored ONNX Runtime reference
|
||||
for one image and one click. This is a model/weight proof, not an app, launcher, other-OS, or
|
||||
production-engine integration test. Timing from the debug setup probe is not a release benchmark.
|
||||
@@ -0,0 +1,56 @@
|
||||
"""bp: local Burn weight preparation, with tiny fake conversions only.
|
||||
|
||||
The real converter and tensor parity need the ignored live test and the standalone probe.
|
||||
The dependency cannot cancel mid-component; the cache must discard a late answer instead.
|
||||
Case shape: name, file, old, new, package, target, test filter.
|
||||
"""
|
||||
FILE = 'crates/ai-burn-setup/src/cache.rs'
|
||||
PACKAGE = 'craft-ai-burn-setup'
|
||||
|
||||
|
||||
def case(name, old, new, test):
|
||||
"""Keep the common crate and unit-test target explicit in every resolved case."""
|
||||
return name, FILE, old, new, PACKAGE, 'lib', test
|
||||
|
||||
|
||||
BP = [
|
||||
case('burn-source-hash-unchecked',
|
||||
'copied != file.size || hash_file(&snapshot)? != file.sha256',
|
||||
'copied != file.size', 'a_source_hash_mismatch'),
|
||||
case('burn-source-size-unchecked',
|
||||
'copied != file.size || hash_file(&snapshot)? != file.sha256',
|
||||
'hash_file(&snapshot)? != file.sha256', 'a_wrong_source_size'),
|
||||
case('burn-saved-hash-unchecked',
|
||||
'if hash_file(&final_dir.join(name))? != *expected {',
|
||||
'if false {', 'damaged_saved_weights'),
|
||||
case('burn-converter-revision-forgotten',
|
||||
'digest.update(bundle.revision.as_bytes());',
|
||||
'', 'a_new_converter_revision'),
|
||||
case('burn-source-identity-forgotten',
|
||||
'digest.update(file.sha256.as_bytes());',
|
||||
'', 'a_new_expected_source'),
|
||||
case('burn-cancel-ignored',
|
||||
'if cancelled.load(Ordering::Acquire) {',
|
||||
'if false {', 'cancel_'),
|
||||
case('burn-empty-weights-accepted',
|
||||
'if size == 0 || size > 512 * 1024 * 1024 {',
|
||||
'if size > 512 * 1024 * 1024 {', 'empty_converted_weights'),
|
||||
case('burn-manifest-cap-ignored',
|
||||
'if bytes.len() > 4096 {',
|
||||
'if false {', 'an_oversized_manifest'),
|
||||
case('burn-source-folder-used-as-cache',
|
||||
'&& destination(cache)?.starts_with(original)',
|
||||
'&& false', 'the_original_folder_cannot'),
|
||||
case('burn-second-conversion-not-locked',
|
||||
'lock.try_lock().map_err(|_| {',
|
||||
'Ok::<(), std::io::Error>(()).map_err(|_| {', 'another_apps_conversion_lock'),
|
||||
case('burn-killed-run-leftovers-kept',
|
||||
' sweep_stale(cache, &key);\n',
|
||||
'', 'leftovers_of_a_killed_run'),
|
||||
case('burn-sweep-takes-other-keys',
|
||||
'.is_some_and(|n| prefixes.iter().any(|p| n.starts_with(p.as_str())));',
|
||||
'.is_some_and(|n| n.contains(".work."));', 'leftovers_of_a_killed_run'),
|
||||
case('burn-sweep-takes-a-renamed-copy',
|
||||
'SCRATCH_ROLES.map(|role| format!("{key}.{role}."));',
|
||||
'SCRATCH_ROLES.map(|_| format!("{key}."));', 'leftovers_of_a_killed_run'),
|
||||
]
|
||||
@@ -487,6 +487,7 @@ from mutation_generic import GS_CASES # noqa: E402
|
||||
from mutation_generic_mask import GM_CASES # noqa: E402
|
||||
from mutation_generic_uploads import GU_CASES # noqa: E402
|
||||
from mutation_segment import SEG_CASES # noqa: E402
|
||||
from mutation_burn_preparation import BP # noqa: E402
|
||||
|
||||
PS_RS = C + 'ai-comfy-env/src/source/pack/status.rs'
|
||||
PS = [
|
||||
@@ -548,7 +549,7 @@ S21 = [
|
||||
('selections-share-a-sink-name', SAM21, 'NEXT_SELECTION.fetch_add(1, Ordering::Relaxed)', '0', CU, 'sam21_session', 'its_own_sink_name'),
|
||||
]
|
||||
|
||||
GROUPS = {'rt': RTEN_CASES, 'gu': GU_CASES, 'gm': GM_CASES, 'gs': GS_CASES, 'seg': SEG_CASES, 'nw': NW, 'nq': NQ, 'ns': NS, 'nf': NF, 'ce': CE, 'cg': CG, 'sf': SF, 's21': S21, 'ca': CA, 'lg': LG, 'ps': PS, 'ct': CT, 'u2': U2, 'nr': NR, 'u1': U1, 'u3': U3, 'u4': U4, 'p4': P4, 'p10': P10, 'v1': V1, 'v2': V2, 'v3': V3, 'sd': SD, 'vx': VX, 'lc': LC, 'lr': LR, 'wf': WF}
|
||||
GROUPS = {'bp': BP, 'rt': RTEN_CASES, 'gu': GU_CASES, 'gm': GM_CASES, 'gs': GS_CASES, 'seg': SEG_CASES, 'nw': NW, 'nq': NQ, 'ns': NS, 'nf': NF, 'ce': CE, 'cg': CG, 'sf': SF, 's21': S21, 'ca': CA, 'lg': LG, 'ps': PS, 'ct': CT, 'u2': U2, 'nr': NR, 'u1': U1, 'u3': U3, 'u4': U4, 'p4': P4, 'p10': P10, 'v1': V1, 'v2': V2, 'v3': V3, 'sd': SD, 'vx': VX, 'lc': LC, 'lr': LR, 'wf': WF}
|
||||
# Mutants whose effect is also refused by a second, independent check on this machine. They are
|
||||
# recorded as equivalent here, with the reason, and are never counted as caught.
|
||||
EQUIVALENT = {
|
||||
|
||||
Reference in new issue
Block a user