j2k-transcode-metal 0.7.3

Metal acceleration for JPEG-to-HTJ2K coefficient-domain transcode stages
Documentation
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
// SPDX-License-Identifier: MIT OR Apache-2.0

use j2k_transcode::accelerator::TranscodeStageError;
use j2k_transcode::accelerator::{
    DctGridToDwt53Job, DctGridToReversibleDwt53Job, DctToWaveletStageAccelerator,
};
#[cfg(target_os = "macos")]
use j2k_transcode::accelerator::{RayonReversibleDwt53Accelerator, ReversibleDwt53FirstLevel};
#[cfg(target_os = "macos")]
use j2k_transcode::{dct8x8_blocks_to_dwt53_float_linear, Dwt53TwoDimensional};
use j2k_transcode_metal::weights::{Dwt53WeightRows, SparseDwt53WeightRows};
use j2k_transcode_metal::MetalDctToWaveletStageAccelerator;

#[cfg(target_os = "macos")]
fn should_run_metal_runtime() -> bool {
    j2k_test_support::metal_runtime_gate(module_path!())
}

#[test]
fn explicit_metal_53_reports_unavailable_on_non_macos() {
    #[cfg(target_os = "macos")]
    if !should_run_metal_runtime() {
        return;
    }

    let mut accelerator = MetalDctToWaveletStageAccelerator::new_explicit();
    let blocks = vec![[[0.0; 8]; 8]];
    let result = accelerator.dct_grid_to_dwt53(DctGridToDwt53Job {
        blocks: &blocks,
        block_cols: 1,
        block_rows: 1,
        width: 8,
        height: 8,
    });

    #[cfg(not(target_os = "macos"))]
    assert!(matches!(
        result.expect_err("explicit Metal is unavailable off macOS"),
        TranscodeStageError::DeviceUnavailable
    ));

    #[cfg(target_os = "macos")]
    let _ = result;
}

#[test]
fn explicit_metal_reversible_53_reports_unavailable_on_non_macos() {
    #[cfg(target_os = "macos")]
    if !should_run_metal_runtime() {
        return;
    }

    let mut accelerator = MetalDctToWaveletStageAccelerator::new_explicit();
    let blocks = vec![[0i16; 64]];
    let result = accelerator.dct_grid_to_reversible_dwt53(DctGridToReversibleDwt53Job {
        dequantized_blocks: &blocks,
        block_cols: 1,
        block_rows: 1,
        width: 8,
        height: 8,
    });

    #[cfg(not(target_os = "macos"))]
    assert!(matches!(
        result.expect_err("explicit Metal is unavailable off macOS"),
        TranscodeStageError::DeviceUnavailable
    ));

    #[cfg(target_os = "macos")]
    let _ = result;
}

#[test]
fn auto_metal_53_falls_back_for_tiny_jobs() {
    let mut accelerator = MetalDctToWaveletStageAccelerator::for_auto();
    let blocks = vec![[[0.0; 8]; 8]];
    let output = accelerator
        .dct_grid_to_dwt53(DctGridToDwt53Job {
            blocks: &blocks,
            block_cols: 1,
            block_rows: 1,
            width: 8,
            height: 8,
        })
        .expect("auto accelerator can decline tiny 5/3 job");

    assert!(output.is_none());
    assert_eq!(accelerator.dwt53_attempts(), 1);
    assert_eq!(accelerator.dwt53_dispatches(), 0);
}

#[test]
fn auto_metal_reversible_53_declines_tiny_jobs() {
    let mut accelerator = MetalDctToWaveletStageAccelerator::for_auto();
    let blocks = vec![[0i16; 64]];
    let output = accelerator
        .dct_grid_to_reversible_dwt53(DctGridToReversibleDwt53Job {
            dequantized_blocks: &blocks,
            block_cols: 1,
            block_rows: 1,
            width: 8,
            height: 8,
        })
        .expect("auto accelerator can decline tiny reversible 5/3 job");

    // `None` hands the job to the caller's scalar fallback — the same
    // contract as the float 5/3 path and the CUDA accelerator.
    assert!(output.is_none());
    assert_eq!(accelerator.reversible_dwt53_attempts(), 1);
    assert_eq!(accelerator.reversible_dwt53_dispatches(), 0);
}

