Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

perf(enhance): CoreML on the GPU on Apple machines - 1.8 s a 1080p frame - and a log line saying where each frame's time goes

Jareer84c0e625e0e1
diff --git a/src/crates/concat-host/src/enhance.rs b/src/crates/concat-host/src/enhance.rs
index dfcdfa16..be51d061 100644
--- a/src/crates/concat-host/src/enhance.rs
+++ b/src/crates/concat-host/src/enhance.rs
@@ -237,7 +237,7 @@ impl Enhancers {
if !self.installed() {
crate::cutout::fetch(ModelId::Enhance, &file, cancel, progress)?;
}
- let enhancer = Arc::new(on_gpu(&file).map_or_else(|| Enhancer::load(&file), Ok)?);
+ let enhancer = Arc::new(fastest(&file)?);
*self.model.lock().map_err(|_| "model slot poisoned")? = Some(Arc::clone(&enhancer));
Ok(enhancer)
}
@@ -404,24 +404,43 @@ fn footage(
.map_err(|error| error.to_string())?;
let encoded = (|| {
let mut count = 0u64;
+ // Where the time went, said once at the end: the model is nine
+ // tenths of it on a Mac, and the rest is what overlapping the
+ // stages could win back.
+ let mut t = [std::time::Duration::ZERO; 4];
+ let mut at = std::time::Instant::now();
+ let mut lap = |slot: usize, t: &mut [std::time::Duration; 4]| {
+ let now = std::time::Instant::now();
+ t[slot] += now - at;
+ at = now;
+ };
while let Some(frame) = decoder.next_frame().map_err(|error| error.to_string())? {
+ lap(0, &mut t);
if job.cancelled() {
return Err("enhance cancelled".to_owned());
}
- let enhanced = vision::mix(
- enhancer.enhance(&frame, request.factor)?,
- &frame,
- request.strength,
- );
+ let model = enhancer.enhance(&frame, request.factor)?;
+ lap(1, &mut t);
+ let enhanced = vision::mix(model, &frame, request.strength);
+ lap(2, &mut t);
let enhanced = crop(&enhanced, width, height);
encoder
.write_frame(&enhanced)
.map_err(|error| error.to_string())?;
+ lap(3, &mut t);
count += 1;
progress(Progress::Analysing(
(count as f64 / expected).min(0.99) as f32
));
}
+ let per = |d: std::time::Duration| d.as_secs_f64() / count.max(1) as f64;
+ log::info!(
+ "enhance: {count} frames, a frame: decode {:.3}s, model {:.3}s, mix {:.3}s, encode {:.3}s",
+ per(t[0]),
+ per(t[1]),
+ per(t[2]),
+ per(t[3])
+ );
encoder.finish().map_err(|error| error.to_string())
})();
// Windows will not rename or delete a file something still holds open,
@@ -471,6 +490,28 @@ pub(crate) fn crop(frame: &concat_core::Frame, width: u32, height: u32) -> conca
out
}
+/// The model on the fastest thing this machine has. On Apple's, CoreML
+/// with the network's shape fixed, which runs it on the GPU through
+/// Apple's own kernels: 1.8 s a 1080p frame on an M5, where our shaders
+/// take 4.2. Everywhere else our shaders on the GPU (Windows' ONNX Runtime
+/// has no GPU provider at all), and ONNX Runtime on the CPU only when no
+/// GPU opens.
+fn fastest(file: &Path) -> Result<Enhancer, String> {
+ if cfg!(target_vendor = "apple") {
+ match Enhancer::load(file) {
+ Ok(enhancer) => {
+ log::info!("enhance: through CoreML");
+ return Ok(enhancer);
+ }
+ Err(error) => log::warn!("enhance: CoreML would not load it: {error}"),
+ }
+ }
+ match on_gpu(file) {
+ Some(enhancer) => Ok(enhancer),
+ None => Enhancer::load(file),
+ }
+}
+
/// The model on the GPU, in compute shaders of our own
/// (`concat_render::upscale`), when its file reads as the compact network
/// and a GPU opens: about six times what ONNX Runtime does on this
@@ -519,7 +560,46 @@ impl vision::WindowRunner for GpuWindows {
mod tests {
use super::*;
- /// The model on the GPU and through ONNX Runtime give the same picture,
+ /// Times the stages of a real run, by hand.
+ #[test]
+ #[ignore = "a probe"]
+ fn enhance_stage_timing() {
+ let dir = std::env::temp_dir().join("concat-enhance-timing");
+ let _ = std::fs::create_dir_all(&dir);
+ let clip = dir.join("clip.mp4");
+ let made = std::process::Command::new("ffmpeg")
+ .args(["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc2=size=1920x1080:rate=30:duration=1"])
+ .args(["-c:v", "libx264", "-pix_fmt", "yuv420p"])
+ .arg(&clip)
+ .status();
+ if !made.is_ok_and(|s| s.success()) {
+ return;
+ }
+ let data = ["org.standalones.concat", "app.concat.editor"]
+ .iter()
+ .filter_map(|id| {
+ let p = PathBuf::from(std::env::var_os("HOME")?).join("Library/Application Support").join(id);
+ p.join("cutout-models/realesr-general-x4v3.onnx").is_file().then_some(p)
+ })
+ .next()
+ .expect("the model");
+ let enhancers = Enhancers::new(&data);
+ let target = dir.join("out.mp4");
+ let _ = std::fs::remove_file(&target);
+ let request = EnhanceRequest {
+ media_path: clip.to_string_lossy().into_owned(),
+ still: false,
+ factor: 2,
+ strength: 0.8,
+ target,
+ };
+ let started = std::time::Instant::now();
+ enhancers.enhance(&request, &mut |_| {}).expect("enhances");
+ eprintln!("whole run: {:?}", started.elapsed());
+ }
+
+ /// The model on our shaders and through ONNX Runtime - CoreML on a Mac,
+ /// the CPU elsewhere - give the same picture,
/// tiles, margins and pasting included: a few levels at the worst pixel
/// and well under one on average, the
/// GPU working in half floats. Needs the fetched model and a GPU.
diff --git a/src/crates/concat-render/src/upscale.rs b/src/crates/concat-render/src/upscale.rs
index 5665102f..542d841c 100644
--- a/src/crates/concat-render/src/upscale.rs
+++ b/src/crates/concat-render/src/upscale.rs
@@ -168,17 +168,29 @@ fn conv_shader_for(bw: u32, bh: u32) -> String {
}
}
for g in 0..4u32 {
+ // A group's nine taps summed in the stored type, then carried into
+ // the f32 sum: one conversion a group rather than one a product,
+ // and only 36 terms ever added at sixteen bits. One tap's matrix is
+ // read and spent on every pixel of the block before the next is
+ // read, so a single matrix is ever held in registers: holding all
+ // nine at once, with the neighbourhood and the sums, was past what
+ // a thread has, and spilled.
+ for p in 0..pixels.len() {
+ code += &format!(" var s{p}_{g} = vec4<T>(0.0);\n");
+ }
for tap in 0..9u32 {
- code += &format!(" let m{g}_{tap} = taps[{}u];\n", g * 9 + tap);
+ code += &format!(" {{\n let m = taps[{}u];\n", g * 9 + tap);
+ for (p, (dy, dx)) in pixels.iter().enumerate() {
+ code += &format!(
+ " s{p}_{g} += m * n{}_{};\n",
+ tap / 3 + dy,
+ tap % 3 + dx
+ );
+ }
+ code += " }\n";
}
- // A group's nine taps summed in the stored type, then the partial
- // carried into the f32 sum: one conversion a group rather than one
- // a product, and only 36 terms ever added at sixteen bits.
- for (p, (dy, dx)) in pixels.iter().enumerate() {
- let terms: Vec<String> = (0..9u32)
- .map(|tap| format!("m{g}_{tap} * n{}_{}", tap / 3 + dy, tap % 3 + dx))
- .collect();
- code += &format!(" a{p}_{g} += vec4<f32>({});\n", terms.join(" + "));
+ for p in 0..pixels.len() {
+ code += &format!(" a{p}_{g} += vec4<f32>(s{p}_{g});\n");
}
}
code += " }\n";
diff --git a/src/crates/concat-vision/src/compact.rs b/src/crates/concat-vision/src/compact.rs
index 425e537f..a51cfd11 100644
--- a/src/crates/concat-vision/src/compact.rs
+++ b/src/crates/concat-vision/src/compact.rs
@@ -390,6 +390,12 @@ fn text(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).into_owned()
}
+/// What the tests of this crate share.
+#[cfg(test)]
+pub(crate) mod tests_support {
+ pub(crate) use super::tests::fetched_model;
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/crates/concat-vision/src/enhance.rs b/src/crates/concat-vision/src/enhance.rs
index 59033c9e..898f66ae 100644
--- a/src/crates/concat-vision/src/enhance.rs
+++ b/src/crates/concat-vision/src/enhance.rs
@@ -387,8 +387,9 @@ impl Enhancer {
/// [`crate::models::ModelId::Enhance`].
#[cfg(feature = "infer")]
pub fn load(file: &std::path::Path) -> Result<Enhancer, String> {
+ let side = i64::from(WINDOW);
Ok(Enhancer::with(Box::new(Runtime(
- crate::runtime::Model::from_file(file)?,
+ crate::runtime::Model::from_file_fixed(file, &[("height", side), ("width", side)])?,
))))
}
@@ -722,3 +723,64 @@ mod tests {
assert_eq!(half.pixel(0, 0), Some([150, 100, 128, 255]));
}
}
+
+/// A probe, run by hand: the model through CoreML as Apple's newer
+/// MLProgram, its shape fixed so the Neural Engine can take it, timed a
+/// window at a time against what the GPU upscaler does.
+#[cfg(all(test, feature = "infer", target_vendor = "apple"))]
+mod coreml_probe {
+ use ort::ep::coreml::{ComputeUnits, ModelFormat, SpecializationStrategy};
+
+ #[test]
+ #[ignore = "a probe; needs the fetched model"]
+ fn coreml_on_the_neural_engine() {
+ let Some(file) = crate::compact::tests_support::fetched_model() else {
+ eprintln!("no model here");
+ return;
+ };
+ for (units, side) in [
+ (ComputeUnits::CPUAndGPU, 288usize),
+ (ComputeUnits::CPUAndGPU, 544),
+ (ComputeUnits::CPUAndGPU, 1056),
+ (ComputeUnits::All, 544),
+ ] {
+ let ep = ort::ep::CoreML::default()
+ .with_model_format(ModelFormat::MLProgram)
+ .with_static_input_shapes(true)
+ .with_specialization_strategy(SpecializationStrategy::FastPrediction)
+ .with_compute_units(units)
+ .build();
+ let mut session = ort::session::Session::builder()
+ .expect("a builder")
+ .with_dimension_override("height", side as i64)
+ .expect("height")
+ .with_dimension_override("width", side as i64)
+ .expect("width")
+ .with_execution_providers([ep])
+ .expect("coreml")
+ .commit_from_file(&file)
+ .expect("loads");
+ let planes = vec![0.5f32; 3 * side * side];
+ let input = || {
+ ort::value::Tensor::from_array(([1usize, 3, side, side], planes.clone()))
+ .expect("a tensor")
+ };
+ let started = std::time::Instant::now();
+ session.run(ort::inputs!["input" => input()]).expect("runs");
+ let first = started.elapsed();
+ let runs = 10;
+ let started = std::time::Instant::now();
+ for _ in 0..runs {
+ session.run(ort::inputs!["input" => input()]).expect("runs");
+ }
+ let each = started.elapsed().as_secs_f64() / f64::from(runs);
+ let core = (side - 32) as f64;
+ let windows = (1920.0 / core).ceil() * (1080.0 / core).ceil();
+ eprintln!(
+ "{units:?} {side}: first {first:?}, then {:.1} ms a window = {:.2} s a 1080p frame",
+ each * 1000.0,
+ each * windows
+ );
+ }
+ }
+}
diff --git a/src/crates/concat-vision/src/runtime.rs b/src/crates/concat-vision/src/runtime.rs
index 4e8fb1a1..31f22166 100644
--- a/src/crates/concat-vision/src/runtime.rs
+++ b/src/crates/concat-vision/src/runtime.rs
@@ -93,10 +93,35 @@ pub struct Model {
impl Model {
/// Loads a model from its bytes.
pub fn from_bytes(bytes: &[u8]) -> Result<Model, String> {
+ Model::build(bytes, &[], accelerators())
+ }
+
+ /// Loads a model whose input is always one size: its free dimensions
+ /// fixed by name, and on Apple's machines CoreML asked for Apple's
+ /// newer MLProgram format with the shape known up front, which is what
+ /// lets it put the whole network on the GPU. Without that it took only
+ /// what its older format could, and gave the rest to the CPU: Enhance
+ /// ran at 27 seconds a 1080p frame through it, and 1.8 like this.
+ pub fn from_file_fixed(path: &std::path::Path, dims: &[(&str, i64)]) -> Result<Model, String> {
+ let bytes = std::fs::read(path)
+ .map_err(|error| format!("could not read {}: {error}", path.display()))?;
+ Model::build(&bytes, dims, fixed_accelerators())
+ }
+
+ fn build(
+ bytes: &[u8],
+ dims: &[(&str, i64)],
+ providers: Vec<ort::ep::ExecutionProviderDispatch>,
+ ) -> Result<Model, String> {
ready()?;
let mut builder = Session::builder().map_err(|error| format!("onnx runtime: {error}"))?;
+ for (name, size) in dims {
+ builder = builder
+ .with_dimension_override(*name, *size)
+ .map_err(|error| format!("onnx runtime: {error}"))?;
+ }
builder = builder
- .with_execution_providers(accelerators())
+ .with_execution_providers(providers)
.map_err(|error| format!("onnx runtime: {error}"))?;
// Every core on one frame at a time: the models are convolutional
// and a frame fills a machine on its own.
@@ -175,6 +200,30 @@ fn platform_accelerator() -> Option<ort::ep::ExecutionProviderDispatch> {
Some(ort::ep::CoreML::default().build())
}
+/// [`accelerators`] for a model of one fixed shape; see
+/// [`Model::from_file_fixed`]. The GPU rather than the Neural Engine:
+/// measured on an M5, CoreML ran Enhance's network four times faster on
+/// the GPU than on the Neural Engine with the CPU.
+fn fixed_accelerators() -> Vec<ort::ep::ExecutionProviderDispatch> {
+ #[cfg(target_vendor = "apple")]
+ {
+ use ort::ep::coreml::{ComputeUnits, ModelFormat, SpecializationStrategy};
+ vec![
+ ort::ep::CoreML::default()
+ .with_model_format(ModelFormat::MLProgram)
+ .with_static_input_shapes(true)
+ .with_specialization_strategy(SpecializationStrategy::FastPrediction)
+ .with_compute_units(ComputeUnits::CPUAndGPU)
+ .build(),
+ ort::ep::CPU::default().build(),
+ ]
+ }
+ #[cfg(not(target_vendor = "apple"))]
+ {
+ accelerators()
+ }
+}
+
#[cfg(target_os = "android")]
fn platform_accelerator() -> Option<ort::ep::ExecutionProviderDispatch> {
Some(ort::ep::NNAPI::default().build())