rusting_brain 5.0.0

A Rust deep-learning library for training and running transformer language models, dense and mixture-of-experts, on CPU or CUDA.
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
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
//! The CLIP image tower, frozen, as a source of conditioning tokens.
//!
//! [`crate::clip`] is the text half of the same model and [`crate::vision`] is
//! a vision transformer trained from scratch. Neither is this one.
//! `crate::vision` uses RMSNorm, rotary positions and mean pooling, so it
//! cannot read a published CLIP checkpoint; this module reads one and runs it
//! forward, which is all an image-to-3D pipeline needs, because the tower is
//! frozen and never sees a gradient.
//!
//! The tower is: a patch embedding, a class token, a learned position table, a
//! layer norm, twelve of [`crate::clip`]'s layers with attention that is not
//! causal, and a final layer norm. [`VitEncoder::encode`] returns every token,
//! `[patches + 1, d_model]`, with no pooling and no projection head: a
//! cross-attention condition wants the whole grid, and the class token at row 0
//! is there for a caller that wants a single vector too.
//!
//! NOTE: the patch embedding is a convolution in the checkpoint, with the
//! kernel the same size as the stride. That makes it a linear map of the pixels
//! in each patch, so the `[d_model, channels, patch, patch]` weight is read as
//! `[d_model, channels * patch * patch]` and run through [`Dense`] instead of
//! [`Conv2d`](crate::conv::Conv2d). Same arithmetic, no convolution.
//!
//! Inference only. With the `cuda` feature, [`VitEncoder::attach_device`] moves
//! the tower onto a card and [`VitEncoder::encode_batch`] runs many images as
//! one stack there, which is what a corpus of a hundred thousand images needs.

use crate::clip::{Layer, Norm, dense, norm, run_layer};
use crate::conv::{Dense, FeatureMap};
use crate::matrix::Matrix;
use crate::network::NetworkError;
use crate::safetensors::ShardedSafeTensors;
use crate::transformer::Precision;

/// The two things about an image tower that its weights do not state.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VitEncoderConfig {
    /// Query heads. CLIP's image towers use 64-wide heads throughout, so this
    /// is `d_model / 64`: 12 for ViT-B, 16 for ViT-L.
    pub num_heads: usize,
    /// LayerNorm epsilon, `1e-5` in every published tower.
    pub eps: f32,
    /// `x * sigmoid(1.702x)` rather than the exact GELU. True for the OpenAI
    /// checkpoints and the ones converted from them.
    pub quick_gelu: bool,
}

impl Default for VitEncoderConfig {
    /// ViT-B/16.
    fn default() -> Self {
        Self {
            num_heads: 12,
            eps: 1e-5,
            quick_gelu: true,
        }
    }
}

/// A frozen CLIP image tower.
pub struct VitEncoder {
    config: VitEncoderConfig,
    /// `[d_model, channels * patch * patch]`, the convolution read flat.
    pub(crate) patch: Dense,
    class_token: Vec<f32>,
    /// `[patches + 1, d_model]`.
    positions: Matrix,
    /// CLIP's `pre_layrnorm`; DINOv2 has none.
    pub(crate) pre_norm: Option<Norm>,
    pub(crate) layers: Vec<Layer>,
    pub(crate) post_norm: Norm,
    /// `visual_projection`, which maps the class token into the space the
    /// text tower's pooled vector is projected to. Only full CLIP checkpoints
    /// carry it.
    projection: Option<Dense>,
    channels: usize,
    patch_size: usize,
    /// The exact GELU rather than [`VitEncoderConfig::quick_gelu`]'s pick,
    /// for DINOv2.
    pub(crate) exact_gelu: bool,
    /// The same weights on a CUDA device, when one was attached.
    #[cfg(feature = "cuda")]
    device: Option<crate::cuda_image::DeviceVitEncoder>,
}

impl VitEncoder {
    /// Reads a tower out of a checkpoint.
    ///
    /// `prefix` is what comes before `vision_model` in the tensor names: empty
    /// for a standalone CLIP checkpoint, something like `image_encoder.` where
    /// the tower is one model among several. Everything but
    /// [`VitEncoderConfig`] is taken from the shapes, so a ViT-L checkpoint
    /// loads by changing `num_heads` and nothing else.
    pub fn load<P: AsRef<std::path::Path>>(
        path: P,
        prefix: &str,
        config: VitEncoderConfig,
        precision: Precision,
    ) -> Result<Self, NetworkError> {
        let mut file = ShardedSafeTensors::open(path)?;
        Self::read_at(&mut file, prefix, config, precision)
    }