#[test]
fn auto_metal_reversible_53_batch_declines_tiny_jobs() {
    let mut accelerator = MetalDctToWaveletStageAccelerator::for_auto();
    let blocks = vec![[0i16; 64]];
    let jobs = [DctGridToReversibleDwt53Job {
        dequantized_blocks: &blocks,
        block_cols: 1,
        block_rows: 1,
        width: 8,
        height: 8,
    }];
    let output = accelerator
        .dct_grid_to_reversible_dwt53_batch(&jobs)
        .expect("auto accelerator can decline tiny reversible 5/3 batch");

    assert!(output.is_none());
    assert_eq!(accelerator.reversible_dwt53_batch_attempts(), 1);
    assert_eq!(accelerator.reversible_dwt53_batch_dispatches(), 0);
}

#[cfg(target_os = "macos")]
#[test]
fn explicit_metal_dct53_matches_scalar_for_structured_cases() {
    if !should_run_metal_runtime() {
        return;
    }

    let blocks = structured_blocks(2, 2);
    let mut accelerator = MetalDctToWaveletStageAccelerator::new_explicit();

    for (width, height) in [(8, 8), (13, 11), (16, 16)] {
        let actual = match accelerator.dct_grid_to_dwt53(DctGridToDwt53Job {
            blocks: &blocks,
            block_cols: 2,
            block_rows: 2,
            width,
            height,
        }) {
            Ok(Some(output)) => output,
            Ok(None) => panic!("explicit Metal accelerator must not silently fall back"),
            Err(TranscodeStageError::DeviceUnavailable) => {
                j2k_test_support::metal_device_unavailable_is_skip(module_path!());
                return;
            }
            Err(message) => panic!("explicit Metal 5/3 accelerator failed: {message}"),
        };
        let expected = dct8x8_blocks_to_dwt53_float_linear(&blocks, 2, 2, width, height)
            .expect("scalar 5/3 projection accepts covered grid");

        let max_diff = max_abs_diff(&actual, &expected);
        assert!(
            max_diff <= 2.0e-2,
            "Metal 5/3 DCT projection diverged for {width}x{height}: {max_diff}"
        );
    }

    assert_eq!(accelerator.dwt53_dispatches(), 3);
}

#[cfg(target_os = "macos")]
#[test]
fn explicit_metal_reversible_dct53_matches_rayon_for_structured_cases() {
    if !should_run_metal_runtime() {
        return;
    }

    let blocks = structured_i16_blocks(2, 2);
    let mut expected_accelerator = RayonReversibleDwt53Accelerator::default();
    let mut accelerator = MetalDctToWaveletStageAccelerator::new_explicit();

    for (width, height) in [
        (1, 1),
        (1, 2),
        (2, 1),
        (2, 2),
        (8, 8),
        (13, 11),
        (13, 12),
        (12, 11),
        (16, 16),
    ] {
        let job = DctGridToReversibleDwt53Job {
            dequantized_blocks: &blocks,
            block_cols: 2,
            block_rows: 2,
            width,
            height,
        };
        let actual = match accelerator.dct_grid_to_reversible_dwt53(job) {
            Ok(Some(output)) => output,
            Ok(None) => panic!("explicit Metal accelerator must not silently fall back"),
            Err(TranscodeStageError::DeviceUnavailable) => {
                j2k_test_support::metal_device_unavailable_is_skip(module_path!());
                return;
            }
            Err(message) => panic!("explicit Metal reversible 5/3 accelerator failed: {message}"),
        };
        let expected = expected_accelerator
            .dct_grid_to_reversible_dwt53(job)
            .expect("rayon reversible 5/3 accepts covered grid")
            .expect("rayon handles reversible 5/3 job");

        assert_reversible_eq(&actual, &expected, width, height);
    }

    assert_eq!(accelerator.reversible_dwt53_dispatches(), 9);
}

