-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpu_adapter.rs
More file actions
1746 lines (1672 loc) · 75.6 KB
/
Copy pathcpu_adapter.rs
File metadata and controls
1746 lines (1672 loc) · 75.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Phase 6 — CPU backend adapter.
//!
//! Sits one layer above the per-crate CPU reference implementations,
//! exposing the same `compute_srgb_u8` shape the GPU `ExecMetric`
//! already uses. The orchestrator's OOM-fallback ladder swaps a GPU
//! backend for a CPU one without changing the call site.
//!
//! ## Per-metric mapping (see `docs/CPU_BACKENDS.md`)
//!
//! | Metric | CPU reference crate | Feature flag |
//! |---------|-------------------------|----------------|
//! | Cvvdp | `cvvdp` (in-tree) | `cpu-cvvdp` |
//! | Ssim2 | `fast-ssim2` (Imazen) | `cpu-ssim2` |
//! | Dssim | `dssim-core` | `cpu-dssim` |
//! | Butter | `butteraugli` | `cpu-butter` |
//! | Zensim | `zensim` | `cpu-zensim` |
//! | Iwssim | `iwssim` (in-tree, 8g) | `cpu-iwssim` |
//!
//! Phase 8h (2026-05-27): the ssim2 row was switched from upstream
//! `ssimulacra2 0.5` to Imazen's SIMD-accelerated `fast-ssim2 0.8`.
//! Per-call scores may shift by atomic-add tolerance vs. the prior
//! implementation; the input shape is unchanged (sRGB u8 × 3-channel)
//! and the call surface (`compute` / `set_reference` / `compute_with_cached_reference`)
//! is untouched. See `docs/CPU_BACKENDS.md` for the rationale.
//!
//! Phase 8g (2026-05-27): added `iwssim` — a pure-Rust CPU port of the
//! canonical Python-IW-SSIM reference (Wang & Li 2011) with magetypes
//! SIMD on the SSIM-stats hot loops. The historical `Unavailable`
//! arm for iwssim is retained for build configurations that omit the
//! `cpu-iwssim` feature.
//!
//! ## Cached-reference semantics
//!
//! Each CPU backend has a different relationship with reference reuse:
//!
//! - **cvvdp** has a true cached-reference path (`warm_reference` +
//! `score_with_warm_ref`). Skips ~50% of the pipeline.
//! - **butteraugli** (Phase 9.Y, 2026-05-27): now wired to the
//! `ButteraugliReference::new(&[u8], …) + .compare(&[u8])` precompute
//! API. The ref-side sRGB→linear→XYB→frequency-separated→mask path
//! is built once and reused across compare calls. Replaces the prior
//! byte-stash wiring that recomputed `full` on every warm-ref call.
//! - **dssim-core** lets you `create_image(reference)` once and reuse;
//! the adapter caches the prepared `DssimImage`.
//! - **fast-ssim2** has a true cached-ref path (`Ssimulacra2Reference::new`
//! + `compare`) that skips ~50 % of the pipeline. The adapter wires it
//! up so `set_reference` + `compute_with_cached_reference` are now
//! amortised, not recompute. **Change vs. Phase 6's `ssimulacra2` 0.5
//! wiring**: that crate had no precompute API and the adapter just
//! stashed bytes for shape parity. fast-ssim2's `Ssimulacra2Reference`
//! replaces that with a true warm path.
//! - **zensim** (task #134, 2026-05-28): the `Zensim::precompute_reference`
//! + `compute_with_ref` pair is wired through `set_reference` +
//! `compute_with_cached_reference`. The reference-side sRGB → linear → XYB
//! conversion + multi-scale downscale pyramid runs once per source;
//! subsequent compare calls reuse the cached `PrecomputedReference`.
//! Measured speedup on the 7950X at 16 MP is ≈+12 % per amortized
//! warm call (3-trial median, 10-distorteds-per-ref sweep — see
//! `benchmarks/zensim_cached_ref_cpu_2026-05-28.meta`). The previous
//! wiring stashed raw bytes and re-converted them on every call —
//! `supports_cached_ref` returned `false`, so the orchestrator never
//! picked the warm dispatch. The strip warm-ref variant now
//! dispatches through `compute_with_ref_streaming_strips` so the
//! warm dispatch carries into the memory-bounded strip mode too.
//! (Note: the GPU cached_ref sweep at
//! `benchmarks/zensim_cached_ref_2026-05-22.csv` measures 38–40 % on
//! CUDA / wgpu — the GPU win is larger because it skips device
//! uploads and ref-side kernel launches across the sweep, neither of
//! which apply on the CPU path.)
//!
//! The pool's worker decides whether to dispatch through
//! `compute_with_cached_reference` based on a static feature query
//! ([`CpuAdapter::supports_cached_ref`]); backends without acceleration
//! still produce a correct score.
//!
//! ## Memory characteristics
//!
//! CPU backends use RAM, not VRAM. Resident-set growth depends on
//! image size:
//!
//! - cvvdp: ~5-7 bytes/pixel scratch (Weber pyramid + DKL planes
//! + diffmap). 4096² = ~120 MiB.
//! - butteraugli: ~30-40 bytes/pixel internal (XYB working set + blur
//! buffers). 4096² = ~600 MiB.
//! - dssim-core: ~40 bytes/pixel (multi-scale LAB pyramid).
//! 4096² = ~700 MiB.
//! - fast-ssim2: ~50 bytes/pixel (XYB + sub-band buffers; ~24 image-sized
//! f32 planes plus the downscale pyramid per `fast_ssim2::MAX_IMAGE_PIXELS`
//! docs). 4096² = ~850 MiB. fast-ssim2 caps inputs at 16384² to bound
//! the working set.
//! - zensim: ~10-15 bytes/pixel (XYB working set + per-scale features).
//! 4096² = ~250 MiB.
//!
//! Phase 6 records these as `ram_mib` cells in the capability cache via
//! the bench runner's CPU extension (see `bench::run_impl_cpu`).
#![cfg(feature = "bench")]
use zenmetrics_api::{MetricKind, MetricParams, Score};
// ---------------------------------------------------------------------------
// Public adapter type
// ---------------------------------------------------------------------------
/// CPU adapter — one per metric, per (w, h) signature.
///
/// Internal state is feature-gated per metric. Construction selects the
/// concrete CPU implementation based on `metric`; if the matching feature
/// is disabled, [`Self::new`] returns
/// [`CpuAdapterError::FeatureNotEnabled`] so the caller can advance the
/// fallback ladder.
///
/// `pub(crate)` — only the orchestrator's executor + pool create these.
pub(crate) struct CpuAdapter {
metric: MetricKind,
width: u32,
height: u32,
state: CpuAdapterState,
}
/// Per-metric internal state. Each arm holds the heap-allocated CPU
/// scorer + any cached reference state.
#[allow(clippy::large_enum_variant)]
enum CpuAdapterState {
#[cfg(feature = "cpu-cvvdp")]
Cvvdp(Box<cvvdp::Cvvdp>),
#[cfg(feature = "cpu-ssim2")]
Ssim2(Ssim2State),
#[cfg(feature = "cpu-dssim")]
Dssim(DssimState),
#[cfg(feature = "cpu-butter")]
Butter(ButterState),
#[cfg(feature = "cpu-zensim")]
Zensim(ZensimState),
#[cfg(feature = "cpu-iwssim")]
Iwssim(Box<iwssim::Iwssim>),
/// Built without ANY CPU backend feature, or built without the
/// specific feature for `metric`. The compute path returns
/// [`CpuAdapterError::FeatureNotEnabled`].
#[allow(dead_code)]
FeatureDisabled(MetricKind),
/// Reserved for any future metric whose CPU backend isn't yet
/// implemented. Phase 8g landed iwssim; this arm is currently
/// unreachable for ordinary callers but kept for symmetry.
#[allow(dead_code)]
Unavailable(MetricKind),
}
// ---------------------------------------------------------------------------
// Per-metric state structs (only compiled when the feature is on)
// ---------------------------------------------------------------------------
#[cfg(feature = "cpu-ssim2")]
struct Ssim2State {
width: usize,
height: usize,
/// Cached fast-ssim2 reference — `set_reference` builds the precomputed
/// reference data (~50 % of the SSIMULACRA2 pipeline) once; subsequent
/// `compute_with_cached_reference` calls reuse it. Phase 8h replaced
/// the prior `Option<Vec<u8>>` byte-stash (used by the ssimulacra2 0.5
/// fallback) with this true warm-state cache.
cached_ref: Option<fast_ssim2::Ssimulacra2Reference>,
}
#[cfg(feature = "cpu-dssim")]
struct DssimState {
width: usize,
height: usize,
dssim: dssim_core::Dssim,
/// dssim-core builds a multi-scale internal representation once via
/// `create_image` and reuses it across compares. Cache when
/// `set_reference` fires.
cached_ref: Option<dssim_core::DssimImage<f32>>,
}
#[cfg(feature = "cpu-butter")]
struct ButterState {
width: usize,
height: usize,
params: butteraugli::ButteraugliParams,
/// Phase 9.Y (2026-05-27): butteraugli 0.9.2 exposes a true
/// `ButteraugliReference::new(&[u8], w, h, params)` precompute API
/// with `.compare(&[u8]) -> ButteraugliResult`. The precompute path
/// runs sRGB → linear → XYB → mask + frequency-separation on the
/// reference once and reuses the result across compare calls — the
/// dist-side pipeline still runs per call, but the ref-side half
/// (≈30-50% of the per-pair work) is hoisted. Replaces the prior
/// `Option<Vec<u8>>` byte-stash that just recomputed `full` on the
/// warm path. The corresponding `supports_cached_ref()` arm is
/// flipped from `false` to `true`.
cached_ref: Option<butteraugli::ButteraugliReference>,
}
#[cfg(feature = "cpu-zensim")]
struct ZensimState {
width: usize,
height: usize,
zensim: zensim::Zensim,
/// Task #134 (2026-05-28): zensim's `Zensim::precompute_reference`
/// returns a `PrecomputedReference` that owns the multi-scale XYB
/// pyramid for the source image. We cache it here so subsequent
/// `compute_with_ref` calls can skip the sRGB → linear → XYB
/// conversion + downscale (≈+12 % per amortized warm call on the
/// 7950X at 16 MP — see `benchmarks/zensim_cached_ref_cpu_2026-05-28.meta`
/// for the measured 3-trial median). Replaces the prior
/// `Option<Vec<u8>>` byte stash that recomputed the full cold path
/// on every warm-ref call.
cached_ref: Option<zensim::PrecomputedReference>,
}
// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------
/// Adapter-level errors. Translated into the executor's
/// [`crate::executor::OrchestratorError`] at the boundary.
#[derive(Debug, Clone)]
#[allow(dead_code)] // some variants only fire when specific cpu-* features are on
pub(crate) enum CpuAdapterError {
/// Build does not include the feature for this metric's CPU
/// reference. e.g. `--features bench` without `cpu-cvvdp`.
/// Ladder advances to the next backend.
FeatureNotEnabled(MetricKind),
/// Metric has no clean CPU reference upstream (Iwssim). Documented
/// in `docs/CPU_BACKENDS.md`. Ladder advances.
Unavailable(MetricKind),
/// Construction or compute failed inside the CPU reference crate.
/// `String` carries the rendered error from the crate's own
/// `Display`. Not retryable — ladder treats this as a hard fault
/// for this backend at this size.
Failed(String),
/// Input byte length doesn't match `width × height × 3`. Validation
/// guard before passing the slice to the underlying crate (some
/// of which panic on mismatch rather than returning an error).
InvalidInputSize { expected: usize, got: usize },
}
impl std::fmt::Display for CpuAdapterError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CpuAdapterError::FeatureNotEnabled(k) => write!(
f,
"cpu adapter: feature 'cpu-{}' not enabled in this build",
k.tag()
),
CpuAdapterError::Unavailable(k) => {
write!(f, "cpu adapter: metric '{}' has no CPU reference", k.tag())
}
CpuAdapterError::Failed(msg) => write!(f, "cpu adapter: {msg}"),
CpuAdapterError::InvalidInputSize { expected, got } => write!(
f,
"cpu adapter: invalid input slice (expected {expected} bytes, got {got})"
),
}
}
}
impl std::error::Error for CpuAdapterError {}
// ---------------------------------------------------------------------------
// Construction
// ---------------------------------------------------------------------------
impl CpuAdapter {
/// Build a CPU adapter for `metric` at `width × height` with
/// `params`. Returns `Err(FeatureNotEnabled)` when the matching
/// `cpu-<metric>` feature is off in the current build.
pub fn new(
metric: MetricKind,
width: u32,
height: u32,
params: &MetricParams,
) -> Result<Self, CpuAdapterError> {
let state = match metric {
MetricKind::Cvvdp => construct_cvvdp(width, height, params),
MetricKind::Ssim2 => construct_ssim2(width, height, params),
MetricKind::Dssim => construct_dssim(width, height, params),
MetricKind::Butter => construct_butter(width, height, params),
MetricKind::Zensim => construct_zensim(width, height, params),
MetricKind::Iwssim => construct_iwssim(width, height, params),
}?;
Ok(Self {
metric,
width,
height,
state,
})
}
/// Which metric this adapter scores.
#[allow(dead_code)]
pub fn metric(&self) -> MetricKind {
self.metric
}
/// Width in pixels.
#[allow(dead_code)]
pub fn width(&self) -> u32 {
self.width
}
/// Height in pixels.
#[allow(dead_code)]
pub fn height(&self) -> u32 {
self.height
}
/// Whether this backend has a true cached-reference fast path. When
/// false, the worker pool's cached-ref dispatch still produces a
/// correct score but pays the full per-call cost.
#[allow(dead_code)] // only called when feature = "cuda" is on (via pool.rs)
pub fn supports_cached_ref(&self) -> bool {
match self.state {
#[cfg(feature = "cpu-cvvdp")]
CpuAdapterState::Cvvdp(_) => true,
#[cfg(feature = "cpu-dssim")]
CpuAdapterState::Dssim(_) => true,
// Phase 8h: fast-ssim2's `Ssimulacra2Reference` precomputes
// the source's XYB / sub-bands once and reuses them across
// distorted candidates — true warm path. The prior
// `ssimulacra2` 0.5 wiring returned false here because that
// crate had no precompute API.
#[cfg(feature = "cpu-ssim2")]
CpuAdapterState::Ssim2(_) => true,
// Phase 9.Y (2026-05-27): butteraugli 0.9.2's
// `ButteraugliReference` precomputes the reference XYB +
// masks once and reuses across `compare(dist_bytes)` calls.
// Prior wiring stored raw bytes and recomputed `full` per
// warm-ref call — equivalent but with no speedup. The
// upgrade keeps the public API identical and turns
// `set_reference` + `compute_with_cached_reference` into a
// true warm path.
#[cfg(feature = "cpu-butter")]
CpuAdapterState::Butter(_) => true,
// Task #134 (2026-05-28): zensim has a true cached-reference
// path via `Zensim::precompute_reference` + `compute_with_ref`.
// The reference XYB conversion + downscale pyramid is hoisted
// out of the per-pair compare — measured +12 % per amortized
// warm call on the 7950X at 16 MP. The prior wiring returned
// `false` here even though `set_reference` stashed bytes, so
// the orchestrator never selected the warm dispatch.
#[cfg(feature = "cpu-zensim")]
CpuAdapterState::Zensim(_) => true,
// iwssim has a true warm path: `warm_reference` caches the
// 5-level Laplacian pyramid + per-scale Gaussian bands; the
// distorted-side pyramid still has to build on every call,
// but the ref-side eigendecomposition (10×10 covariance,
// 5 scales) is hoisted out of the inner loop. Task #136
// (2026-05-28): `compute_with_cached_reference` routes
// through `score_with_warm_ref_strip` so the cached-ref
// entry carries the strip walker's -48 % peak heap win at
// 16 / 40 MP; score parity is within the documented 1e-4
// strip tolerance. See the dispatch arm in
// `compute_with_cached_reference` for measurements.
#[cfg(feature = "cpu-iwssim")]
CpuAdapterState::Iwssim(_) => true,
CpuAdapterState::FeatureDisabled(_) | CpuAdapterState::Unavailable(_) => false,
}
}
/// One-shot compute: hand both buffers, get a score back.
pub fn compute(
&mut self,
ref_bytes: &[u8],
dist_bytes: &[u8],
) -> Result<Score, CpuAdapterError> {
let expected = (self.width as usize) * (self.height as usize) * 3;
if ref_bytes.len() != expected {
return Err(CpuAdapterError::InvalidInputSize {
expected,
got: ref_bytes.len(),
});
}
if dist_bytes.len() != expected {
return Err(CpuAdapterError::InvalidInputSize {
expected,
got: dist_bytes.len(),
});
}
match &mut self.state {
#[cfg(feature = "cpu-cvvdp")]
CpuAdapterState::Cvvdp(c) => compute_cvvdp(c, ref_bytes, dist_bytes),
#[cfg(feature = "cpu-ssim2")]
CpuAdapterState::Ssim2(s) => compute_ssim2(s, ref_bytes, dist_bytes),
#[cfg(feature = "cpu-dssim")]
CpuAdapterState::Dssim(s) => compute_dssim(s, ref_bytes, dist_bytes),
#[cfg(feature = "cpu-butter")]
CpuAdapterState::Butter(s) => compute_butter(s, ref_bytes, dist_bytes),
#[cfg(feature = "cpu-zensim")]
CpuAdapterState::Zensim(s) => compute_zensim(s, ref_bytes, dist_bytes),
#[cfg(feature = "cpu-iwssim")]
CpuAdapterState::Iwssim(c) => compute_iwssim(c, ref_bytes, dist_bytes),
CpuAdapterState::FeatureDisabled(k) => Err(CpuAdapterError::FeatureNotEnabled(*k)),
CpuAdapterState::Unavailable(k) => Err(CpuAdapterError::Unavailable(*k)),
}
}
/// Install reference bytes for subsequent cached-ref calls. On
/// backends without a true cached-ref API, this caches the bytes
/// internally and `compute_with_cached_reference` recomputes from
/// the cached buffer.
#[allow(dead_code)] // only called when feature = "cuda" is on (via pool.rs)
pub fn set_reference(&mut self, ref_bytes: &[u8]) -> Result<(), CpuAdapterError> {
let expected = (self.width as usize) * (self.height as usize) * 3;
if ref_bytes.len() != expected {
return Err(CpuAdapterError::InvalidInputSize {
expected,
got: ref_bytes.len(),
});
}
match &mut self.state {
#[cfg(feature = "cpu-cvvdp")]
CpuAdapterState::Cvvdp(c) => c
.warm_reference(ref_bytes)
.map_err(|e| CpuAdapterError::Failed(e.to_string())),
#[cfg(feature = "cpu-ssim2")]
CpuAdapterState::Ssim2(s) => {
let img = ssim2_image_ref(ref_bytes, s.width, s.height);
let precomputed = fast_ssim2::Ssimulacra2Reference::new(img).map_err(|e| {
CpuAdapterError::Failed(format!("fast-ssim2 Ssimulacra2Reference::new: {e}"))
})?;
s.cached_ref = Some(precomputed);
Ok(())
}
#[cfg(feature = "cpu-dssim")]
CpuAdapterState::Dssim(s) => {
let img = make_dssim_image(&s.dssim, ref_bytes, s.width, s.height)?;
s.cached_ref = Some(img);
Ok(())
}
#[cfg(feature = "cpu-butter")]
CpuAdapterState::Butter(s) => {
// Phase 9.Y: build a `ButteraugliReference` from the
// sRGB-u8 reference bytes once. The precompute runs:
// sRGB → linear → XYB → frequency-separated (LF/MF/HF/UHF)
// → reference mask. Roughly 30-50% of the per-pair
// pipeline cost — the half/sub-res mirror builds in
// parallel via rayon. Holds onto a BufferPool that the
// compare path reuses.
let pre = butteraugli::ButteraugliReference::new(
ref_bytes,
s.width,
s.height,
s.params.clone(),
)
.map_err(|e| {
CpuAdapterError::Failed(format!("butteraugli ButteraugliReference::new: {e:?}"))
})?;
s.cached_ref = Some(pre);
Ok(())
}
#[cfg(feature = "cpu-zensim")]
CpuAdapterState::Zensim(s) => {
// Task #134 (2026-05-28): build the cached
// `PrecomputedReference` once. The crate runs the source
// sRGB → linear → XYB conversion + multi-scale pyramid
// downscale internally; subsequent
// `compute_with_cached_reference` calls dispatch through
// `compute_with_ref` and skip both stages. Measured
// +12 % per amortized warm call on the 7950X at 16 MP
// (see `benchmarks/zensim_cached_ref_cpu_2026-05-28.meta`
// for the 3-trial median wall data).
let src: &[[u8; 3]] = bytemuck::cast_slice(ref_bytes);
let ref_slice = zensim::RgbSlice::new(src, s.width, s.height);
let precomputed = s.zensim.precompute_reference(&ref_slice).map_err(|e| {
CpuAdapterError::Failed(format!("zensim precompute_reference: {e:?}"))
})?;
s.cached_ref = Some(precomputed);
Ok(())
}
#[cfg(feature = "cpu-iwssim")]
CpuAdapterState::Iwssim(c) => c
.warm_reference(ref_bytes)
.map_err(|e| CpuAdapterError::Failed(e.to_string())),
CpuAdapterState::FeatureDisabled(k) => Err(CpuAdapterError::FeatureNotEnabled(*k)),
CpuAdapterState::Unavailable(k) => Err(CpuAdapterError::Unavailable(*k)),
}
}
/// Strip-mode compute: walk image in horizontal slabs of
/// `strip_height` rows + halo. Reduces peak heap for 40 MP+
/// inputs on metrics that support strip dispatch.
///
/// Phase 9.Z.B follow-on status (2026-05-28):
/// - **iwssim**: real strip walker (see `iwssim::Iwssim::score_strip`).
/// Bit-identical-tolerance parity vs full at < 1e-4 abs JOD.
/// - **ssim2**: real strip walker via fast-ssim2 0.8.1
/// `compute_ssimulacra2_strip` (96-row halo, ~24 × strip_h ×
/// width × 4 B peak).
/// - **butter**: real strip walker via butteraugli 0.9.3
/// `butteraugli_strip` (64-row halo, 3.8x heap reduction at 40 MP).
/// - **zensim**: real strip walker via zensim
/// `compute_streaming_strips` (per-strip ref + dist, ~125 MB at
/// 80 MP).
/// - **cvvdp**: API stub — delegates to `score()` (no memory win
/// yet; multi-day walker queued). Returns the same score.
/// - **dssim**: not yet wired (no upstream strip API on dssim-core 3.4).
///
/// Pass `strip_height = 0` to get the metric's default body size
/// (256 rows for ssim2/butter/zensim; iwssim/cvvdp keep their own
/// per-crate defaults).
#[allow(dead_code)] // only called via the strip-aware executor path
pub fn compute_strip(
&mut self,
ref_bytes: &[u8],
dist_bytes: &[u8],
_strip_height: u32,
) -> Result<Score, CpuAdapterError> {
let expected = (self.width as usize) * (self.height as usize) * 3;
if ref_bytes.len() != expected {
return Err(CpuAdapterError::InvalidInputSize {
expected,
got: ref_bytes.len(),
});
}
if dist_bytes.len() != expected {
return Err(CpuAdapterError::InvalidInputSize {
expected,
got: dist_bytes.len(),
});
}
match &mut self.state {
#[cfg(feature = "cpu-cvvdp")]
CpuAdapterState::Cvvdp(c) => {
let h = if strip_height == 0 { 512 } else { strip_height };
let v = c
.score_strip(ref_bytes, dist_bytes, h)
.map_err(|e| CpuAdapterError::Failed(e.to_string()))?;
Ok(make_score("cvvdp", cvvdp_cpu_version(), v as f64))
}
#[cfg(feature = "cpu-iwssim")]
CpuAdapterState::Iwssim(c) => {
let h = if strip_height == 0 {
iwssim::STRIP_BODY_DEFAULT
} else {
strip_height
};
let result = c
.score_strip(ref_bytes, dist_bytes, h)
.map_err(|e| CpuAdapterError::Failed(e.to_string()))?;
Ok(make_score("iwssim", iwssim_cpu_version(), result.score))
}
#[cfg(feature = "cpu-ssim2")]
CpuAdapterState::Ssim2(s) => {
// fast-ssim2 0.8.1 `compute_ssimulacra2_strip` walks the
// image in horizontal strips with a 96-row halo. Bounds
// peak heap to ~24 × strip_h × width × 4 B. Default
// strip_height of 256 matches the documented sweet spot
// (220 MiB at 7700x5200).
let h = if strip_height == 0 { 256 } else { strip_height };
let ref_img = ssim2_image_ref(ref_bytes, s.width, s.height);
let dist_img = ssim2_image_ref(dist_bytes, s.width, s.height);
let v =
fast_ssim2::compute_ssimulacra2_strip(ref_img, dist_img, h).map_err(|e| {
CpuAdapterError::Failed(format!(
"fast-ssim2 compute_ssimulacra2_strip: {e}"
))
})?;
Ok(make_score("ssim2", env!("CARGO_PKG_VERSION"), v))
}
#[cfg(feature = "cpu-dssim")]
CpuAdapterState::Dssim(_) => Err(CpuAdapterError::Failed(
"dssim strip-mode not yet wired in cpu_adapter".into(),
)),
#[cfg(feature = "cpu-butter")]
CpuAdapterState::Butter(s) => {
// butteraugli 0.9.3 `butteraugli_strip` walks the dist
// side in horizontal strips with a 64-row halo (FIR
// chained blur stack). Peak heap drops 3.8x at 40 MP
// (7.43 GB -> 1.94 GB) at equivalent wall time. Default
// strip_height of 256.
use imgref::ImgRef;
let h = if strip_height == 0 { 256 } else { strip_height };
let ref_rgb: &[rgb::RGB<u8>] = bytemuck::cast_slice(ref_bytes);
let dist_rgb: &[rgb::RGB<u8>] = bytemuck::cast_slice(dist_bytes);
let ref_img = ImgRef::new(ref_rgb, s.width, s.height);
let dist_img = ImgRef::new(dist_rgb, s.width, s.height);
let result = butteraugli::butteraugli_strip(ref_img, dist_img, &s.params, h)
.map_err(|e| CpuAdapterError::Failed(format!("butteraugli_strip: {e:?}")))?;
Ok(make_score(
"butter",
env!("CARGO_PKG_VERSION"),
result.score,
))
}
#[cfg(feature = "cpu-zensim")]
CpuAdapterState::Zensim(s) => {
// zensim `compute_streaming_strips` decomposes the
// multiscale pyramid into horizontal strips with
// `strip_inner` body + 2*`strip_margin` halo per side.
// Best for one-off pairs (the warm-ref variant lives
// on `compute_with_cached_reference_strip`). The crate
// default geometry is (256, 128).
let inner = if strip_height == 0 {
256
} else {
strip_height as usize
};
let margin = inner / 2; // matches the documented default ratio
let src: &[[u8; 3]] = bytemuck::cast_slice(ref_bytes);
let dst: &[[u8; 3]] = bytemuck::cast_slice(dist_bytes);
let ref_slice = zensim::RgbSlice::new(src, s.width, s.height);
let dist_slice = zensim::RgbSlice::new(dst, s.width, s.height);
let result = s
.zensim
.compute_streaming_strips(&ref_slice, &dist_slice, inner, margin)
.map_err(|e| {
CpuAdapterError::Failed(format!("zensim compute_streaming_strips: {e:?}"))
})?;
Ok(make_score(
"zensim",
env!("CARGO_PKG_VERSION"),
result.score(),
))
}
CpuAdapterState::FeatureDisabled(k) => Err(CpuAdapterError::FeatureNotEnabled(*k)),
CpuAdapterState::Unavailable(k) => Err(CpuAdapterError::Unavailable(*k)),
}
}
/// Strip-mode compute against the cached reference. See
/// [`Self::compute_strip`] for per-metric implementation status.
///
/// Phase 9.Z.B follow-on status (2026-05-28):
/// - **iwssim**: real warm_ref_strip walker (eigendecomposition
/// cached in `WarmState`; ref state full + one strip dist
/// working set).
/// - **ssim2**: real warm_ref_strip via fast-ssim2 0.8.1
/// `Ssimulacra2Reference::compare_strip` (~220 MiB at 40 MP).
/// - **butter**: real warm_ref_strip via butteraugli 0.9.3
/// `ButteraugliReference::compare_strip` (requires reference
/// built via `new`/`new_linear`; planar refs return
/// `InvalidParameter`).
/// - **zensim**: real warm_ref_strip via zensim
/// `compute_with_ref_streaming_strips` — reuses cached
/// `PrecomputedReference` across strips for batch encoder loops.
/// - **cvvdp**: API stub — delegates to `score_with_warm_ref()`.
/// - **dssim**: not yet wired (no upstream strip API).
#[allow(dead_code)]
pub fn compute_with_cached_reference_strip(
&mut self,
dist_bytes: &[u8],
_strip_height: u32,
) -> Result<Score, CpuAdapterError> {
let expected = (self.width as usize) * (self.height as usize) * 3;
if dist_bytes.len() != expected {
return Err(CpuAdapterError::InvalidInputSize {
expected,
got: dist_bytes.len(),
});
}
match &mut self.state {
#[cfg(feature = "cpu-cvvdp")]
CpuAdapterState::Cvvdp(c) => {
let h = if strip_height == 0 { 512 } else { strip_height };
let v = c
.score_with_warm_ref_strip(dist_bytes, h)
.map_err(|e| CpuAdapterError::Failed(e.to_string()))?;
Ok(make_score("cvvdp", cvvdp_cpu_version(), v as f64))
}
#[cfg(feature = "cpu-iwssim")]
CpuAdapterState::Iwssim(c) => {
if !c.has_reference() {
return Err(CpuAdapterError::Failed(
"iwssim: no cached reference; call set_reference first".into(),
));
}
let h = if strip_height == 0 {
iwssim::STRIP_BODY_DEFAULT
} else {
strip_height
};
let result = c
.score_with_warm_ref_strip(dist_bytes, h)
.map_err(|e| CpuAdapterError::Failed(e.to_string()))?;
Ok(make_score("iwssim", iwssim_cpu_version(), result.score))
}
#[cfg(feature = "cpu-ssim2")]
CpuAdapterState::Ssim2(s) => {
// fast-ssim2 0.8.1 `Ssimulacra2Reference::compare_strip`
// strip-walks the dist side; cached ref-side data stays
// resident (so peak heap is bounded by dist-side only,
// ~220 MiB at 40 MP).
let precomputed = s.cached_ref.as_ref().ok_or_else(|| {
CpuAdapterError::Failed(
"ssim2: no cached reference; call set_reference first".into(),
)
})?;
let h = if strip_height == 0 { 256 } else { strip_height };
let dist_img = ssim2_image_ref(dist_bytes, s.width, s.height);
let v = precomputed.compare_strip(dist_img, h).map_err(|e| {
CpuAdapterError::Failed(format!("fast-ssim2 compare_strip: {e}"))
})?;
Ok(make_score("ssim2", env!("CARGO_PKG_VERSION"), v))
}
#[cfg(feature = "cpu-dssim")]
CpuAdapterState::Dssim(_) => Err(CpuAdapterError::Failed(
"dssim warm_ref strip-mode not yet wired in cpu_adapter".into(),
)),
#[cfg(feature = "cpu-butter")]
CpuAdapterState::Butter(s) => {
// butteraugli 0.9.3 `ButteraugliReference::compare_strip`
// requires the reference to have been built via
// `new` or `new_linear` (planar constructor doesn't
// retain interleaved source — `compare_strip` returns
// `InvalidParameter` in that case).
let pre = s.cached_ref.as_ref().ok_or_else(|| {
CpuAdapterError::Failed(
"butter: no cached reference; call set_reference first".into(),
)
})?;
let h = if strip_height == 0 { 256 } else { strip_height };
let result = pre.compare_strip(dist_bytes, h).map_err(|e| {
CpuAdapterError::Failed(format!(
"butteraugli ButteraugliReference::compare_strip: {e:?}"
))
})?;
Ok(make_score(
"butter",
env!("CARGO_PKG_VERSION"),
result.score,
))
}
#[cfg(feature = "cpu-zensim")]
CpuAdapterState::Zensim(s) => {
// Task #134 (2026-05-28): dispatch through the cached
// `PrecomputedReference` and the strip-aggregating
// `compute_with_ref_streaming_strips` entrypoint. The
// distorted side still walks horizontal strips (peak
// dist memory ~O(strip_h × width)), but the source-side
// pyramid is reused from the cached precompute — the
// best of both worlds for batch quantization loops.
//
// Replaces the prior wiring which fell back to the cold
// `compute_streaming_strips` path (rebuilds the per-strip
// reference precompute on every call), losing the warm
// amortization for any caller that combined memory-bounded
// strip dispatch with cached_ref hints.
let precomputed = s.cached_ref.as_ref().ok_or_else(|| {
CpuAdapterError::Failed(
"zensim: no cached reference; call set_reference first".into(),
)
})?;
let inner = if strip_height == 0 {
256
} else {
strip_height as usize
};
let margin = inner / 2;
let dst: &[[u8; 3]] = bytemuck::cast_slice(dist_bytes);
let dist_slice = zensim::RgbSlice::new(dst, s.width, s.height);
let result = s
.zensim
.compute_with_ref_streaming_strips(precomputed, &dist_slice, inner, margin)
.map_err(|e| {
CpuAdapterError::Failed(format!(
"zensim compute_with_ref_streaming_strips: {e:?}"
))
})?;
Ok(make_score(
"zensim",
env!("CARGO_PKG_VERSION"),
result.score(),
))
}
CpuAdapterState::FeatureDisabled(k) => Err(CpuAdapterError::FeatureNotEnabled(*k)),
CpuAdapterState::Unavailable(k) => Err(CpuAdapterError::Unavailable(*k)),
}
}
/// Whether this backend supports memory-bounded strip dispatch.
/// Used by the orchestrator's chooser to decide whether
/// `MemoryMode::Strip` is a candidate for CPU dispatch on this
/// metric.
///
/// Phase 9.Z.B follow-on (2026-05-28): ssim2, butter, zensim, and
/// iwssim all expose real strip walkers via the sibling crates.
/// cvvdp returns `false` (API stub delegates to full path; multi-day
/// walker queued).
#[allow(dead_code)]
pub fn supports_strip(&self) -> bool {
match self.state {
#[cfg(feature = "cpu-cvvdp")]
CpuAdapterState::Cvvdp(_) => false,
#[cfg(feature = "cpu-iwssim")]
CpuAdapterState::Iwssim(_) => true,
#[cfg(feature = "cpu-ssim2")]
CpuAdapterState::Ssim2(_) => true,
#[cfg(feature = "cpu-butter")]
CpuAdapterState::Butter(_) => true,
#[cfg(feature = "cpu-zensim")]
CpuAdapterState::Zensim(_) => true,
_ => false,
}
}
/// Compute against the previously-set reference. Returns
/// `Err(Failed)` if [`Self::set_reference`] hasn't been called yet
/// (or was reset by a prior `compute` on backends without cached
/// state).
#[allow(dead_code)] // only called when feature = "cuda" is on (via pool.rs)
pub fn compute_with_cached_reference(
&mut self,
dist_bytes: &[u8],
) -> Result<Score, CpuAdapterError> {
let expected = (self.width as usize) * (self.height as usize) * 3;
if dist_bytes.len() != expected {
return Err(CpuAdapterError::InvalidInputSize {
expected,
got: dist_bytes.len(),
});
}
match &mut self.state {
#[cfg(feature = "cpu-cvvdp")]
CpuAdapterState::Cvvdp(c) => {
let v = c
.score_with_warm_ref(dist_bytes)
.map_err(|e| CpuAdapterError::Failed(e.to_string()))?;
Ok(make_score("cvvdp", cvvdp_cpu_version(), v as f64))
}
#[cfg(feature = "cpu-ssim2")]
CpuAdapterState::Ssim2(s) => {
let precomputed = s.cached_ref.as_ref().ok_or_else(|| {
CpuAdapterError::Failed(
"ssim2: no cached reference; call set_reference first".into(),
)
})?;
let dist_img = ssim2_image_ref(dist_bytes, s.width, s.height);
let v = precomputed
.compare(dist_img)
.map_err(|e| CpuAdapterError::Failed(format!("fast-ssim2 compare: {e}")))?;
Ok(make_score("ssim2", env!("CARGO_PKG_VERSION"), v))
}
#[cfg(feature = "cpu-dssim")]
CpuAdapterState::Dssim(s) => {
let r = s.cached_ref.as_ref().ok_or_else(|| {
CpuAdapterError::Failed(
"dssim: no cached reference; call set_reference first".into(),
)
})?;
let dist_img = make_dssim_image(&s.dssim, dist_bytes, s.width, s.height)?;
let (score, _maps) = s.dssim.compare(r, dist_img);
Ok(make_score("dssim", dssim_cpu_version(), f64::from(score)))
}
#[cfg(feature = "cpu-butter")]
CpuAdapterState::Butter(s) => {
// Phase 9.Y: dispatch against the cached `ButteraugliReference`.
// The compare path runs the dist-side sRGB → linear → XYB
// → frequency-separation, then diffs against the precomputed
// ref-side data. ~30-50 % fewer ops per call than `full`.
let pre = s.cached_ref.as_ref().ok_or_else(|| {
CpuAdapterError::Failed(
"butter: no cached reference; call set_reference first".into(),
)
})?;
let result = pre
.compare(dist_bytes)
.map_err(|e| CpuAdapterError::Failed(format!("butteraugli compare: {e:?}")))?;
Ok(make_score(
"butter",
env!("CARGO_PKG_VERSION"),
result.score,
))
}
#[cfg(feature = "cpu-zensim")]
CpuAdapterState::Zensim(s) => {
// Task #134 (2026-05-28): dispatch through the cached
// `PrecomputedReference`. The compare path runs the
// distorted-side sRGB → linear → XYB + pyramid downscale,
// then diffs against the precomputed ref pyramid — the
// ref-side conversion + downscale (≈50 % of the per-pair
// pipeline by CPU sweep #132 measurement) is hoisted out.
// Replaces the prior wiring which cloned the raw byte
// stash and re-ran the full cold path on every call.
let precomputed = s.cached_ref.as_ref().ok_or_else(|| {
CpuAdapterError::Failed(
"zensim: no cached reference; call set_reference first".into(),
)
})?;
let dst: &[[u8; 3]] = bytemuck::cast_slice(dist_bytes);
let dist_slice = zensim::RgbSlice::new(dst, s.width, s.height);
let result = s
.zensim
.compute_with_ref(precomputed, &dist_slice)
.map_err(|e| {
CpuAdapterError::Failed(format!("zensim compute_with_ref: {e:?}"))
})?;
Ok(make_score(
"zensim",
env!("CARGO_PKG_VERSION"),
result.score(),
))
}
#[cfg(feature = "cpu-iwssim")]
CpuAdapterState::Iwssim(c) => {
if !c.has_reference() {
return Err(CpuAdapterError::Failed(
"iwssim: no cached reference; call set_reference first".into(),
));
}
// Task #136 (2026-05-28): route through the strip walker
// even on the "cached_ref" entry point. The non-strip
// `score_with_warm_ref` retains `lp_ref + g_ref` but
// STILL builds a full-image `lp_dis` pyramid and a
// full-image `compute_iw_maps` working set inside
// `score_with_split` (~11 × `h*w` f32 just in
// `box_stats_3x3`; +`nexp × big_n × 4` in
// `build_y_matrix`). Measured (heaptrack process peak,
// 7950X, synth pair):
//
// size | full | warm_ref | warm_ref_strip
// ------+----------+-----------+----------------
// 1 MP | 153.8 MB | 153.8 MB | 103.6 MB (-33 %)
// 16 MP | 2.47 GB | 2.47 GB | 1.29 GB (-48 %)
// 40 MP | 5.90 GB | 5.90 GB | 3.07 GB (-48 %)
//
// Per-pair score diff at all measured sizes ≤ 2e-6
// absolute — well inside iwssim's documented strip
// parity tolerance of 1e-4 (see
// `crates/iwssim/tests/strip_parity.rs` and
// `iwssim::Iwssim::score_with_warm_ref_strip` docs).
// Wall time regresses 9.5 % (1 MP) → 23.9 % (16 MP) →
// 34.7 % (40 MP) — accepted because the
// cached-ref entry's value proposition for the
// orchestrator is amortizing the ref-side pyramid,
// which the strip variant ALSO does (warm state
// identical: `lp_ref`, `g_ref`, per-scale `eigs`).
// The explicit strip-mode entry
// `compute_with_cached_reference_strip` remains for
// callers that want to pin a body height.
let result = c
.score_with_warm_ref_strip(dist_bytes, iwssim::STRIP_BODY_DEFAULT)
.map_err(|e| CpuAdapterError::Failed(e.to_string()))?;
Ok(make_score("iwssim", iwssim_cpu_version(), result.score))
}
CpuAdapterState::FeatureDisabled(k) => Err(CpuAdapterError::FeatureNotEnabled(*k)),
CpuAdapterState::Unavailable(k) => Err(CpuAdapterError::Unavailable(*k)),
}
}
}
// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------
#[allow(dead_code)] // only used when at least one cpu-* feature is on
fn make_score(name: &'static str, version: &'static str, value: f64) -> Score {
Score {
value,
metric_name: name,
metric_version: version,
}
}
// ---------------------------------------------------------------------------
// cvvdp wiring
// ---------------------------------------------------------------------------
#[cfg(feature = "cpu-cvvdp")]
fn construct_cvvdp(
width: u32,
height: u32,
params: &MetricParams,
) -> Result<CpuAdapterState, CpuAdapterError> {
// cvvdp re-exports CvvdpParams from cvvdp-gpu, and the umbrella
// wraps the *same* struct in MetricParams::Cvvdp. So we can lift
// the params without an extra translation table.
let p = match params {
MetricParams::Cvvdp(p) => p.clone(),
_ => {
return Err(CpuAdapterError::Failed(format!(
"expected MetricParams::Cvvdp, got {params:?}"
)));
}
};
let c =
cvvdp::Cvvdp::new(width, height, p).map_err(|e| CpuAdapterError::Failed(e.to_string()))?;
Ok(CpuAdapterState::Cvvdp(Box::new(c)))
}
#[cfg(not(feature = "cpu-cvvdp"))]
#[allow(unused_variables)]
fn construct_cvvdp(
_width: u32,
_height: u32,
_params: &MetricParams,
) -> Result<CpuAdapterState, CpuAdapterError> {
Err(CpuAdapterError::FeatureNotEnabled(MetricKind::Cvvdp))
}
#[cfg(feature = "cpu-cvvdp")]
fn compute_cvvdp(c: &mut cvvdp::Cvvdp, r: &[u8], d: &[u8]) -> Result<Score, CpuAdapterError> {
let v = c
.score(r, d)
.map_err(|e| CpuAdapterError::Failed(e.to_string()))?;
Ok(make_score("cvvdp", cvvdp_cpu_version(), v as f64))
}
#[cfg(feature = "cpu-cvvdp")]
fn cvvdp_cpu_version() -> &'static str {