    /// The same, from a checkpoint that is already open.
    pub fn read_at(
        file: &mut ShardedSafeTensors,
        prefix: &str,
        config: VitEncoderConfig,
        precision: Precision,
    ) -> Result<Self, NetworkError> {
        if config.num_heads == 0 {
            return Err(NetworkError::InvalidConfig(
                "an image tower needs at least one attention head".into(),
            ));
        }
        // Transformers 5 saves `CLIPVisionModel` without `vision_model.`.
        let mut base = format!("{prefix}vision_model.");
        let patches = |base: &str| format!("{base}embeddings.patch_embedding.weight");
        if !file.names().any(|name| name == patches(&base)) {
            base = prefix.to_string();
        }

        let (values, shape) = file.tensor(&patches(&base))?;
        let [d_model, channels, patch_rows, patch_cols] = shape[..] else {
            return Err(NetworkError::InvalidConfig(format!(
                "the patch embedding is {shape:?}, which is not a convolution weight"
            )));
        };
        if patch_rows != patch_cols {
            return Err(NetworkError::InvalidConfig(format!(
                "the patch embedding reads a {patch_rows}x{patch_cols} patch, which is not square"
            )));
        }
        // No bias: the published towers train this convolution without one.
        let patch = Dense::new(
            Matrix::from_vec(d_model, channels * patch_rows * patch_cols, values),
            None,
        )?;

        let class_token = file.tensor(&format!("{base}embeddings.class_embedding"))?.0;
        if class_token.len() != d_model {
            return Err(NetworkError::InvalidTarget {
                expected: d_model,
                actual: class_token.len(),
            });
        }
        let positions = file.matrix(&format!("{base}embeddings.position_embedding.weight"))?;
        if positions.cols != d_model {
            return Err(NetworkError::InvalidConfig(format!(
                "the position table is {} wide and the patch embedding produces {d_model}",
                positions.cols
            )));
        }
        let patches = positions.rows - 1;
        // A square grid of patches plus the class token is the only layout the
        // flattening in `encode` knows how to undo.
        if patches.isqrt().pow(2) != patches || patches == 0 {
            return Err(NetworkError::InvalidConfig(format!(
                "the position table holds {} rows, which is not a square grid plus a class token",
                positions.rows
            )));
        }

        // Transformers shipped this one misspelled and kept the name for
        // compatibility, so both spellings are in the wild.
        let pre_norm = norm(file, &format!("{base}pre_layrnorm"))
            .or_else(|_| norm(file, &format!("{base}pre_layernorm")))?;

        let mut layers = Vec::new();
        while let Ok(layer) = read_layer(file, &base, layers.len(), precision) {
            layers.push(layer);
        }
        if layers.is_empty() {
            return Err(NetworkError::InvalidConfig(format!(
                "{base}encoder.layers.0 is missing, so this is not an image tower"
            )));
        }
        if d_model % config.num_heads != 0 {
            return Err(NetworkError::InvalidConfig(format!(
                "{} heads do not divide a width of {d_model}",
                config.num_heads
            )));
        }

        Ok(Self {
            post_norm: norm(file, &format!("{base}post_layernorm"))?,
            projection: file
                .matrix(&format!("{prefix}visual_projection.weight"))
                .ok()
                .map(|weight| Dense::new(weight, None))
                .transpose()?,
            config,
            patch,
            class_token,
            positions,
            pre_norm: Some(pre_norm),
            layers,
            channels,
            patch_size: patch_rows,
            exact_gelu: false,
            #[cfg(feature = "cuda")]
            device: None,
        })
    }