#[cfg(target_os = "macos")]
#[test]
fn explicit_metal_reversible_dct53_batch_matches_rayon_for_structured_cases() {
    if !should_run_metal_runtime() {
        return;
    }

    let batch_blocks = [
        structured_i16_blocks_with_offset(2, 2, 0),
        structured_i16_blocks_with_offset(2, 2, 31),
        structured_i16_blocks_with_offset(2, 2, -27),
        structured_i16_blocks_with_offset(2, 2, 59),
    ];
    let mut accelerator = MetalDctToWaveletStageAccelerator::new_explicit();

    for (width, height) in [(8, 8), (13, 11), (13, 12), (12, 11), (16, 16)] {
        let jobs: Vec<_> = batch_blocks
            .iter()
            .map(|blocks| DctGridToReversibleDwt53Job {
                dequantized_blocks: blocks,
                block_cols: 2,
                block_rows: 2,
                width,
                height,
            })
            .collect();
        let actual = match accelerator.dct_grid_to_reversible_dwt53_batch(&jobs) {
            Ok(Some(output)) => output,
            Ok(None) => panic!("explicit Metal batch accelerator must not silently fall back"),
            Err(TranscodeStageError::DeviceUnavailable) => {
                j2k_test_support::metal_device_unavailable_is_skip(module_path!());
                return;
            }
            Err(message) => {
                panic!("explicit Metal reversible 5/3 batch accelerator failed: {message}");
            }
        };

        assert_eq!(actual.len(), jobs.len());
        for (idx, (actual, job)) in actual.iter().zip(jobs.iter()).enumerate() {
            let mut expected_accelerator = RayonReversibleDwt53Accelerator::default();
            let expected = expected_accelerator
                .dct_grid_to_reversible_dwt53(*job)
                .expect("rayon reversible 5/3 accepts covered grid")
                .expect("rayon handles reversible 5/3 job");
            assert_eq!(
                actual, &expected,
                "reversible 5/3 batch mismatch for item {idx} at {width}x{height}"
            );
        }
    }

    assert_eq!(accelerator.reversible_dwt53_batch_dispatches(), 5);
}

#[test]
fn dwt53_weight_rows_match_expected_geometry_for_supported_lengths() {
    for sample_len in [8_usize, 13, 16] {
        let rows = Dwt53WeightRows::for_len(sample_len).expect("bounded dense 5/3 weight rows");

        assert_eq!(rows.low.len(), sample_len.div_ceil(2));
        assert_eq!(rows.high.len(), sample_len / 2);
        assert!(rows.low.iter().all(|row| row.len() == sample_len));
        assert!(rows.high.iter().all(|row| row.len() == sample_len));
        assert!(rows
            .low
            .iter()
            .all(|row| row.iter().any(|&value| value.to_bits() != 0)));
        assert!(rows
            .high
            .iter()
            .all(|row| row.iter().any(|&value| value.to_bits() != 0)));
    }
}

#[test]
fn dwt53_weight_rows_are_deterministic() {
    let first = Dwt53WeightRows::for_len(13).expect("bounded dense 5/3 weight rows");
    let second = Dwt53WeightRows::for_len(13).expect("bounded dense 5/3 weight rows");

    assert_eq!(f32_rows_to_bits(&first.low), f32_rows_to_bits(&second.low));
    assert_eq!(
        f32_rows_to_bits(&first.high),
        f32_rows_to_bits(&second.high)
    );
}

#[test]
fn sparse_dwt53_weight_rows_reconstruct_dense_rows_for_wsi_lengths() {
    for sample_len in [8_usize, 13, 16, 224, 512, 1024, 2048] {
        let dense = Dwt53WeightRows::for_len(sample_len).expect("bounded dense 5/3 weight rows");
        let sparse =
            SparseDwt53WeightRows::for_len(sample_len).expect("bounded sparse 5/3 weight rows");

        assert!(sparse.max_taps_per_row() <= 5);
        assert_eq!(sparse.low.len(), dense.low.len());
        assert_eq!(sparse.high.len(), dense.high.len());
        assert_eq!(reconstruct_sparse_rows(&sparse.low, sample_len), dense.low);
        assert_eq!(
            reconstruct_sparse_rows(&sparse.high, sample_len),
            dense.high
        );
    }
}

