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
//! `pad_to_square` canvas fill: tile a `&mut [MaybeUninit<u8>]`
//! with a repeating 3-byte RGB pattern.
//!
//! Tracking: [#151](https://github.com/Findit-AI/mlxrs/issues/151).
//!
//! # The defect class
//!
//! The original [`crate::vlm::image::pad_to_square`] canvas fill was:
//!
//! ```rust,ignore
//! for _ in 0..(bytes_usize / 3) {
//! canvas_buf.extend_from_slice(&fill); // RGB triple
//! }
//! ```
//!
//! Each iteration was a 3-byte `extend_from_slice` on a `Vec<u8>` —
//! `~bytes/3` function calls, each with its own bounds check and `len`
//! update. For a near-budget `13377²` canvas (`~511 MiB / 3 ≈ 180M`
//! iterations) this is a genuinely slow idiom — the per-call overhead
//! dwarfs the actual byte writes by an order of magnitude in our
//! benches. This kernel barely needs intrinsics; the per-3-byte
//! `extend` is the slow idiom — fixing that captures most of the win.
//!
//! # The fix — `chunks_mut(3) + copy_from_slice`
//!
//! Replace the per-iteration `extend_from_slice` with a single
//! `chunks_mut(3)` slice-tiled fill into a pre-reserved buffer. LLVM
//! emits a tight `stp`-pair loop on aarch64 for this shape that runs
//! at memory bandwidth (~70 GB/s on M-series Apple silicon, capped by
//! L3 / DRAM rather than the ALU).
//!
//! Three implementations are benchmarked at 256² / 1024² / 4096² canvas
//! sizes:
//!
//! | impl | 256² (≈196k B) | 1024² (≈3.1M B) | 4096² (≈50M B) |
//! | ---------------------------------------------- | --------------:| ---------------:| --------------:|
//! | OLD `for _ in 0..bytes/3 { extend_from_slice }` | (see bench) | (see bench) | (see bench) |
//! | NEW scalar `chunks_mut(3) + copy_from_slice` | (see bench) | (see bench) | (see bench) |
//! | NEW NEON 48-byte pre-broadcast `vst1q_u8` tile | (see bench) | (see bench) | (see bench) |
//!
//! Concrete numbers live in the bench output
//! (`mlxrs/benches/simd_pad_canvas_fill.rs`).
//!
//! # NEON kernel — 48-byte LCM(3, 16) pre-broadcast
//!
//! The hand-rolled NEON kernel builds a 48-byte pre-broadcast pattern once on
//! the stack (LCM(3, 16) — three RGB triples pack evenly into one
//! 16-byte NEON register, so a 48-byte tile is the smallest power of
//! the pattern that aligns with `vst1q_u8` chunks of 16). It then
//! emits three `vst1q_u8` stores per 48-byte tile (no `vld` in the
//! body — the broadcast lives in three NEON registers across the loop).
//! Tail bytes (`out.len() % 48`) are handled by the scalar arm.
//!
//! # Correctness class — `Exact`
//!
//! This kernel is pure data movement (a `memset`-like tile fill with a 3-byte
//! period). The scalar and NEON paths produce **bit-identical** output
//! — both write the same byte sequence `fill[0..3]` repeated
//! `out.len() / 3` times, plus any partial-triple tail (handled
//! identically by the scalar arm at the start/end of both paths).
//! The differential test in this module asserts byte equality via
//! [`crate::simd::diff::assert_eq_over_lane_sweep`] (the `Exact` class).
//!
//! # `MaybeUninit<u8>` API — type-encoded uninit safety
//!
//! The kernel API takes `&mut [MaybeUninit<u8>]` (not `&mut [u8]`) so
//! the call site in [`crate::vlm::image::pad_to_square`] can pass
//! `Vec::spare_capacity_mut()` **directly** — no `from_raw_parts_mut`
//! cast over uninit backing memory (which would be UB regardless of
//! the subsequent writes, per the `from_raw_parts_mut` safety contract
//! requiring "properly initialized" elements). The kernels write every
//! byte of `out` via `MaybeUninit::write` (scalar) or raw pointer store
//! `vst1q_u8` (NEON) — both sound on `MaybeUninit`. The function-level
//! contract on [`pad_canvas_fill`] is "every byte of `out` is written
//! before this returns", so the caller may safely `set_len` over the
//! covered region.
//!
//! # No new dependencies
//!
//! Pure `core::slice` + `core::arch::aarch64` + `core::mem::MaybeUninit`
//! (all `core`, no crate dep). The dispatcher routes through
//! [`crate::simd::is_neon_available`].
use MaybeUninit;
use ;
/// Fill `out` with the repeating 3-byte RGB triple `rgb`. Scalar
/// reference — the bit-exact oracle for the NEON dispatcher.
///
/// **Always compiled** — independent of `target_arch`. Anchors the
/// math contract (a `(out.len() / 3)`-iteration `MaybeUninit::write` of
/// the same 3-byte triple), is the differential-test oracle, and is
/// the fallback path on every non-`aarch64` target.
///
/// # Initialization contract
///
/// Every byte of `out` is written via `MaybeUninit::write` before this
/// returns. On return the entire slice is fully initialized; the caller
/// may treat the backing memory as `[u8]` (via `Vec::set_len`,
/// `MaybeUninit::slice_assume_init_ref`, etc.).
///
/// # Implementation choice
///
/// `chunks_exact_mut(3)` over the **already-sized**
/// `&mut [MaybeUninit<u8>]` (caller has pre-reserved). Each chunk
/// writes 3 `MaybeUninit::write` calls (one per RGB byte). The
/// alternative — build a ~48-byte pre-broadcast LCM(3, 16) pattern on
/// the stack and bulk-copy by 48-byte tiles — is what the NEON kernel
/// does; we keep the scalar path simple (one `chunks_exact_mut(3)`
/// line) so it stays the trivially-auditable reference. LLVM emits a
/// tight `stp`-pair loop on aarch64 for this shape — the bench shows
/// it already runs at memory bandwidth on M-series silicon.
///
/// # Tail handling
///
/// If `out.len() % 3 != 0` (a partial RGB triple at the end), the
/// trailing 1 or 2 bytes are filled with the leading 1 or 2 bytes of
/// `rgb`. This matches the `out.chunks_exact_mut(3)` semantics: the
/// final remainder has `len() < 3` and we write each remaining slot
/// individually with the corresponding `rgb` byte.
///
/// **In the [`crate::vlm::image::pad_to_square`] call site `out.len()`
/// is always a multiple of 3** (the byte count is `size * size * 3` by
/// construction), so the partial-triple branch is unreachable in
/// practice. The branch exists for the function-level contract and
/// for the test sweep — the partial-triple length cases (`1`, `2`,
/// `17` etc. in [`crate::simd::diff::lane_sweep_lengths(16)`]) are
/// covered by the differential test.
/// Fill `out` with the repeating 3-byte RGB triple `rgb`. NEON
/// 48-byte LCM(3, 16) pre-broadcast tile.
///
/// # Algorithm
///
/// 1. Build a 48-byte pattern on the stack: three RGB triples × 16
/// repetitions = 48 bytes (`LCM(3, 16) = 48`). 48 is the smallest
/// multiple of both the RGB period (3) and the NEON `uint8x16_t`
/// register width (16) — so the pattern can be reloaded as three
/// distinct 16-byte NEON registers, each aligned with a
/// `vst1q_u8` store.
/// 2. Load the three 16-byte chunks into three `uint8x16_t`
/// registers **once**, outside the body loop. The body is a tight
/// three-`vst1q_u8` sequence per 48-byte tile — no `vld` in the
/// hot path.
/// 3. Tail (`out.len() % 48` bytes) is handled by
/// [`pad_canvas_fill_scalar`] on the trailing slice. The tail is
/// bounded above by 47 bytes — negligible compared to the body
/// even at the smallest tested 256² (≈196k B) canvas.
///
/// # Initialization contract
///
/// Every byte of `out` is written before this returns — the body loop
/// covers `out[0..body_len]` via raw `vst1q_u8` stores, and the
/// scalar arm covers the trailing `out[body_len..]` via
/// `MaybeUninit::write`. On return the entire slice is fully
/// initialized.
///
/// # Safety
///
/// 1. NEON must be available on the executing CPU. This is the
/// caller's obligation — the public dispatcher
/// [`pad_canvas_fill`] discharges it via
/// [`crate::simd::is_neon_available`].
/// 2. `out` must be a valid `&mut [MaybeUninit<u8>]` slice (the
/// standard `&mut [T]` aliasing contract — Rust's borrow checker
/// enforces this at every safe call site). Writing to
/// `MaybeUninit<u8>` via a raw pointer store is always sound
/// (`MaybeUninit<u8>` has no validity invariants beyond size +
/// alignment; the standard library's `MaybeUninit` doc explicitly
/// permits this idiom).
///
/// There is no input alignment requirement: `vst1q_u8` accepts
/// unaligned stores at full throughput on aarch64 (no faulting on
/// misalignment, no perf cliff — verified by the bench at 256² which
/// hits worst-case alignment for the canvas allocation).
pub unsafe
/// Fill `out` with the repeating 3-byte RGB triple `rgb`. Routes to
/// NEON on `aarch64` (when the CPU reports NEON), else to
/// [`pad_canvas_fill_scalar`].
///
/// # Initialization contract
///
/// **Every byte of `out` is written before this returns.** On return
/// the entire `&mut [MaybeUninit<u8>]` slice is fully initialized; the
/// caller may treat the backing memory as `[u8]` (e.g. via
/// `Vec::set_len` over the covered region after passing
/// `spare_capacity_mut()`).
///
/// Tracking: [#151](https://github.com/Findit-AI/mlxrs/issues/151).
/// No intrinsics strictly required. The hand-rolled NEON 48-byte
/// (`LCM(3, 16)`) pre-broadcast tile ships unconditionally; if the bench
/// regresses (LLVM auto-vec catches up, future toolchain), the NEON
/// kernel can be removed and the dispatcher collapsed to the scalar
/// arm without touching the call site.
///
/// # Correctness class
///
/// `Exact` — the SIMD output is bit-identical to scalar. Pure data
/// movement: a `memset`-like tile fill with a 3-byte period.
/// Differential test in [`mod@self`]'s `tests` module uses
/// [`crate::simd::diff::assert_eq_over_lane_sweep`] (the `Exact` class,
/// `lanes = 16` for `uint8x16_t`).
///
/// # Call site
///
/// [`crate::vlm::image::pad_to_square`] — fills the pre-reserved
/// `size * size * 3`-byte canvas with a uniform RGB triple before the
/// source overlay step. Passes `canvas_buf.spare_capacity_mut()`
/// directly (no `from_raw_parts_mut` cast).