    /// A register-free DINOv2 tower as transformers saves `Dinov2Model`
    /// (`facebook/dinov2-small`, `-base`), for square images `image_size`
    /// pixels a side. The position table is resampled to that grid the way
    /// transformers' `interpolate_pos_encoding` does it, bicubic without
    /// corner alignment, and each layer's LayerScale is folded into the
    /// projection in front of it. [`VitEncoder::encode`] then returns the
    /// class token and the patch tokens through the final norm, which is
    /// transformers' `last_hidden_state`; normalize images with
    /// [`IMAGENET_MEAN`] and [`IMAGENET_STD`].
    pub fn load_dinov2<P: AsRef<std::path::Path>>(
        path: P,
        image_size: usize,
        precision: Precision,
    ) -> Result<Self, NetworkError> {
        let file = &mut ShardedSafeTensors::open(path)?;
        let (values, shape) = file.tensor("embeddings.patch_embeddings.projection.weight")?;
        let [d_model, channels, patch, patch_cols] = shape[..] else {
            return Err(NetworkError::InvalidConfig(format!(
                "the patch embedding is {shape:?}, which is not a convolution weight"
            )));
        };
        if patch != patch_cols || !image_size.is_multiple_of(patch) || image_size == 0 {
            return Err(NetworkError::InvalidConfig(format!(
                "{image_size}-pixel images do not split into {patch}x{patch_cols} patches"
            )));
        }
        let patch_embedding = Dense::new(
            Matrix::from_vec(d_model, channels * patch * patch, values),
            Some(
                file.tensor("embeddings.patch_embeddings.projection.bias")?
                    .0,
            ),
        )?;
        let class_token = file.tensor("embeddings.cls_token")?.0;
        let table = file.tensor("embeddings.position_embeddings")?.0;
        let table = Matrix::from_vec(table.len() / d_model.max(1), d_model, table);
        let mut layers = Vec::new();
        while let Ok(layer) = read_dinov2_layer(file, layers.len(), precision) {
            layers.push(layer);
        }
        let grid = (table.rows.max(1) - 1).isqrt();
        if layers.is_empty() || class_token.len() != d_model || grid * grid + 1 != table.rows {
            return Err(NetworkError::InvalidConfig(
                "this is not a DINOv2 checkpoint: no layers, a class token of another width \
                 or a position table that is not a square grid plus a class row"
                    .into(),
            ));
        }
        Ok(Self {
            config: VitEncoderConfig {
                num_heads: d_model / 64,
                eps: 1e-6,
                quick_gelu: false,
            },
            patch: patch_embedding,
            class_token,
            positions: resample_positions(&table, image_size / patch),
            pre_norm: None,
            layers,
            post_norm: norm(file, "layernorm")?,
            projection: None,
            channels,
            patch_size: patch,
            exact_gelu: true,
            #[cfg(feature = "cuda")]
            device: None,
        })
    }

    /// The configuration this tower was built for.
    pub fn config(&self) -> &VitEncoderConfig {
        &self.config
    }

    /// Uploads the tower to a CUDA device, and [`VitEncoder::encode`] and
    /// [`VitEncoder::encode_batch`] run there from now on.
    ///
    /// The device computes in FP16, so its tokens differ slightly from the
    /// host's. A failed upload leaves the tower on the CPU and returns the
    /// error; a failure later, during a pass, is returned too and never falls
    /// back to the CPU.
    #[cfg(feature = "cuda")]
    pub fn attach_device(
        &mut self,
        gpu: std::sync::Arc<crate::cuda_image::ImageGpu>,
    ) -> Result<(), NetworkError> {
        self.device = Some(crate::cuda_image::DeviceVitEncoder::upload(&gpu, self)?);
        Ok(())
    }

    /// Side of the square image the tower expects, in pixels.
    pub fn image_size(&self) -> usize {
        self.patch_size * (self.positions.rows - 1).isqrt()
    }

    /// Colour channels the tower expects, 3 in every published checkpoint.
    pub fn channels(&self) -> usize {
        self.channels
    }

    /// Width of one token.
    pub fn d_model(&self) -> usize {
        self.positions.cols
    }

    /// Tokens [`VitEncoder::encode`] returns: one per patch, plus the class
    /// token.
    pub fn tokens(&self) -> usize {
        self.positions.rows
    }

    /// Runs the tower and returns every token, `[tokens, d_model]`.
    ///
    /// Row 0 is the class token and the rest are the patches in row-major
    /// order. The final layer norm is applied to all of them, not to the class
    /// token alone: a condition that mixes normalized and unnormalized rows
    /// would make the cross-attention learn the difference for no reason.
    ///
    /// The image is expected already resized to [`VitEncoder::image_size`] and
    /// already normalized the way the checkpoint was trained, which for CLIP is
    /// per-channel `(pixel - mean) / std` over `[0, 1]` values; see
    /// [`CLIP_MEAN`] and [`CLIP_STD`].
    pub fn encode(&self, image: &FeatureMap) -> Result<Matrix, NetworkError> {
        #[cfg(feature = "cuda")]
        if self.device.is_some() {
            return Ok(self.encode_batch(std::slice::from_ref(image))?.remove(0));
        }

        let flat = self.flatten(image)?;
        let projected = self.patch.forward(&flat)?;
        let mut hidden = Matrix::new(self.positions.rows, self.d_model());
        hidden.row_mut(0).copy_from_slice(&self.class_token);
        for index in 0..projected.rows {
            hidden
                .row_mut(index + 1)
                .copy_from_slice(projected.row(index));
        }
        for index in 0..hidden.rows {
            for (value, learned) in hidden
                .row_mut(index)
                .iter_mut()
                .zip(self.positions.row(index))
            {
                *value += learned;
            }
        }

        if let Some(norm) = &self.pre_norm {
            hidden = norm.forward(&hidden, self.config.eps);
        }
        let activation = match (self.exact_gelu, self.config.quick_gelu) {
            (true, _) => crate::ffn::gelu_erf,
            (false, true) => crate::clip::quick_gelu_value,
            (false, false) => crate::ffn::gelu,
        };
        for layer in &self.layers {
            run_layer(
                layer,
                &mut hidden,
                self.config.num_heads,
                self.config.eps,
                activation,
                false,
            )?;
        }
        Ok(self.post_norm.forward(&hidden, self.config.eps))
    }