fn f32_rows_to_bits(rows: &[Vec<f32>]) -> Vec<Vec<u32>> {
    rows.iter()
        .map(|row| row.iter().map(|value| value.to_bits()).collect())
        .collect()
}

fn reconstruct_sparse_rows(
    rows: &[j2k_transcode_metal::weights::SparseWeightRow],
    sample_len: usize,
) -> Vec<Vec<f32>> {
    rows.iter()
        .map(|row| {
            let mut dense = vec![0.0; sample_len];
            for tap in &row.taps {
                dense[tap.sample_idx] = tap.weight;
            }
            dense
        })
        .collect()
}

#[cfg(target_os = "macos")]
fn assert_reversible_eq(
    actual: &ReversibleDwt53FirstLevel,
    expected: &ReversibleDwt53FirstLevel,
    width: usize,
    height: usize,
) {
    assert_eq!(
        actual, expected,
        "reversible 5/3 mismatch for {width}x{height}"
    );
}

#[cfg(target_os = "macos")]
fn max_abs_diff(actual: &Dwt53TwoDimensional<f64>, expected: &Dwt53TwoDimensional<f64>) -> f64 {
    assert_eq!(actual.low_width, expected.low_width);
    assert_eq!(actual.low_height, expected.low_height);
    assert_eq!(actual.high_width, expected.high_width);
    assert_eq!(actual.high_height, expected.high_height);

    actual
        .ll
        .iter()
        .zip(expected.ll.iter())
        .chain(actual.hl.iter().zip(expected.hl.iter()))
        .chain(actual.lh.iter().zip(expected.lh.iter()))
        .chain(actual.hh.iter().zip(expected.hh.iter()))
        .map(|(actual, expected)| (actual - expected).abs())
        .fold(0.0, f64::max)
}

#[cfg(target_os = "macos")]
#[expect(
    clippy::cast_precision_loss,
    reason = "test grid indices are bounded by allocated fixture dimensions"
)]
fn structured_blocks(block_cols: usize, block_rows: usize) -> Vec<[[f64; 8]; 8]> {
    let mut blocks = Vec::with_capacity(block_cols * block_rows);
    for block_y in 0..block_rows {
        for block_x in 0..block_cols {
            let mut block = [[0.0; 8]; 8];
            block[0][0] = 384.0 + (block_x * 19 + block_y * 23) as f64;
            block[0][1] = -17.0 + block_x as f64;
            block[1][0] = 11.0 - block_y as f64;
            block[2][3] = 7.0;
            block[4][4] = -3.0;
            block[7][7] = 2.0;
            blocks.push(block);
        }
    }
    blocks
}

#[cfg(target_os = "macos")]
fn structured_i16_blocks(block_cols: usize, block_rows: usize) -> Vec<[i16; 64]> {
    structured_i16_blocks_with_offset(block_cols, block_rows, 0)
}

#[cfg(target_os = "macos")]
fn structured_i16_blocks_with_offset(
    block_cols: usize,
    block_rows: usize,
    base_offset: i16,
) -> Vec<[i16; 64]> {
    let mut blocks = Vec::with_capacity(block_cols * block_rows);
    for block_y in 0..block_rows {
        for block_x in 0..block_cols {
            let mut block = [0i16; 64];
            let block_offset =
                i16::try_from(block_x * 19 + block_y * 23).expect("fixture offset fits i16");
            let x_offset = i16::try_from(block_x).expect("fixture x offset fits i16");
            let y_offset = i16::try_from(block_y).expect("fixture y offset fits i16");
            block[0] = 384 + base_offset + block_offset;
            block[1] = -17 + x_offset;
            block[8] = 11 - y_offset;
            block[19] = 7;
            block[36] = -3;
            block[63] = 2;
            blocks.push(block);
        }
    }
    blocks
}