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
//! Spatial interpolation ops.
//!
//! Two primitives:
//!
//! - [`bilinear_interpolate`] — a separable **bilinear + antialias** resize of
//! a 2-D spatial grid, matching PyTorch
//! `torch.nn.functional.interpolate(mode="bilinear", align_corners=False,
//! antialias=True)` exactly (the antialias triangle-filter path of `aten`'s
//! `UpSampleKernel.cpp`, not the plain 2-tap align-corners=False kernel).
//! - [`bicubic_interpolate`] — a separable **bicubic** (Keys' cubic, `a =
//! -0.5`) resize of a `(B, C, H, W)` batched grid, the pure-MLX fallback
//! `mlx-vlm` uses when no Metal kernel is available
//! (`mlx-vlm/mlx_vlm/models/kernels.py`'s `_bicubic_interpolate_mlx`). The
//! LFM2.5-VL SigLIP2 vision tower resizes its learned position-embedding grid
//! per image with this (`vision.py`'s `resize_positional_embeddings`).
//!
//! This is the resize SigLIP2 NaFlex (and other native-resolution ViTs)
//! use to stretch a learned position-embedding grid from its trained
//! square shape (e.g. `16 x 16`) to a per-image patch grid
//! `(H_patch, W_patch)`. HF's
//! `Siglip2VisionEmbeddings.resize_positional_embeddings` resizes with
//! `F.interpolate(..., mode="bilinear", align_corners=False,
//! antialias=True)`, and the future LFM2.5-VL SigLIP2 vision tower uses the
//! same kernel, so the primitive lives in [`crate::ops`] — not inside the
//! model code — so independent vision ports can share it without coupling
//! their model implementations.
//!
//! ## Why on-device (MLX), not a NEON/SIMD kernel
//!
//! The interpolation runs through MLX ([`matmul`] over precomputed
//! weight matrices), so it executes on the active MLX device (GPU on
//! Apple silicon) alongside the rest of the vision graph. A hand-rolled
//! CPU/NEON kernel is deliberately **not** used here: the position-embed
//! grid is already a device [`Array`], so a CPU path would force a
//! device→host→device round-trip purely to interpolate a tiny grid,
//! which would dominate the cost. Only the constant triangle-weight tables
//! are built on the host (a few hundred `f32`); the actual resampling is
//! two device matmuls. (Contrast the NaFlex *image* resize, which starts
//! from host RGB bytes and therefore correctly reuses the NEON
//! `vlm::resize`.)
//!
//! ## Algorithm (separable bilinear + antialias, `align_corners=False`)
//!
//! Bilinear interpolation is separable: a 2-D resize equals a 1-D resize
//! along each axis. PyTorch's antialias path (the `aa_filter` triangle in
//! `UpSampleKernel.cpp`) builds, per output index `i` on an axis of length
//! `out` resampling an input axis of length `in`:
//!
//! ```text
//! scale = in / out (align_corners=False)
//! center = scale * (i + 0.5) (NO half-pixel -0.5 shift)
//! support = scale >= 1 ? scale : 1 (interp_size = 2 ⇒ *0.5)
//! invscale = scale >= 1 ? 1 / scale : 1
//! xmin = max(floor(center - support + 0.5), 0)
//! xmax = min(floor(center + support + 0.5), in)
//! ```
//!
//! and for each input tap `t` in `xmin..xmax` the (unnormalized) weight is
//! the triangle filter `f((t - center + 0.5) * invscale)` with
//! `f(x) = max(0, 1 - |x|)`. The taps are then **renormalized** to sum to
//! `1` (PyTorch divides each by their total). This produces a dense
//! `(out, in)` weight matrix `W` per axis, and the resize is
//! `W_h · X · W_wᵀ` contracted over the two spatial axes via [`matmul`].
//!
//! - When **downsampling** (`scale > 1`) the support is stretched by
//! `scale`, so the filter averages over a wider neighbourhood — this is
//! the antialiasing, and where the result differs from a plain 2-tap
//! bilinear.
//! - When **upsampling** (`scale <= 1`) `support = 1`, `invscale = 1`, and
//! the two-tap weights already sum to `1`, so the renormalization is a
//! no-op and the result is exactly plain bilinear `align_corners=False`.
//!
//! Off-edge taps are excluded by the `[0, in]` clamp on `xmin`/`xmax` (the
//! kernel narrows the window at the borders and renormalizes the surviving
//! taps), matching PyTorch. Byte-level agreement with the oracle is
//! confirmed numerically only by the gated SigLIP2 e2e parity test (the
//! hand-computed unit cases below pin the weight formula on small grids).
use crate::;
/// Upper bound on either output spatial dimension. The bilinear weight
/// matrices are dense (`out * in` `f32`), built on the host before the
/// device matmuls; this caps the host build (and the device matmul
/// shapes) so a hostile / mis-derived `(out_h, out_w)` cannot drive an
/// unbounded host allocation. A position-embed grid resize is at most a
/// few thousand patches per side in any realistic ViT, so `4096` is far
/// above any legitimate use while still bounding the `out * in` product
/// well within `i32` for the matmul.
const MAX_INTERP_DIM: usize = 4096;
/// Upper bound on the element count of a single `(out, in)` weight table.
///
/// The per-axis [`MAX_INTERP_DIM`] cap alone permits an `out * in` product up
/// to `MAX_INTERP_DIM^2` (≈ 16 Mi `f32` ≈ 64 MiB) for one table — large enough
/// that an infallible `vec![0.0f32; total]` would abort on allocator pressure.
/// A real position-embed resize is a `16 x 16` grid stretched to a few-thousand
/// patch grid, so one weight table is at most a few thousand `f32`; `1 << 22`
/// (4 Mi elements) is far above any legitimate use yet keeps an over-product a
/// recoverable [`Error::CapExceeded`] *before* the allocation, tighter than the
/// `MAX_INTERP_DIM^2` the per-axis caps would otherwise allow.
const MAX_INTERP_WEIGHT_ELEMS: usize = 1 << 22;
/// Upper bound on the element count of any **resample intermediate / output**
/// (a `dim * dim * C` device tensor in the separable matmul chain).
///
/// The per-axis [`MAX_INTERP_DIM`] and per-table [`MAX_INTERP_WEIGHT_ELEMS`]
/// caps bound the *weight matrices* but not the resampled tensors that thread the
/// channel axis `C` through the two matmuls: with each axis individually within
/// `MAX_INTERP_DIM` (e.g. `H_in = W_in = 4096`, `out_h = out_w = 1024`,
/// `C = 4096`) the first matmul output `out_h * W_in * C` is already ≈ 17 G
/// elements — an unbounded device allocation. This bounds each of the three
/// `*_count` products (row-resample, column-resample, final output) before any
/// device graph is built. A real position-embed resize is a `16 x 16 x hidden`
/// grid stretched to a few-thousand-patch grid (a few million elements at most),
/// so `1 << 26` (64 Mi elements ≈ 256 MiB `f32`) is far above any legitimate use
/// yet rejects the adversarial product as a typed [`Error::CapExceeded`] before
/// the matmul.
const MAX_INTERP_RESAMPLE_ELEMS: usize = 1 << 26;
/// PyTorch's antialias triangle (tent) filter `f(x) = max(0, 1 - |x|)`
/// (`HelperInterpLinear::aa_filter` in `aten`'s `UpSampleKernel.cpp`).
/// Evaluated in `f64` for the host-side weight build; the resulting
/// per-axis weights are cast to the grid dtype before the device matmul.
/// Build the dense `(out, in)` bilinear+antialias resampling weight matrix
/// for one axis, as a row-major `Vec<f32>` of length `out * in`.
///
/// Implements PyTorch's `UpSampleKernel.cpp` antialias linear path exactly
/// (see the module docs): per output row `i`, the source `center =
/// scale * (i + 0.5)` (no `-0.5` shift — antialias bakes the half-pixel
/// into the `+0.5` inside the filter argument), a `support` stretched by
/// `scale` when downsampling, the `[0, in]`-clamped tap window
/// `xmin..xmax`, the triangle filter at `(t - center + 0.5) * invscale`,
/// and a per-row renormalization so the surviving taps sum to `1`.
///
/// `in_dim` and `out_dim` are both `>= 1` (guaranteed by the caller).
/// Reject a spatial dimension outside `[1, MAX_INTERP_DIM]`.
/// Bilinear-resize (with antialias) a 2-D spatial grid from `(H_in, W_in, C)`
/// to `(out_h, out_w, C)`, matching PyTorch
/// `F.interpolate(mode="bilinear", align_corners=False, antialias=True)`.
///
/// `grid` is a rank-3 `(H_in, W_in, C)` float array — the layout SigLIP2
/// reshapes its `(num_positions, embed_dim)` position-embedding table
/// into before resampling (`H_in == W_in == sqrt(num_positions)`,
/// `C == embed_dim`). The channel axis is interpolated independently
/// (the resize is purely spatial). The output is a fresh
/// `(out_h, out_w, C)` array in the **same dtype** as `grid` (the weight
/// matrices are cast to `grid.dtype()` before the matmuls, so an
/// f16/bf16 grid stays in its dtype — no silent f32 promotion).
///
/// The resize is computed as two [`matmul`]s by the separable identity
/// `out = W_h · grid · W_wᵀ`:
/// - `W_h` is the `(out_h, H_in)` row-resampling matrix,
/// - `W_w` is the `(out_w, W_in)` column-resampling matrix,
///
/// each built from the antialias triangle filter at the half-pixel source
/// coordinates (see the module docs). Both matmuls run on the active MLX
/// device.
///
/// ## Errors
/// - `grid` is not rank-3 → [`Error::RankMismatch`].
/// - any of `H_in`, `W_in`, `out_h`, `out_w` is `0`, or `out_h` / `out_w`
/// exceeds the dense-weight-matrix cap (`MAX_INTERP_DIM`, 4096) →
/// [`Error::OutOfRange`] / [`Error::CapExceeded`].
/// - either axis's `out * in` weight-table element count exceeds the tighter
/// product cap (`MAX_INTERP_WEIGHT_ELEMS`) → [`Error::CapExceeded`]; or the
/// (fallible) weight-buffer reservation exceeds available memory →
/// [`Error::AllocFailure`].
/// - any resample tensor's element count — the row-resample `out_h * W_in * C`,
/// the column-resample `out_w * out_h * C`, or the output `out_h * out_w * C`
/// — exceeds the resample cap (`MAX_INTERP_RESAMPLE_ELEMS`), even though every
/// axis is within `MAX_INTERP_DIM` → [`Error::CapExceeded`] (rejected before
/// any device array / matmul is built).
/// - `grid`'s dtype is non-floating (the triangle weights are fractional;
/// an integer grid would truncate every sample) →
/// [`Error::UnsupportedDtype`].
/// - underlying [`matmul`] / [`reshape`] / [`transpose_axes`] /
/// [`astype`] errors propagate (e.g. a non-finite grid value flows
/// through unchanged — interpolation is linear in the samples).
// ───────────────────────────── bicubic ─────────────────────────────
/// The bicubic tap count for one resampled axis: `int(2 * support + 1)` with
/// `support = 2.0`. A `support = 2` cubic spans the two input pixels on each side
/// of the source coordinate, so each output row reads `5` candidate taps. The
/// four taps `floor-1..floor+2` are the active window (PyTorch's bicubic uses
/// exactly these four; `mlx-vlm`'s `_bicubic_interpolate_mlx` uses the same
/// support-2 window); the fifth tap (`floor+3`, distance `∈ (2, 3]`) is always
/// zero-weighted by the cubic kernel, and off-grid taps are clamp-folded onto a
/// valid index. Both bicubic paths (mlx-vlm Keys' `a = -0.5` and PyTorch's
/// `A = -0.75`) share this 5-candidate layout.
const BICUBIC_TAPS: usize = 5;
/// Cubic-convolution coefficient for the `mlx-vlm` / SigLIP2 bicubic path
/// (`kernels.py`'s `_cubic_weight`): Keys' cubic with `a = -0.5`.
const CUBIC_A_KEYS: f64 = -0.5;
/// Cubic-convolution coefficient for PyTorch's bicubic path
/// (`torch.nn.functional.interpolate(mode="bicubic")`): `A = -0.75`, the value
/// `get_cubic_upsample_coefficients` hard-codes in
/// `aten/src/ATen/native/UpSample.h`. This is the kernel HF CLAP's
/// `reshape_mel2img` resize runs through (it calls PyTorch bicubic), so the CLAP
/// `align_corners=True` path must use this coefficient, not Keys' `-0.5`.
const CUBIC_A_PYTORCH: f64 = -0.75;
/// Two-piece cubic convolution kernel parameterized by the coefficient `A`,
/// evaluated in `f64` for the host-side weight build:
///
/// ```text
/// w(t) = (A+2)|t|^3 - (A+3)|t|^2 + 1 for |t| <= 1
/// A|t|^3 - 5A|t|^2 + 8A|t| - 4A for 1 < |t| < 2
/// 0 for |t| >= 2
/// ```
///
/// The `|t| <= 1` branch is PyTorch's `cubic_convolution1(|t|, A)` and the
/// `1 < |t| < 2` branch its `cubic_convolution2(|t|, A)`
/// (`aten/src/ATen/native/UpSample.h`); with `A = -0.5` it is Keys' cubic
/// (`kernels.py`'s `_cubic_weight`), with `A = -0.75` it is PyTorch's bicubic
/// kernel. Both forms are a partition of unity over the four `floor-1..floor+2`
/// taps, so the four in-window coefficients sum to `1` for any source phase.
/// How a bicubic axis builder handles taps that fall outside `[0, in_dim)`.
///
/// The two reference bicubic implementations differ ONLY here (the kernel form,
/// the 5-tap window, and the index clamp are shared):
/// Build the `(out_dim, BICUBIC_TAPS)` per-axis resampling tables for the
/// bicubic `align_corners=False`, `antialias=False` path — `kernels.py`'s
/// `_weights_1d` specialized to `support = 2.0`, `fs = 1.0`.
///
/// Returns `(pix, weights)` flattened row-major:
/// - `pix[i * TAPS + k]` is the (clamped-to-`[0, in_dim)`) source index of the
/// `k`-th tap of output row `i`;
/// - `weights[i * TAPS + k]` is its (renormalized) cubic weight.
///
/// The source coordinate is the half-pixel center `c = (i + 0.5) / out * in -
/// 0.5`; the first tap starts at `floor(c - support) + 1`; out-of-bounds taps
/// are zero-weighted (and their index clamped so the on-device gather only ever
/// reads a valid row), then the surviving weights are renormalized to sum to 1
/// (matching `_weights_1d`'s `w / (sum(w) + 1e-8)`). `in_dim`, `out_dim >= 1`.
/// Build the `(out_dim, BICUBIC_TAPS)` per-axis resampling tables for the
/// bicubic **`align_corners=True`**, `antialias=False` path — PyTorch
/// `nn.functional.interpolate(mode="bicubic", align_corners=True)` (the variant
/// HF CLAP's `reshape_mel2img` uses to stretch the mel spectrogram's time axis).
///
/// This is a faithful port of PyTorch's bicubic, NOT the mlx-vlm Keys' variant,
/// so it differs from [`build_bicubic_axis`] in two ways:
///
/// 1. **Coefficient**: the cubic uses `A = -0.75` ([`CUBIC_A_PYTORCH`], the value
/// `get_cubic_upsample_coefficients` hard-codes in
/// `aten/src/ATen/native/UpSample.h`), not Keys' `-0.5`.
/// 2. **Source-coordinate map**: `align_corners=True` aligns the input/output
/// endpoints exactly, so for an output axis of length `out > 1` the source
/// center is `c = i · (in − 1) / (out − 1)` (`i = 0 → 0`, `i = out − 1 →
/// in − 1`), with NO half-pixel `−0.5` shift. For `out == 1` PyTorch maps to
/// the single source coordinate `0` (it avoids the `out − 1 == 0` division).
///
/// The boundary handling is [`CubicBoundary::ReplicateEdge`] — PyTorch's
/// `upsample_get_value_bounded`
/// (`aten/src/ATen/native/cpu/UpSampleKernel.cpp`): an out-of-range tap keeps its
/// full cubic coefficient and reads the **replicated edge** pixel
/// (`data[clamp(x, 0, width-1)]`), with NO renormalization (the four
/// coefficients already sum to 1). The 5-tap window starting at `floor(c) − 1`
/// and the `[0, in_dim)` index clamp are shared with [`build_bicubic_axis`].
/// `in_dim`, `out_dim >= 1`.
/// Shared core for the two bicubic axis builders: given the cubic coefficient
/// `a`, the out-of-bounds `boundary` policy, and a `center(i)` that maps an
/// output index to its (fractional) source coordinate, build the
/// `(out_dim, BICUBIC_TAPS)` clamped-index + cubic-weight tables. The callers
/// differ ONLY in those three parameters (the `align_corners` coordinate map,
/// `A`, and the edge handling); the 5-tap window, the kernel form, and the
/// `[0, in_dim)` index clamp are identical.
///
/// In both modes the index is clamped to `[0, in_dim)` so the on-device gather
/// only ever reads a valid row. The weight handling differs per [`CubicBoundary`]:
/// - [`CubicBoundary::ZeroRenormalize`]: out-of-bounds taps are zero-weighted,
/// then the surviving weights are renormalized to sum to 1 (`w / (sum(w) +
/// 1e-8)`) — `kernels.py`'s `_weights_1d`.
/// - [`CubicBoundary::ReplicateEdge`]: every tap (in- or out-of-bounds) keeps its
/// full cubic coefficient, and the clamped index makes an out-of-bounds tap
/// read the replicated edge pixel; NO renormalization — PyTorch's
/// `upsample_get_value_bounded`. The four `floor-1..floor+2` cubic taps already
/// sum to 1, and the fifth (`floor+3`, distance `∈ (2, 3]`) is exactly
/// zero-weighted by the kernel, so the row sums to 1 without renormalizing.
/// Bicubic-resize a batched `(B, C, H_in, W_in)` grid to `(B, C, out_h,
/// out_w)`, matching `mlx-vlm`'s pure-MLX `_bicubic_interpolate_mlx`
/// (`align_corners=False`, `antialias=False`: Keys' cubic, `a = -0.5`).
///
/// This is the resize the LFM2.5-VL SigLIP2 vision tower applies to its learned
/// position-embedding grid per image (`vision.py`'s
/// `resize_positional_embeddings` calls `bicubic_interpolate(pos[None], size=(h,
/// w))`). Like `_bicubic_interpolate_mlx`, the resampling is separable: build a
/// `(out, TAPS)` cubic-weight table per axis (on the host), gather the candidate
/// taps along that axis, and contract over the taps. Height is resampled first,
/// then width — exactly the reference's two-stage `gather + sum`.
///
/// `x` is a rank-4 `(B, C, H_in, W_in)` float array; the output is
/// `(B, C, out_h, out_w)` in the **same dtype** as `x` (computed in `f32` and
/// cast back, mirroring the reference's `astype(float32)` / restore). The
/// channel and batch axes pass through untouched (the resize is purely spatial).
///
/// ## Errors
/// - `x` is not rank-4 → [`Error::RankMismatch`].
/// - any of `B`, `C`, `H_in`, `W_in`, `out_h`, `out_w` is `0` →
/// [`Error::OutOfRange`]; or exceeds the per-axis cap (`MAX_INTERP_DIM`, 4096)
/// → [`Error::CapExceeded`].
/// - a per-axis tap table (`out_dim * BICUBIC_TAPS`) exceeds
/// `MAX_INTERP_WEIGHT_ELEMS`, or any resample tensor — the height/width gather
/// (`B * C * out_h * TAPS * W_in`, `B * C * out_h * out_w * TAPS`), the
/// post-height intermediate, or the output — exceeds the resample cap
/// (`MAX_INTERP_RESAMPLE_ELEMS`), even with every axis within `MAX_INTERP_DIM`
/// → [`Error::CapExceeded`] (or [`Error::ArithmeticOverflow`] if the product
/// overflows `usize`), rejected before any host vector / device tensor is
/// built.
/// - `x`'s dtype is non-floating (the cubic weights are fractional; an integer
/// grid would truncate every sample) → [`Error::UnsupportedDtype`].
/// - underlying gather / reshape / reduce / cast op errors propagate (a
/// non-finite grid value flows through unchanged — interpolation is linear in
/// the samples).
/// Bicubic-resize a batched `(B, C, H_in, W_in)` grid to `(B, C, out_h, out_w)`
/// with **`align_corners=True`** — PyTorch
/// `nn.functional.interpolate(mode="bicubic", align_corners=True)`.
///
/// This is the resize HF CLAP's `ClapAudioEncoder.reshape_mel2img` applies to
/// the log-mel spectrogram before the patch-embed (it upsamples the time axis
/// from the mel frame count to `spec_size · freq_ratio` with `align_corners=True`
/// bicubic). It is a faithful port of PyTorch's bicubic, so it differs from the
/// mlx-vlm-flavored [`bicubic_interpolate`] in three ways (see the private
/// `build_bicubic_axis_aligned`): the cubic coefficient is PyTorch's `A = -0.75`
/// (not Keys' `-0.5`); the source-coordinate map aligns the endpoints with no
/// half-pixel shift; and out-of-range taps replicate the edge pixel with NO
/// renormalization (`upsample_get_value_bounded`) rather than zero-weight +
/// renormalize. The separable gather + cubic-weight contract, the dtype handling,
/// the bounds, and the errors are identical.
///
/// `x` is a rank-4 `(B, C, H_in, W_in)` float array; the output is
/// `(B, C, out_h, out_w)` in the **same dtype** as `x` (computed in `f32` and
/// cast back). The channel and batch axes pass through untouched.
///
/// ## Errors
/// Identical to [`bicubic_interpolate`]: rank ≠ 4 → [`Error::RankMismatch`]; a
/// zero spatial dim → [`Error::OutOfRange`]; an over-cap dimension or resample
/// tensor → [`Error::CapExceeded`] / [`Error::ArithmeticOverflow`]; a
/// non-floating dtype → [`Error::UnsupportedDtype`]; underlying gather / reshape
/// / reduce / cast errors propagate.
/// The shared separable-bicubic resample, parameterized by the per-axis weight
/// builder (`align_corners` false vs true). Validates the rank / spatial dims /
/// dtype, then resamples height (axis 2) and width (axis 3) via a `gather +
/// weighted sum` over the `BICUBIC_TAPS` candidate taps — the two-stage
/// reference path mlx-vlm's `_bicubic_interpolate_mlx` uses.