    /// [`VitEncoder::encode`] over several images, one token matrix each.
    ///
    /// On the host this is a loop. On a device the images run as one stack,
    /// `[images * tokens, d_model]`, so every projection is one GEMM over all
    /// of them, and only attention is split per image. The whole slice is one
    /// stack, so the caller picks the batch size by how many images it passes.
    pub fn encode_batch(&self, images: &[FeatureMap]) -> Result<Vec<Matrix>, NetworkError> {
        #[cfg(feature = "cuda")]
        if let Some(device) = self.device.as_ref().filter(|_| !images.is_empty()) {
            let tokens = self.tokens();
            let width = self.d_model();
            let mut patches = Matrix::new(images.len() * tokens, self.patch.in_dim());
            let mut embedding = Matrix::new(images.len() * tokens, width);
            for (index, image) in images.iter().enumerate() {
                let flat = self.flatten(image)?;
                let first = index * tokens;
                // Row `first` stays zero, so the class token gets no projection.
                let start = (first + 1) * flat.cols;
                patches.data[start..start + flat.data.len()].copy_from_slice(&flat.data);
                let rows = first * width..(first + tokens) * width;
                embedding.data[rows].copy_from_slice(&self.positions.data);
                for (value, class) in embedding.row_mut(first).iter_mut().zip(&self.class_token) {
                    *value += class;
                }
            }
            let stacked = device.forward(&patches, &embedding, tokens)?;
            return Ok(stacked
                .data
                .chunks_exact(tokens * width)
                .map(|image| Matrix::from_vec(tokens, width, image.to_vec()))
                .collect());
        }
        images.iter().map(|image| self.encode(image)).collect()
    }

    /// The image as one vector: the class token through the final norm, then
    /// through `visual_projection` when the checkpoint has one.
    ///
    /// With a full CLIP checkpoint this is the vector the text tower's
    /// [`pool`](crate::clip::ClipTextEncoder::pool) is compared with, by
    /// [`crate::clip::zero_shot`] or by cosine similarity for retrieval.
    pub fn embed(&self, image: &FeatureMap) -> Result<Vec<f32>, NetworkError> {
        let tokens = self.encode(image)?;
        match &self.projection {
            Some(projection) => projection.apply(tokens.row(0)),
            None => Ok(tokens.row(0).to_vec()),
        }
    }

    /// The image cut into patches, `[patches, channels * patch * patch]`, one
    /// row per patch in row-major order.
    fn flatten(&self, image: &FeatureMap) -> Result<Matrix, NetworkError> {
        let size = self.image_size();
        if image.channels != self.channels || image.height != size || image.width != size {
            return Err(NetworkError::InvalidConfig(format!(
                "the tower reads a {}x{size}x{size} image and this one is {}x{}x{}",
                self.channels, image.channels, image.height, image.width
            )));
        }

        let patch = self.patch_size;
        let grid = size / patch;
        let mut flat = Matrix::new(grid * grid, self.patch.in_dim());
        for row in 0..grid {
            for column in 0..grid {
                let target = flat.row_mut(row * grid + column);
                for channel in 0..self.channels {
                    for y in 0..patch {
                        let source = (channel * size + row * patch + y) * size + column * patch;
                        let start = (channel * patch + y) * patch;
                        target[start..start + patch]
                            .copy_from_slice(&image.data[source..source + patch]);
                    }
                }
            }
        }
        Ok(flat)
    }
}

/// Per-channel mean CLIP's images were normalized with, over `[0, 1]` pixels.
pub const CLIP_MEAN: [f32; 3] = [0.481_454_82, 0.457_827_5, 0.408_210_74];
/// Per-channel standard deviation to match [`CLIP_MEAN`].
pub const CLIP_STD: [f32; 3] = [0.268_629_54, 0.261_302_6, 0.275_777_1];
/// Per-channel mean DINOv2's images were normalized with, over `[0, 1]` pixels.
pub const IMAGENET_MEAN: [f32; 3] = [0.485, 0.456, 0.406];
/// Per-channel standard deviation to match [`IMAGENET_MEAN`].
pub const IMAGENET_STD: [f32; 3] = [0.229, 0.224, 0.225];

/// Composites an RGBA image onto one flat colour and normalizes it for the
/// tower.
///
/// Renders of a 3D asset come out with an alpha channel, and the tower has
/// three input channels. Compositing is the cheap answer; training a fourth
/// weight column would mean unfreezing the tower.
///
/// `pixels` is `[r, g, b, a]` per pixel in row-major order with values in
/// `[0, 1]`, which is what an image decoder gives after dividing by 255.
pub fn composite_rgba(
    pixels: &[f32],
    size: usize,
    background: [f32; 3],
) -> Result<FeatureMap, NetworkError> {
    if pixels.len() != size * size * 4 {
        return Err(NetworkError::InvalidTarget {
            expected: size * size * 4,
            actual: pixels.len(),
        });
    }
    let mut map = FeatureMap::new(3, size, size);
    for (index, pixel) in pixels.as_chunks::<4>().0.iter().enumerate() {
        let alpha = pixel[3];
        for channel in 0..3 {
            let composited = pixel[channel] * alpha + background[channel] * (1.0 - alpha);
            map.data[channel * size * size + index] =
                (composited - CLIP_MEAN[channel]) / CLIP_STD[channel];
        }
    }
    Ok(map)
}

/// Decodes, resizes and normalizes one image the way a CLIP tower was trained.
///
/// `size` is [`VitEncoder::image_size`] and `background` is the grey level a
/// transparent pixel is composited onto, which for a render on white is 1.0.
///
/// This is the one place the `image` crate is used for reading, so a caller
/// that already has pixels builds a [`FeatureMap`] itself or goes through
/// [`composite_rgba`].
#[cfg(feature = "images")]
pub fn read_image<P: AsRef<std::path::Path>>(
    path: P,
    size: usize,
    background: f32,
) -> Result<FeatureMap, NetworkError> {
    let path = path.as_ref();
    let decoded = image::open(path)
        .map_err(|error| NetworkError::InvalidDataset(format!("{}: {error}", path.display())))?;
    let side = size as u32;
    let decoded = decoded.resize_exact(side, side, image::imageops::FilterType::CatmullRom);

    // A render of a 3D asset is usually cut out, and the tower has three input
    // channels, so the alpha is composited rather than fed.
    if decoded.color().has_alpha() {
        let rgba: Vec<f32> = decoded
            .to_rgba8()
            .iter()
            .map(|&value| f32::from(value) / 255.0)
            .collect();
        return composite_rgba(&rgba, size, [background; 3]);
    }

    let mut map = FeatureMap::new(3, size, size);
    for (index, pixel) in decoded.to_rgb8().pixels().enumerate() {
        for channel in 0..3 {
            map.data[channel * size * size + index] =
                (f32::from(pixel[channel]) / 255.0 - CLIP_MEAN[channel]) / CLIP_STD[channel];
        }
    }
    Ok(map)
}

/// The class row then a square grid of positions, the grid resampled to
/// `grid` a side as PyTorch's bicubic `interpolate` with `align_corners=False`
/// does it (A = -0.75, edge rows repeated).
fn resample_positions(table: &Matrix, grid: usize) -> Matrix {
    let (from, width) = ((table.rows - 1).isqrt(), table.cols);
    if from == grid {
        return table.clone();
    }
    let cubic = |x: f32| {
        const A: f32 = -0.75;
        match x.abs() {
            x if x <= 1.0 => ((A + 2.0) * x - (A + 3.0)) * x * x + 1.0,
            x => ((A * x - 5.0 * A) * x + 8.0 * A) * x - 4.0 * A,
        }
    };
    let scale = from as f32 / grid as f32;
    // Each output index's four source indices and weights.
    let taps: Vec<[(usize, f32); 4]> = (0..grid)
        .map(|out| {
            let real = scale * (out as f32 + 0.5) - 0.5;
            let floor = real.floor();
            let t = real - floor;
            std::array::from_fn(|k| {
                let index = (floor as isize + k as isize - 1).clamp(0, from as isize - 1);
                (index as usize, cubic(t + 1.0 - k as f32))
            })
        })
        .collect();
    let mut out = Matrix::new(grid * grid + 1, width);
    out.row_mut(0).copy_from_slice(table.row(0));
    for y in 0..grid {
        for x in 0..grid {
            let target = out.row_mut(1 + y * grid + x);
            for &(sy, wy) in &taps[y] {
                let mut row = vec![0.0f32; width];
                for &(sx, wx) in &taps[x] {
                    for (r, v) in row.iter_mut().zip(table.row(1 + sy * from + sx)) {
                        *r += wx * v;
                    }
                }
                for (t, r) in target.iter_mut().zip(row) {
                    *t += wy * r;
                }
            }
        }
    }
    out
}

/// A DINOv2 layer as a CLIP one: the same pre-norm attention and MLP, with
/// each LayerScale multiplied into the projection it scales.
fn read_dinov2_layer(
    file: &mut ShardedSafeTensors,
    index: usize,
    precision: Precision,
) -> Result<Layer, NetworkError> {
    let layer = format!("encoder.layer.{index}");
    let scaled = |file: &mut ShardedSafeTensors, name: &str, scale: &str| {
        let mut dense = dense(file, name, Precision::F32)?;
        let lambda = file.tensor(scale)?.0;
        for (row, &l) in lambda.iter().enumerate() {
            dense.weight.row_mut(row).iter_mut().for_each(|w| *w *= l);
        }
        if let Some(bias) = &mut dense.bias {
            bias.iter_mut().zip(&lambda).for_each(|(b, l)| *b *= l);
        }
        if precision == Precision::Q8 {
            dense.quantize();
        }
        Ok::<_, NetworkError>(dense)
    };
    Ok(Layer {
        attention_norm: norm(file, &format!("{layer}.norm1"))?,
        query: dense(
            file,
            &format!("{layer}.attention.attention.query"),
            precision,
        )?,
        key: dense(file, &format!("{layer}.attention.attention.key"), precision)?,
        value: dense(
            file,
            &format!("{layer}.attention.attention.value"),
            precision,
        )?,
        output: scaled(
            file,
            &format!("{layer}.attention.output.dense"),
            &format!("{layer}.layer_scale1.lambda1"),
        )?,
        mlp_norm: norm(file, &format!("{layer}.norm2"))?,
        mlp_in: dense(file, &format!("{layer}.mlp.fc1"), precision)?,
        mlp_out: scaled(
            file,
            &format!("{layer}.mlp.fc2"),
            &format!("{layer}.layer_scale2.lambda1"),
        )?,
    })
}

fn read_layer(
    file: &mut ShardedSafeTensors,
    base: &str,
    index: usize,
    precision: Precision,
) -> Result<Layer, NetworkError> {
    let layer = format!("{base}encoder.layers.{index}");
    Ok(Layer {
        attention_norm: norm(file, &format!("{layer}.layer_norm1"))?,
        query: dense(file, &format!("{layer}.self_attn.q_proj"), precision)?,
        key: dense(file, &format!("{layer}.self_attn.k_proj"), precision)?,
        value: dense(file, &format!("{layer}.self_attn.v_proj"), precision)?,
        output: dense(file, &format!("{layer}.self_attn.out_proj"), precision)?,
        mlp_norm: norm(file, &format!("{layer}.layer_norm2"))?,
        mlp_in: dense(file, &format!("{layer}.mlp.fc1"), precision)?,
        mlp_out: dense(file, &format!("{layer}.mlp.fc2"), precision)?,
    })
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use std::collections::BTreeMap;

    const D_MODEL: usize = 8;
    const PATCH: usize = 2;
    const GRID: usize = 3;
    const LAYERS: usize = 2;

    /// A tower whose every residual branch is zeroed, so the layers are the
    /// identity and the output is the embedding through the two norms. That
    /// gives the forward pass a reference to be checked against rather than
    /// only a shape.
    pub(crate) fn checkpoint(path: &std::path::Path, identity_layers: bool) {
        let mut tensors: BTreeMap<String, (Vec<usize>, Vec<f32>)> = BTreeMap::new();
        let mut add = |name: String, shape: Vec<usize>, zero: bool| {
            let count = shape.iter().product::<usize>();
            let values = (0..count)
                .map(|index| match zero {
                    true => 0.0,
                    false => ((index % 11) as f32 - 5.0) * 0.05,
                })
                .collect();
            tensors.insert(name, (shape, values));
        };

        add(
            "vision_model.embeddings.patch_embedding.weight".into(),
            vec![D_MODEL, 3, PATCH, PATCH],
            false,
        );
        add(
            "vision_model.embeddings.class_embedding".into(),
            vec![D_MODEL],
            false,
        );
        add(
            "vision_model.embeddings.position_embedding.weight".into(),
            vec![GRID * GRID + 1, D_MODEL],
            false,
        );
        for name in ["pre_layrnorm", "post_layernorm"] {
            add(format!("vision_model.{name}.weight"), vec![D_MODEL], false);
            add(format!("vision_model.{name}.bias"), vec![D_MODEL], false);
        }
        for index in 0..LAYERS {
            let base = format!("vision_model.encoder.layers.{index}");
            for norm in ["layer_norm1", "layer_norm2"] {
                add(format!("{base}.{norm}.weight"), vec![D_MODEL], false);
                add(format!("{base}.{norm}.bias"), vec![D_MODEL], false);
            }
            for name in ["q_proj", "k_proj", "v_proj", "out_proj"] {
                let zero = identity_layers && name == "out_proj";
                add(
                    format!("{base}.self_attn.{name}.weight"),
                    vec![D_MODEL, D_MODEL],
                    zero,
                );
                add(format!("{base}.self_attn.{name}.bias"), vec![D_MODEL], zero);
            }
            add(
                format!("{base}.mlp.fc1.weight"),
                vec![D_MODEL * 2, D_MODEL],
                false,
            );
            add(format!("{base}.mlp.fc1.bias"), vec![D_MODEL * 2], false);
            add(
                format!("{base}.mlp.fc2.weight"),
                vec![D_MODEL, D_MODEL * 2],
                identity_layers,
            );
            add(
                format!("{base}.mlp.fc2.bias"),
                vec![D_MODEL],
                identity_layers,
            );
        }
        add("visual_projection.weight".into(), vec![4, D_MODEL], false);
        crate::safetensors::write_checkpoint(path, &tensors);
    }

    fn scratch(name: &str) -> std::path::PathBuf {
        std::env::temp_dir().join(format!(
            "rusting-brain-vit-{name}-{}.safetensors",
            std::process::id()
        ))
    }

    pub(crate) fn tiny() -> VitEncoderConfig {
        VitEncoderConfig {
            num_heads: 2,
            ..VitEncoderConfig::default()
        }
    }

    pub(crate) fn ramp(size: usize) -> FeatureMap {
        FeatureMap::from_vec(
            3,
            size,
            size,
            (0..3 * size * size)
                .map(|index| ((index % 7) as f32 - 3.0) * 0.1)
                .collect(),
        )
        .unwrap()
    }

    #[test]
    fn the_shape_is_read_out_of_the_checkpoint() {
        let path = scratch("shape");
        checkpoint(&path, false);
        let tower = VitEncoder::load(&path, "", tiny(), Precision::F32).unwrap();
        assert_eq!(tower.d_model(), D_MODEL);
        assert_eq!(tower.channels(), 3);
        assert_eq!(tower.image_size(), GRID * PATCH);
        assert_eq!(tower.tokens(), GRID * GRID + 1);

        let tokens = tower.encode(&ramp(tower.image_size())).unwrap();
        assert_eq!((tokens.rows, tokens.cols), (GRID * GRID + 1, D_MODEL));
        assert!(tokens.data.iter().all(|value| value.is_finite()));
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn a_tower_saved_without_its_vision_model_prefix_loads_alike() {
        let path = scratch("unprefixed");
        checkpoint(&path, false);
        let prefixed = VitEncoder::load(&path, "", tiny(), Precision::F32).unwrap();
        let mut file = crate::safetensors::SafeTensors::open(&path).unwrap();
        let names: Vec<String> = file.names().map(str::to_string).collect();
        let tensors: BTreeMap<String, (Vec<usize>, Vec<f32>)> = names
            .into_iter()
            .map(|name| {
                let (data, shape) = file.tensor(&name).unwrap();
                (
                    name.trim_start_matches("vision_model.").to_string(),
                    (shape, data),
                )
            })
            .collect();
        crate::safetensors::write_checkpoint(&path, &tensors);
        let unprefixed = VitEncoder::load(&path, "", tiny(), Precision::F32).unwrap();
        std::fs::remove_file(&path).ok();

        let image = ramp(prefixed.image_size());
        assert_eq!(
            unprefixed.encode(&image).unwrap().data,
            prefixed.encode(&image).unwrap().data
        );
    }

    #[test]
    fn the_embedding_is_the_projected_class_token() {
        let path = scratch("embed");
        checkpoint(&path, false);
        let tower = VitEncoder::load(&path, "", tiny(), Precision::F32).unwrap();
        let image = ramp(tower.image_size());
        let class = tower.encode(&image).unwrap().row(0).to_vec();
        let projection = tower.projection.as_ref().unwrap();

        let embedding = tower.embed(&image).unwrap();
        assert_eq!(embedding.len(), 4);
        for (unit, got) in embedding.iter().enumerate() {
            let want: f32 = projection
                .weight
                .row(unit)
                .iter()
                .zip(&class)
                .map(|(a, b)| a * b)
                .sum();
            assert!((got - want).abs() < 1e-5, "{got} against {want}");
        }
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn zeroed_residual_branches_leave_the_embedding_alone() {
        let path = scratch("identity");
        checkpoint(&path, true);
        let tower = VitEncoder::load(&path, "", tiny(), Precision::F32).unwrap();
        let size = tower.image_size();
        let image = ramp(size);
        let tokens = tower.encode(&image).unwrap();

        // The same embedding the forward pass builds, by hand: the class token
        // and the patch projections, each plus its learned position.
        let mut expected = Matrix::new(tower.tokens(), D_MODEL);
        expected.row_mut(0).copy_from_slice(&tower.class_token);
        for row in 0..GRID {
            for column in 0..GRID {
                let mut patch = Vec::new();
                for channel in 0..3 {
                    for y in 0..PATCH {
                        for x in 0..PATCH {
                            let index =
                                (channel * size + row * PATCH + y) * size + column * PATCH + x;
                            patch.push(image.data[index]);
                        }
                    }
                }
                let target = expected.row_mut(row * GRID + column + 1);
                for (unit, weight) in target.iter_mut().enumerate() {
                    *weight = tower
                        .patch
                        .weight
                        .row(unit)
                        .iter()
                        .zip(&patch)
                        .map(|(a, b)| a * b)
                        .sum();
                }
            }
        }
        for index in 0..expected.rows {
            for (value, learned) in expected
                .row_mut(index)
                .iter_mut()
                .zip(tower.positions.row(index))
            {
                *value += learned;
            }
        }
        let expected = tower
            .pre_norm
            .as_ref()
            .unwrap()
            .forward(&expected, tiny().eps);
        let expected = tower.post_norm.forward(&expected, tiny().eps);

        for (got, want) in tokens.data.iter().zip(&expected.data) {
            assert!((got - want).abs() < 1e-5, "{got} against {want}");
        }
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn an_image_of_the_wrong_size_is_refused() {
        let path = scratch("wrong-size");
        checkpoint(&path, false);
        let tower = VitEncoder::load(&path, "", tiny(), Precision::F32).unwrap();
        assert!(tower.encode(&ramp(tower.image_size() + PATCH)).is_err());
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn heads_that_do_not_divide_the_width_are_refused() {
        let path = scratch("bad-heads");
        checkpoint(&path, false);
        let config = VitEncoderConfig {
            num_heads: 3,
            ..tiny()
        };
        assert!(VitEncoder::load(&path, "", config, Precision::F32).is_err());
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn alpha_chooses_between_the_pixel_and_the_background() {
        let opaque = composite_rgba(&[0.5, 0.5, 0.5, 1.0], 1, [0.0, 0.0, 0.0]).unwrap();
        let clear = composite_rgba(&[0.5, 0.5, 0.5, 0.0], 1, [1.0, 1.0, 1.0]).unwrap();
        for channel in 0..3 {
            let expected = (0.5 - CLIP_MEAN[channel]) / CLIP_STD[channel];
            assert!((opaque.data[channel] - expected).abs() < 1e-6);
            let expected = (1.0 - CLIP_MEAN[channel]) / CLIP_STD[channel];
            assert!((clear.data[channel] - expected).abs() < 1e-6);
        }
        assert!(composite_rgba(&[0.0; 3], 1, [0.0; 3]).is_err());
    }

    /// Needs `RB_DINOV2_REF` from `scripts/dinov2_reference.py`.
    #[test]
    #[ignore]
    fn dinov2_matches_transformers() {
        let dir = std::path::PathBuf::from(std::env::var("RB_DINOV2_REF").unwrap());
        let paths: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(dir.join("reference.json")).unwrap())
                .unwrap();
        for name in ["small", "base"] {
            let tower = VitEncoder::load_dinov2(paths[name].as_str().unwrap(), 224, Precision::F32)
                .unwrap();
            let mut reference =
                crate::safetensors::SafeTensors::open(dir.join(format!("{name}.safetensors")))
                    .unwrap();
            let (pixels, _) = reference.tensor("pixels").unwrap();
            let (tokens, _) = reference.tensor("tokens").unwrap();
            let per_image = 3 * 224 * 224;
            let mut images = Vec::new();
            for image in 0..2 {
                let mut map = FeatureMap::new(3, 224, 224);
                map.data
                    .copy_from_slice(&pixels[image * per_image..(image + 1) * per_image]);
                images.push(map);
            }
            for (image, got) in images.iter().map(|m| tower.encode(m).unwrap()).enumerate() {
                let expected = &tokens[image * got.data.len()..(image + 1) * got.data.len()];
                // The patch rows, after the class token.
                let (got, expected) = (&got.data[got.cols..], &expected[got.cols..]);
                let scale = expected.iter().fold(0.0f32, |m, v| m.max(v.abs()));
                let gap = got
                    .iter()
                    .zip(expected)
                    .fold(0.0f32, |m, (a, b)| m.max((a - b).abs()));
                eprintln!("dinov2-{name} image {image}: gap {gap:e} at scale {scale}");
                assert!(
                    gap <= 1e-3 * scale,
                    "dinov2-{name}: gap {gap} at scale {scale}"
                );
            }
        }
    }
}