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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
//! The decoder that turns a diffusion model's latent into pixels.
//!
//! Every latent diffusion model — Stable Diffusion 1.x, SDXL, SD3, FLUX,
//! FLUX.2 — ends the same way: the sampler produces a small, many-channel
//! latent, and a convolutional decoder expands it to an image. The decoder is
//! the half of a variational autoencoder that runs at inference; the encoder
//! only matters for image-to-image work.
//!
//! The architecture below is the one `diffusers` calls `AutoencoderKL`, which
//! is what every checkpoint in that line ships: a stem convolution, a middle
//! pair of residual blocks with one self-attention between them, then a ladder
//! of residual blocks that doubles the resolution at each rung, and a final
//! normalize-activate-convolve to three channels.
//!
//! [`VaeDecoder::load`] reads such a checkpoint straight from
//! `.safetensors` under the `diffusers` key names, so hosting a published
//! decoder needs no conversion step.
//!
//! Inference only, like [`crate::conv`]: no gradients, no CUDA.

use crate::conv::{Conv2d, Dense, FeatureMap, GroupNorm, silu, upsample_nearest};
use crate::matrix::Matrix;
use crate::network::NetworkError;
use crate::safetensors::ShardedSafeTensors;

/// The shape of a decoder, which a checkpoint's `config.json` names.
#[derive(Clone, Debug, PartialEq)]
pub struct VaeConfig {
    /// Channels in the latent the sampler produces. Four for Stable Diffusion
    /// 1.x and XL, sixteen for SD3 and FLUX, thirty-two for FLUX.2.
    pub latent_channels: usize,
    /// Channels in the image. Three, unless something unusual is going on.
    pub out_channels: usize,
    /// Channels at each resolution, from the image's resolution inward, which
    /// is the order the checkpoint's own configuration lists them in.
    pub block_out_channels: Vec<usize>,
    pub layers_per_block: usize,
    pub norm_groups: usize,
    /// The latent's scale and offset, from the same configuration. A latent is
    /// stored as `(value - shift) * scaling`, so decoding undoes that first.
    pub scaling_factor: f32,
    pub shift_factor: f32,
    /// The epsilon of the batch norm FLUX.2 puts over the packed latent, see
    /// [`VaeDecoder::patch_norm`]. Unused by a VAE that has none.
    pub batch_norm_eps: f32,
}

impl Default for VaeConfig {
    /// The Stable Diffusion 1.x and XL decoder, which is the most common one.
    fn default() -> Self {
        Self {
            latent_channels: 4,
            out_channels: 3,
            block_out_channels: vec![128, 256, 512, 512],
            layers_per_block: 2,
            norm_groups: 32,
            scaling_factor: 0.18215,
            shift_factor: 0.0,
            batch_norm_eps: 1e-4,
        }
    }
}

impl VaeConfig {
    /// The FLUX.1 decoder: sixteen latent channels and the scale and shift
    /// that model was trained with. FLUX.2's has thirty-two channels and
    /// neither, and [`VaeConfig::from_file`] reads it from its own file.
    pub fn flux() -> Self {
        Self {
            latent_channels: 16,
            scaling_factor: 0.3611,
            shift_factor: 0.1159,
            ..Self::default()
        }
    }

    /// Reads a diffusers `vae/config.json`.
    pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self, NetworkError> {
        let text = std::fs::read_to_string(path)?;
        let json: serde_json::Value = serde_json::from_str(&text)
            .map_err(|error| NetworkError::InvalidDataset(format!("vae config.json: {error}")))?;

        let default = Self::default();
        let flux2 =
            json.get("_class_name").and_then(|name| name.as_str()) == Some("AutoencoderKLFlux2");
        let number = |name: &str, fallback: usize| -> usize {
            json.get(name)
                .and_then(|value| value.as_u64())
                .map_or(fallback, |value| value as usize)
        };
        let float = |name: &str, fallback: f32| -> f32 {
            json.get(name)
                .and_then(|value| value.as_f64())
                .map_or(fallback, |value| value as f32)
        };

        Ok(Self {
            latent_channels: number("latent_channels", default.latent_channels),
            out_channels: number("out_channels", default.out_channels),
            block_out_channels: match json
                .get("block_out_channels")
                .and_then(|value| value.as_array())
            {
                Some(channels) => channels
                    .iter()
                    .map(|count| count.as_u64().map(|count| count as usize))
                    .collect::<Option<Vec<_>>>()
                    .ok_or_else(|| {
                        NetworkError::InvalidDataset(
                            "vae config.json: block_out_channels is not a list of sizes".into(),
                        )
                    })?,
                None => default.block_out_channels,
            },
            layers_per_block: number("layers_per_block", default.layers_per_block),
            norm_groups: number("norm_num_groups", default.norm_groups),
            // FLUX.2's autoencoder normalizes its latent with a batch norm
            // over the packed patches instead, and records no scale at all;
            // the Stable Diffusion default would shrink its latent five times.
            scaling_factor: float(
                "scaling_factor",
                match flux2 {
                    true => 1.0,
                    false => default.scaling_factor,
                },
            ),
            // Only the models that need an offset record one.
            shift_factor: float("shift_factor", 0.0),
            batch_norm_eps: float("batch_norm_eps", default.batch_norm_eps),
        })
    }

    /// How much larger the image is than the latent: one doubling per rung of
    /// the ladder above the first.
    pub fn upscale(&self) -> usize {
        1 << (self.block_out_channels.len() - 1)
    }
}

/// Two convolutions with a skip connection, the unit the whole decoder is
/// built from.
#[derive(Clone, Debug)]
pub(crate) struct ResnetBlock {
    pub(crate) norm1: GroupNorm,
    pub(crate) conv1: Conv2d,
    pub(crate) norm2: GroupNorm,
    pub(crate) conv2: Conv2d,
    /// A one-by-one convolution on the skip path, present only where the block
    /// changes the channel count.
    pub(crate) shortcut: Option<Conv2d>,
}

impl ResnetBlock {
    fn forward(&self, input: &FeatureMap) -> Result<FeatureMap, NetworkError> {
        let mut hidden = input.clone();
        self.norm1.forward(&mut hidden)?;
        silu(&mut hidden);
        let mut hidden = self.conv1.forward(&hidden)?;
        self.norm2.forward(&mut hidden)?;
        silu(&mut hidden);
        let mut hidden = self.conv2.forward(&hidden)?;

        let skip = match &self.shortcut {
            Some(shortcut) => shortcut.forward(input)?,
            None => input.clone(),
        };
        if skip.data.len() != hidden.data.len() {
            return Err(NetworkError::InvalidTarget {
                expected: hidden.data.len(),
                actual: skip.data.len(),
            });
        }
        for (value, skip) in hidden.data.iter_mut().zip(&skip.data) {
            *value += skip;
        }
        Ok(hidden)
    }
}

/// Self-attention over pixels, which the decoder runs once at its lowest
/// resolution, where the pixel count is small enough for the quadratic cost.
#[derive(Clone, Debug)]
pub(crate) struct AttentionBlock {
    pub(crate) norm: GroupNorm,
    pub(crate) query: Dense,
    pub(crate) key: Dense,
    pub(crate) value: Dense,
    pub(crate) output: Dense,
}

impl AttentionBlock {
    fn forward(&self, input: &FeatureMap) -> Result<FeatureMap, NetworkError> {
        let mut normed = input.clone();
        self.norm.forward(&mut normed)?;
        let tokens = normed.to_tokens();

        let queries = self.query.forward(&tokens)?;
        let keys = self.key.forward(&tokens)?;
        let values = self.value.forward(&tokens)?;
        let attended = attend(&queries, &keys, &values);

        let projected = self.output.forward(&attended)?;
        let mut output = FeatureMap::from_tokens(&projected, input.height, input.width)?;
        for (value, skip) in output.data.iter_mut().zip(&input.data) {
            *value += skip;
        }
        Ok(output)
    }
}

/// Single-head softmax attention of every query row over every key row, the
/// scores scaled by one over the square root of the width.
pub(crate) fn attend(queries: &Matrix, keys: &Matrix, values: &Matrix) -> Matrix {
    let scale = (queries.cols as f32).sqrt().recip();
    let mut attended = Matrix::new(queries.rows, values.cols);
    let mut weights = vec![0.0; queries.rows];
    for pixel in 0..queries.rows {
        let query = queries.row(pixel);
        let mut largest = f32::NEG_INFINITY;
        for (weight, other) in weights.iter_mut().zip(0..queries.rows) {
            let score = query
                .iter()
                .zip(keys.row(other))
                .map(|(query, key)| query * key)
                .sum::<f32>()
                * scale;
            *weight = score;
            largest = largest.max(score);
        }
        let mut total = 0.0;
        for weight in &mut weights {
            *weight = (*weight - largest).exp();
            total += *weight;
        }
        let row = attended.row_mut(pixel);
        for (other, weight) in weights.iter().enumerate() {
            let weight = weight / total;
            for (value, source) in row.iter_mut().zip(values.row(other)) {
                *value += weight * source;
            }
        }
    }
    attended
}

/// One rung of the ladder: several residual blocks, then a doubling.
#[derive(Clone, Debug)]
pub(crate) struct UpBlock {
    pub(crate) resnets: Vec<ResnetBlock>,
    /// The convolution that follows the nearest-neighbour upsample. Absent on
    /// the last rung, which is already at the image's resolution.
    pub(crate) upsampler: Option<Conv2d>,
}

/// The decoder half of a latent diffusion model's autoencoder.
#[derive(Clone, Debug)]
pub struct VaeDecoder {
    config: VaeConfig,
    /// The one-by-one convolution the Stable Diffusion line puts between the
    /// latent and the decoder, mirroring the encoder's `quant_conv`. It lives
    /// beside `decoder.` rather than inside it, and the FLUX line has none.
    pub(crate) post_quant: Option<Conv2d>,
    /// FLUX.2's batch-norm statistics over the packed latent, as a mean and a
    /// standard deviation per packed channel. See [`VaeDecoder::patch_norm`].
    patch_norm: Option<(Vec<f32>, Vec<f32>)>,
    pub(crate) conv_in: Conv2d,
    pub(crate) mid_first: ResnetBlock,
    pub(crate) mid_attention: AttentionBlock,
    pub(crate) mid_last: ResnetBlock,
    pub(crate) up_blocks: Vec<UpBlock>,
    pub(crate) norm_out: GroupNorm,
    pub(crate) conv_out: Conv2d,
    /// The same weights on a CUDA device, when one was attached.
    #[cfg(feature = "cuda")]
    device: Option<std::sync::Arc<crate::cuda_image::DeviceVae>>,
}

impl VaeDecoder {
    /// The configuration this decoder was built for.
    pub fn config(&self) -> &VaeConfig {
        &self.config
    }

    /// The mean and standard deviation of every packed latent channel, for
    /// an autoencoder that normalizes its latent after packing it, which is
    /// FLUX.2's. A sampled latent is `(packed - mean) / std`, so a pipeline
    /// multiplies and adds these back before unpacking; the decoder itself
    /// never sees the packed form.
    pub fn patch_norm(&self) -> Option<(&[f32], &[f32])> {
        self.patch_norm
            .as_ref()
            .map(|(mean, std)| (mean.as_slice(), std.as_slice()))
    }

    /// Reads a decoder out of a checkpoint under the `diffusers` key names.
    ///
    /// `path` is either a `.safetensors` file or the
    /// `model.safetensors.index.json` of a sharded one. `prefix` is what the
    /// decoder's keys start with: `"decoder."` in a standalone VAE file, and
    /// `"vae.decoder."` in a checkpoint that holds the whole pipeline.
    pub fn load(
        path: impl AsRef<std::path::Path>,
        prefix: &str,
        config: VaeConfig,
    ) -> Result<Self, NetworkError> {
        let mut file = ShardedSafeTensors::open(path)?;
        Self::read(&mut file, prefix, config)
    }

    /// The same, from a checkpoint that is already open.
    pub fn read(
        file: &mut ShardedSafeTensors,
        prefix: &str,
        config: VaeConfig,
    ) -> Result<Self, NetworkError> {
        if config.block_out_channels.is_empty() {
            return Err(NetworkError::InvalidConfig(
                "a decoder needs at least one resolution".into(),
            ));
        }
        // The checkpoint lists channels from the image inward and runs them
        // outward, so the ladder is the reverse of the configuration.
        let ladder: Vec<usize> = config.block_out_channels.iter().rev().copied().collect();
        let deepest = ladder[0];

        // `post_quant_conv` sits one level up from the decoder's own keys.
        let root = prefix.strip_suffix("decoder.").unwrap_or("");
        let post_quant = read_conv(file, &format!("{root}post_quant_conv"), 1, 0).ok();
        let patch_norm = match (
            file.tensor(&format!("{root}bn.running_mean")),
            file.tensor(&format!("{root}bn.running_var")),
        ) {
            (Ok((mean, _)), Ok((variance, _))) => {
                let eps = config.batch_norm_eps;
                let std = variance.iter().map(|value| (value + eps).sqrt()).collect();
                Some((mean, std))
            }
            _ => None,
        };
        let conv_in = read_conv(file, &format!("{prefix}conv_in"), 1, 1)?;
        let mid = format!("{prefix}mid_block");
        let mid_first = read_resnet(file, &format!("{mid}.resnets.0"), config.norm_groups)?;
        let mid_attention =
            read_attention(file, &format!("{mid}.attentions.0"), config.norm_groups)?;
        let mid_last = read_resnet(file, &format!("{mid}.resnets.1"), config.norm_groups)?;

        let mut up_blocks = Vec::with_capacity(ladder.len());
        for (rung, _) in ladder.iter().enumerate() {
            let base = format!("{prefix}up_blocks.{rung}");
            // One more residual block per rung than the configuration's count,
            // which is the autoencoder's own asymmetry.
            let resnets = (0..config.layers_per_block + 1)
                .map(|index| {
                    read_resnet(file, &format!("{base}.resnets.{index}"), config.norm_groups)
                })
                .collect::<Result<Vec<_>, _>>()?;
            let upsampler = if rung + 1 < ladder.len() {
                Some(read_conv(file, &format!("{base}.upsamplers.0.conv"), 1, 1)?)
            } else {
                None
            };
            up_blocks.push(UpBlock { resnets, upsampler });
        }

        let norm_out =
            read_group_norm(file, &format!("{prefix}conv_norm_out"), config.norm_groups)?;
        let conv_out = read_conv(file, &format!("{prefix}conv_out"), 1, 1)?;

        // With a `post_quant_conv` in front, the stem reads what that
        // produces and the latent is what the convolution reads.
        let takes = post_quant
            .as_ref()
            .map_or(conv_in.in_channels, |quant| quant.in_channels);
        if takes != config.latent_channels || conv_in.out_channels() != deepest {
            return Err(NetworkError::InvalidConfig(format!(
                "the checkpoint's stem maps {} channels to {}, and the configuration says {} to \
                 {deepest}",
                takes,
                conv_in.out_channels(),
                config.latent_channels
            )));
        }

        Ok(Self {
            config,
            post_quant,
            patch_norm,
            conv_in,
            mid_first,
            mid_attention,
            mid_last,
            up_blocks,
            norm_out,
            conv_out,
            #[cfg(feature = "cuda")]
            device: None,
        })
    }

    /// Uploads every weight to a CUDA device and decodes there from now on.
    ///
    /// Fails closed, leaving the decoder on the CPU if the upload does not fit.
    #[cfg(feature = "cuda")]
    pub fn attach_device(
        &mut self,
        gpu: std::sync::Arc<crate::cuda_image::ImageGpu>,
    ) -> Result<(), NetworkError> {
        self.device = Some(std::sync::Arc::new(crate::cuda_image::DeviceVae::upload(
            &gpu, self,
        )?));
        Ok(())
    }

    /// Decodes a latent into an image whose values sit in roughly `[-1, 1]`.
    ///
    /// `latent` is what the sampler produced, in channel-height-width order and
    /// still carrying the model's scale and shift; both are undone here.
    pub fn decode(&self, latent: &FeatureMap) -> Result<FeatureMap, NetworkError> {
        if latent.channels != self.config.latent_channels {
            return Err(NetworkError::InvalidTarget {
                expected: self.config.latent_channels,
                actual: latent.channels,
            });
        }

        let mut scaled = latent.clone();
        for value in &mut scaled.data {
            *value = *value / self.config.scaling_factor + self.config.shift_factor;
        }

        #[cfg(feature = "cuda")]
        if let Some(device) = &self.device {
            // The device mirror starts at `post_quant`, so the scale and shift
            // above are the only arithmetic either path does on the host.
            return device.decode(&scaled);
        }

        let scaled = match &self.post_quant {
            Some(quant) => quant.forward(&scaled)?,
            None => scaled,
        };

        let mut hidden = self.conv_in.forward(&scaled)?;
        hidden = self.mid_first.forward(&hidden)?;
        hidden = self.mid_attention.forward(&hidden)?;
        hidden = self.mid_last.forward(&hidden)?;

        for block in &self.up_blocks {
            for resnet in &block.resnets {
                hidden = resnet.forward(&hidden)?;
            }
            if let Some(upsampler) = &block.upsampler {
                hidden = upsampler.forward(&upsample_nearest(&hidden, 2))?;
            }
        }

        self.norm_out.forward(&mut hidden)?;
        silu(&mut hidden);
        self.conv_out.forward(&hidden)
    }

    /// [`VaeDecoder::decode`] a tile at a time, so an image too large to
    /// decode in one piece fits in memory.
    ///
    /// The latent is cut into `tile` x `tile` squares that overlap their
    /// neighbours by `overlap` latent pixels, each square is decoded on its
    /// own, and the overlaps are blended with linear ramps so no seam shows.
    /// The middle self-attention and the group norms then see one tile rather
    /// than the whole image, so the result is close to, not equal to,
    /// [`VaeDecoder::decode`]; a latent no larger than `tile` decodes exactly.
    /// `overlap` must be smaller than `tile`; 64 and 8 are common.
    pub fn decode_tiled(
        &self,
        latent: &FeatureMap,
        tile: usize,
        overlap: usize,
    ) -> Result<FeatureMap, NetworkError> {
        if overlap >= tile {
            return Err(NetworkError::InvalidTarget {
                expected: tile.saturating_sub(1),
                actual: overlap,
            });
        }
        stitch_tiles(latent, tile, overlap, self.config.upscale(), |part| {
            self.decode(part)
        })
    }
}

/// Where tiles of length `tile`, overlapping by `overlap`, start along an
/// axis of length `len`. The last one ends flush with the axis.
fn tile_starts(len: usize, tile: usize, overlap: usize) -> Vec<usize> {
    if len <= tile {
        return vec![0];
    }
    let mut starts: Vec<usize> = (0..len - tile).step_by(tile - overlap).collect();
    starts.push(len - tile);
    starts
}

/// Weight of position `at` inside a tile of length `len` that starts at
/// `start` on an axis of length `axis`: a ramp across `ramp` positions at
/// each edge that borders another tile, and one elsewhere.
fn ramp_weight(at: usize, len: usize, start: usize, axis: usize, ramp: usize) -> f32 {
    let mut weight = 1.0f32;
    if start > 0 {
        weight = weight.min((at + 1) as f32 / (ramp + 1) as f32);
    }
    if start + len < axis {
        weight = weight.min((len - at) as f32 / (ramp + 1) as f32);
    }
    weight
}

/// Cuts `latent` into overlapping tiles, runs `decode` on each, and blends
/// the outputs, which are `scale` times the size of their tiles.
fn stitch_tiles(
    latent: &FeatureMap,
    tile: usize,
    overlap: usize,
    scale: usize,
    decode: impl Fn(&FeatureMap) -> Result<FeatureMap, NetworkError>,
) -> Result<FeatureMap, NetworkError> {
    let (height, width) = (latent.height * scale, latent.width * scale);
    let ramp = overlap * scale;
    let mut sum: Vec<f32> = Vec::new();
    let mut weights = vec![0.0f32; height * width];
    let mut channels = 0;
    for top in tile_starts(latent.height, tile, overlap) {
        for left in tile_starts(latent.width, tile, overlap) {
            let (rows, cols) = (tile.min(latent.height), tile.min(latent.width));
            let mut part = FeatureMap::new(latent.channels, rows, cols);
            for c in 0..latent.channels {
                for y in 0..rows {
                    let from = (c * latent.height + top + y) * latent.width + left;
                    let to = (c * rows + y) * cols;
                    part.data[to..to + cols].copy_from_slice(&latent.data[from..from + cols]);
                }
            }
            let out = decode(&part)?;
            if sum.is_empty() {
                channels = out.channels;
                sum = vec![0.0; channels * height * width];
            }
            for y in 0..out.height {
                let wy = ramp_weight(y, out.height, top * scale, height, ramp);
                for x in 0..out.width {
                    let w = wy * ramp_weight(x, out.width, left * scale, width, ramp);
                    let at = (top * scale + y) * width + left * scale + x;
                    weights[at] += w;
                    for c in 0..channels {
                        sum[c * height * width + at] +=
                            w * out.data[(c * out.height + y) * out.width + x];
                    }
                }
            }
        }
    }
    for (index, value) in sum.iter_mut().enumerate() {
        *value /= weights[index % (height * width)];
    }
    FeatureMap::from_vec(channels, height, width, sum)
}

/// One rung of the encoder's ladder: several residual blocks, then a halving.
#[derive(Clone, Debug)]
pub(crate) struct DownBlock {
    pub(crate) resnets: Vec<ResnetBlock>,
    /// The stride-two convolution that ends the rung. Absent on the last one,
    /// which is already at the latent's resolution.
    pub(crate) downsampler: Option<Conv2d>,
}

/// The encoder half of a latent diffusion model's autoencoder.
///
/// Only image-to-image work needs one: text-to-image starts from noise, and
/// the encoder is what turns a starting picture into the latent the sampler
/// then partially renoises. The architecture mirrors [`VaeDecoder`] — a stem,
/// a ladder that halves the resolution at each rung, and a middle pair of
/// residual blocks around one self-attention — and its keys sit under
/// `encoder.` in the same file.
#[derive(Clone, Debug)]
pub struct VaeEncoder {
    config: VaeConfig,
    pub(crate) conv_in: Conv2d,
    pub(crate) down_blocks: Vec<DownBlock>,
    pub(crate) mid_first: ResnetBlock,
    pub(crate) mid_attention: AttentionBlock,
    pub(crate) mid_last: ResnetBlock,
    pub(crate) norm_out: GroupNorm,
    pub(crate) conv_out: Conv2d,
    /// The one-by-one convolution some checkpoints put between the encoder and
    /// the latent. It lives beside `encoder.` rather than inside it.
    pub(crate) quant: Option<Conv2d>,
    /// The same weights on a CUDA device, when one was attached.
    #[cfg(feature = "cuda")]
    device: Option<std::sync::Arc<crate::cuda_image::DeviceVaeEncoder>>,
}

impl VaeEncoder {
    /// The configuration this encoder was built for.
    pub fn config(&self) -> &VaeConfig {
        &self.config
    }

    /// Reads an encoder out of a checkpoint under the `diffusers` key names.
    ///
    /// `path` and `prefix` mean what they do for [`VaeDecoder::load`], with
    /// `"encoder."` in place of `"decoder."`.
    pub fn load(
        path: impl AsRef<std::path::Path>,
        prefix: &str,
        config: VaeConfig,
    ) -> Result<Self, NetworkError> {
        let mut file = ShardedSafeTensors::open(path)?;
        Self::read(&mut file, prefix, config)
    }

    /// The same, from a checkpoint that is already open.
    pub fn read(
        file: &mut ShardedSafeTensors,
        prefix: &str,
        config: VaeConfig,
    ) -> Result<Self, NetworkError> {
        if config.block_out_channels.is_empty() {
            return Err(NetworkError::InvalidConfig(
                "an encoder needs at least one resolution".into(),
            ));
        }
        // The encoder runs the configuration's channels in the order they are
        // written: from the image's resolution inward.
        let ladder = &config.block_out_channels;

        let conv_in = read_conv(file, &format!("{prefix}conv_in"), 1, 1)?;

        let mut down_blocks = Vec::with_capacity(ladder.len());
        for rung in 0..ladder.len() {
            let base = format!("{prefix}down_blocks.{rung}");
            let resnets = (0..config.layers_per_block)
                .map(|index| {
                    read_resnet(file, &format!("{base}.resnets.{index}"), config.norm_groups)
                })
                .collect::<Result<Vec<_>, _>>()?;
            // The halving convolution pads on the right and bottom only, which
            // `encode` does for it, so the convolution itself pads nothing.
            let downsampler = if rung + 1 < ladder.len() {
                Some(read_conv(
                    file,
                    &format!("{base}.downsamplers.0.conv"),
                    2,
                    0,
                )?)
            } else {
                None
            };
            down_blocks.push(DownBlock {
                resnets,
                downsampler,
            });
        }

        let mid = format!("{prefix}mid_block");
        let mid_first = read_resnet(file, &format!("{mid}.resnets.0"), config.norm_groups)?;
        let mid_attention =
            read_attention(file, &format!("{mid}.attentions.0"), config.norm_groups)?;
        let mid_last = read_resnet(file, &format!("{mid}.resnets.1"), config.norm_groups)?;

        let norm_out =
            read_group_norm(file, &format!("{prefix}conv_norm_out"), config.norm_groups)?;
        let conv_out = read_conv(file, &format!("{prefix}conv_out"), 1, 1)?;
        // `quant_conv` sits one level up from the encoder's own keys.
        let root = prefix.strip_suffix("encoder.").unwrap_or("");
        let quant = read_conv(file, &format!("{root}quant_conv"), 1, 0).ok();

        if conv_in.in_channels != config.out_channels || conv_in.out_channels() != ladder[0] {
            return Err(NetworkError::InvalidConfig(format!(
                "the checkpoint's stem maps {} channels to {}, and the configuration says {} to {}",
                conv_in.in_channels,
                conv_in.out_channels(),
                config.out_channels,
                ladder[0]
            )));
        }
        // Most checkpoints predict a mean and a log-variance, so the last
        // convolution is twice as wide as the latent; a few predict the mean
        // alone. Either is fine, and anything else is the wrong file.
        let produced = quant
            .as_ref()
            .map_or(conv_out.out_channels(), |quant| quant.out_channels());
        if produced != config.latent_channels && produced != 2 * config.latent_channels {
            return Err(NetworkError::InvalidConfig(format!(
                "the encoder ends in {produced} channels, which is neither {} nor twice it",
                config.latent_channels
            )));
        }

        Ok(Self {
            config,
            conv_in,
            down_blocks,
            mid_first,
            mid_attention,
            mid_last,
            norm_out,
            conv_out,
            quant,
            #[cfg(feature = "cuda")]
            device: None,
        })
    }

    /// Uploads the encoder to a CUDA device and encodes there from now on.
    ///
    /// Fails closed, leaving the encoder on the CPU if the upload does not fit.
    #[cfg(feature = "cuda")]
    pub fn attach_device(
        &mut self,
        gpu: std::sync::Arc<crate::cuda_image::ImageGpu>,
    ) -> Result<(), NetworkError> {
        self.device = Some(std::sync::Arc::new(
            crate::cuda_image::DeviceVaeEncoder::upload(&gpu, self)?,
        ));
        Ok(())
    }

    /// Encodes an image whose values sit in roughly `[-1, 1]` into the latent
    /// the sampler works on, scale and shift already applied.
    ///
    /// The result is the distribution's mean rather than a draw from it, which
    /// is what image-to-image wants: the noise it needs is added afterwards, at
    /// the level the run starts from.
    pub fn encode(&self, image: &FeatureMap) -> Result<FeatureMap, NetworkError> {
        if image.channels != self.config.out_channels {
            return Err(NetworkError::InvalidTarget {
                expected: self.config.out_channels,
                actual: image.channels,
            });
        }

        let moments = self.moments(image)?;

        // The second half of the channels is the log-variance, which only
        // sampling from the distribution would need.
        let channels = self.config.latent_channels;
        let pixels = moments.pixels();
        let mut latent = FeatureMap::from_vec(
            channels,
            moments.height,
            moments.width,
            moments.data[..channels * pixels].to_vec(),
        )?;
        for value in &mut latent.data {
            *value = (*value - self.config.shift_factor) * self.config.scaling_factor;
        }
        Ok(latent)
    }

    fn moments(&self, image: &FeatureMap) -> Result<FeatureMap, NetworkError> {
        #[cfg(feature = "cuda")]
        if let Some(device) = &self.device {
            return device.moments(image);
        }

        let mut hidden = self.conv_in.forward(image)?;
        for block in &self.down_blocks {
            for resnet in &block.resnets {
                hidden = resnet.forward(&hidden)?;
            }
            if let Some(downsampler) = &block.downsampler {
                hidden = downsampler.forward(&pad_right_bottom(&hidden))?;
            }
        }

        hidden = self.mid_first.forward(&hidden)?;
        hidden = self.mid_attention.forward(&hidden)?;
        hidden = self.mid_last.forward(&hidden)?;

        self.norm_out.forward(&mut hidden)?;
        silu(&mut hidden);
        let mut moments = self.conv_out.forward(&hidden)?;
        if let Some(quant) = &self.quant {
            moments = quant.forward(&moments)?;
        }
        Ok(moments)
    }
}

/// Adds one row at the bottom and one column at the right, which is the
/// padding `diffusers` applies before an encoder's halving convolution.
pub(crate) fn pad_right_bottom(map: &FeatureMap) -> FeatureMap {
    let (height, width) = (map.height + 1, map.width + 1);
    let mut padded = FeatureMap::new(map.channels, height, width);
    for channel in 0..map.channels {
        for row in 0..map.height {
            let from = (channel * map.height + row) * map.width;
            let to = (channel * height + row) * width;
            padded.data[to..to + map.width].copy_from_slice(&map.data[from..from + map.width]);
        }
    }
    padded
}

/// An image in `[-1, 1]` as the eight-bit interleaved rows a PNG encoder wants.
pub fn to_rgb8(image: &FeatureMap) -> Vec<u8> {
    let pixels = image.pixels();
    let mut bytes = Vec::with_capacity(pixels * image.channels);
    for pixel in 0..pixels {
        for channel in 0..image.channels {
            let value = image.data[channel * pixels + pixel];
            bytes.push(((value * 0.5 + 0.5).clamp(0.0, 1.0) * 255.0).round() as u8);
        }
    }
    bytes
}

/// Writes a decoded image to a PNG.
#[cfg(feature = "images")]
pub fn save_png(image: &FeatureMap, path: impl AsRef<std::path::Path>) -> Result<(), NetworkError> {
    let path = path.as_ref();
    dynamic_image(image)?
        .save(path)
        .map_err(|error| NetworkError::InvalidDataset(format!("{}: {error}", path.display())))
}

/// A decoded image encoded as PNG in memory, the same bytes [`save_png`]
/// writes to a `.png` file.
#[cfg(feature = "images")]
pub fn png_bytes(image: &FeatureMap) -> Result<Vec<u8>, NetworkError> {
    let mut bytes = std::io::Cursor::new(Vec::new());
    dynamic_image(image)?
        .write_to(&mut bytes, image::ImageFormat::Png)
        .map_err(|error| NetworkError::InvalidDataset(format!("PNG encoding: {error}")))?;
    Ok(bytes.into_inner())
}

/// An encoded image (PNG or JPEG) resized to exactly `width` x `height`, as a
/// 3-channel FeatureMap in [-1, 1] (channel-planar, like `to_rgb8` reads).
#[cfg(feature = "images")]
pub fn from_image_bytes(
    bytes: &[u8],
    width: usize,
    height: usize,
) -> Result<FeatureMap, NetworkError> {
    if width == 0 || height == 0 {
        return Err(NetworkError::InvalidDataset(format!(
            "cannot resize an image to {width}x{height}"
        )));
    }
    let decoded = image::load_from_memory(bytes)
        .map_err(|error| NetworkError::InvalidDataset(format!("image decoding: {error}")))?;
    let (w, h) = (width as u32, height as u32);
    let rgb = if decoded.width() == w && decoded.height() == h {
        decoded.to_rgb8()
    } else {
        decoded
            .resize_exact(w, h, image::imageops::FilterType::Lanczos3)
            .to_rgb8()
    };
    let pixels = width * height;
    let mut map = FeatureMap::new(3, height, width);
    for (pixel, rgb) in rgb.as_raw().chunks_exact(3).enumerate() {
        for (channel, &byte) in rgb.iter().enumerate() {
            map.data[channel * pixels + pixel] = byte as f32 / 255.0 * 2.0 - 1.0;
        }
    }
    Ok(map)
}

#[cfg(feature = "images")]
fn dynamic_image(image: &FeatureMap) -> Result<image::DynamicImage, NetworkError> {
    let bytes = to_rgb8(image);
    let (width, height) = (image.width as u32, image.height as u32);
    let shape = || NetworkError::InvalidConfig("the image's shape and its bytes disagree".into());
    match image.channels {
        3 => image::RgbImage::from_raw(width, height, bytes)
            .map(image::DynamicImage::ImageRgb8)
            .ok_or_else(shape),
        1 => image::GrayImage::from_raw(width, height, bytes)
            .map(image::DynamicImage::ImageLuma8)
            .ok_or_else(shape),
        channels => Err(NetworkError::InvalidConfig(format!(
            "a {channels}-channel image is neither grey nor RGB"
        ))),
    }
}

pub(crate) fn read_conv(
    file: &mut ShardedSafeTensors,
    name: &str,
    stride: usize,
    padding: usize,
) -> Result<Conv2d, NetworkError> {
    let (values, shape) = file.tensor(&format!("{name}.weight"))?;
    if shape.len() != 4 || shape[2] != shape[3] {
        return Err(NetworkError::InvalidConfig(format!(
            "{name}.weight is {shape:?}, which is not a square convolution kernel"
        )));
    }
    let (out_channels, in_channels, kernel) = (shape[0], shape[1], shape[2]);
    let bias = file
        .tensor(&format!("{name}.bias"))
        .ok()
        .map(|(bias, _)| bias);
    // A one-by-one convolution needs no padding whatever the caller asked for.
    let padding = if kernel == 1 { 0 } else { padding };
    Conv2d::new(
        Matrix::from_vec(out_channels, in_channels * kernel * kernel, values),
        bias,
        in_channels,
        kernel,
        stride,
        padding,
    )
}

fn read_group_norm(
    file: &mut ShardedSafeTensors,
    name: &str,
    groups: usize,
) -> Result<GroupNorm, NetworkError> {
    let (weight, _) = file.tensor(&format!("{name}.weight"))?;
    let (bias, _) = file.tensor(&format!("{name}.bias"))?;
    GroupNorm::new(groups, weight, bias, 1e-6)
}

fn read_resnet(
    file: &mut ShardedSafeTensors,
    name: &str,
    groups: usize,
) -> Result<ResnetBlock, NetworkError> {
    let conv1 = read_conv(file, &format!("{name}.conv1"), 1, 1)?;
    let conv2 = read_conv(file, &format!("{name}.conv2"), 1, 1)?;
    // The shortcut exists only where the channel count changes, so its absence
    // from the checkpoint is information rather than an error.
    let shortcut = match read_conv(file, &format!("{name}.conv_shortcut"), 1, 0) {
        Ok(conv) => Some(conv),
        Err(_) if conv1.in_channels == conv2.out_channels() => None,
        Err(error) => return Err(error),
    };
    Ok(ResnetBlock {
        norm1: read_group_norm(file, &format!("{name}.norm1"), groups)?,
        conv1,
        norm2: read_group_norm(file, &format!("{name}.norm2"), groups)?,
        conv2,
        shortcut,
    })
}

fn read_attention(
    file: &mut ShardedSafeTensors,
    name: &str,
    groups: usize,
) -> Result<AttentionBlock, NetworkError> {
    let projection = |file: &mut ShardedSafeTensors, suffix: &str| -> Result<Dense, NetworkError> {
        let (values, shape) = file.tensor(&format!("{name}.{suffix}.weight"))?;
        // Older checkpoints store these as `[c, c, 1, 1]` convolutions and
        // newer ones as `[c, c]` linear weights; the values are the same.
        let channels = shape[0];
        let (bias, _) = file.tensor(&format!("{name}.{suffix}.bias"))?;
        Dense::new(
            Matrix::from_vec(channels, values.len() / channels, values),
            Some(bias),
        )
    };
    Ok(AttentionBlock {
        norm: read_group_norm(file, &format!("{name}.group_norm"), groups)?,
        query: projection(file, "to_q")?,
        key: projection(file, "to_k")?,
        value: projection(file, "to_v")?,
        output: projection(file, "to_out.0")?,
    })
}

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

    /// A checkpoint with every key the loader reads, at a size that runs fast.
    pub(crate) fn checkpoint(config: &VaeConfig, path: &std::path::Path) {
        checkpoint_at(config, path, true)
    }

    /// The same, with the choice of carrying the convolution the Stable
    /// Diffusion line puts in front of the decoder. The FLUX line has none.
    pub(crate) fn checkpoint_at(config: &VaeConfig, path: &std::path::Path, post_quant: bool) {
        let ladder: Vec<usize> = config.block_out_channels.iter().rev().copied().collect();
        let mut tensors: BTreeMap<String, (Vec<usize>, Vec<f32>)> = BTreeMap::new();
        let mut add = |name: String, shape: Vec<usize>| {
            let count = shape.iter().product::<usize>();
            // Small deterministic values: a real decoder's weights are small,
            // and the test cares about shapes, not about the image.
            let values = (0..count)
                .map(|index| ((index % 7) as f32 - 3.0) * 0.02)
                .collect();
            tensors.insert(name, (shape, values));
        };

        let deepest = ladder[0];
        add(
            "decoder.conv_in.weight".into(),
            vec![deepest, config.latent_channels, 3, 3],
        );
        add("decoder.conv_in.bias".into(), vec![deepest]);

        let resnet =
            |name: &str, input: usize, output: usize, add: &mut dyn FnMut(String, Vec<usize>)| {
                add(format!("{name}.norm1.weight"), vec![input]);
                add(format!("{name}.norm1.bias"), vec![input]);
                add(format!("{name}.conv1.weight"), vec![output, input, 3, 3]);
                add(format!("{name}.conv1.bias"), vec![output]);
                add(format!("{name}.norm2.weight"), vec![output]);
                add(format!("{name}.norm2.bias"), vec![output]);
                add(format!("{name}.conv2.weight"), vec![output, output, 3, 3]);
                add(format!("{name}.conv2.bias"), vec![output]);
                if input != output {
                    add(
                        format!("{name}.conv_shortcut.weight"),
                        vec![output, input, 1, 1],
                    );
                    add(format!("{name}.conv_shortcut.bias"), vec![output]);
                }
            };

        resnet("decoder.mid_block.resnets.0", deepest, deepest, &mut add);
        resnet("decoder.mid_block.resnets.1", deepest, deepest, &mut add);
        for suffix in ["group_norm", "to_q", "to_k", "to_v", "to_out.0"] {
            let shape = if suffix == "group_norm" {
                vec![deepest]
            } else {
                vec![deepest, deepest]
            };
            add(
                format!("decoder.mid_block.attentions.0.{suffix}.weight"),
                shape,
            );
            add(
                format!("decoder.mid_block.attentions.0.{suffix}.bias"),
                vec![deepest],
            );
        }

        let mut input = deepest;
        for (rung, channels) in ladder.iter().enumerate() {
            for index in 0..config.layers_per_block + 1 {
                resnet(
                    &format!("decoder.up_blocks.{rung}.resnets.{index}"),
                    input,
                    *channels,
                    &mut add,
                );
                input = *channels;
            }
            if rung + 1 < ladder.len() {
                add(
                    format!("decoder.up_blocks.{rung}.upsamplers.0.conv.weight"),
                    vec![*channels, *channels, 3, 3],
                );
                add(
                    format!("decoder.up_blocks.{rung}.upsamplers.0.conv.bias"),
                    vec![*channels],
                );
            }
        }

        add("decoder.conv_norm_out.weight".into(), vec![input]);
        add("decoder.conv_norm_out.bias".into(), vec![input]);
        add(
            "decoder.conv_out.weight".into(),
            vec![config.out_channels, input, 3, 3],
        );
        add("decoder.conv_out.bias".into(), vec![config.out_channels]);

        // The encoder half, which image-to-image reads.
        let forward = &config.block_out_channels;
        add(
            "encoder.conv_in.weight".into(),
            vec![forward[0], config.out_channels, 3, 3],
        );
        add("encoder.conv_in.bias".into(), vec![forward[0]]);

        let mut input = forward[0];
        for (rung, channels) in forward.iter().enumerate() {
            for index in 0..config.layers_per_block {
                resnet(
                    &format!("encoder.down_blocks.{rung}.resnets.{index}"),
                    input,
                    *channels,
                    &mut add,
                );
                input = *channels;
            }
            if rung + 1 < forward.len() {
                add(
                    format!("encoder.down_blocks.{rung}.downsamplers.0.conv.weight"),
                    vec![*channels, *channels, 3, 3],
                );
                add(
                    format!("encoder.down_blocks.{rung}.downsamplers.0.conv.bias"),
                    vec![*channels],
                );
            }
        }

        resnet("encoder.mid_block.resnets.0", input, input, &mut add);
        resnet("encoder.mid_block.resnets.1", input, input, &mut add);
        for suffix in ["group_norm", "to_q", "to_k", "to_v", "to_out.0"] {
            let shape = if suffix == "group_norm" {
                vec![input]
            } else {
                vec![input, input]
            };
            add(
                format!("encoder.mid_block.attentions.0.{suffix}.weight"),
                shape,
            );
            add(
                format!("encoder.mid_block.attentions.0.{suffix}.bias"),
                vec![input],
            );
        }

        add("encoder.conv_norm_out.weight".into(), vec![input]);
        add("encoder.conv_norm_out.bias".into(), vec![input]);
        let moments = 2 * config.latent_channels;
        add("encoder.conv_out.weight".into(), vec![moments, input, 3, 3]);
        add("encoder.conv_out.bias".into(), vec![moments]);
        add("quant_conv.weight".into(), vec![moments, moments, 1, 1]);
        add("quant_conv.bias".into(), vec![moments]);
        if post_quant {
            let latent = config.latent_channels;
            add("post_quant_conv.weight".into(), vec![latent, latent, 1, 1]);
            add("post_quant_conv.bias".into(), vec![latent]);
        }

        crate::safetensors::write_checkpoint(path, &tensors);
    }

    pub(crate) fn tiny() -> VaeConfig {
        VaeConfig {
            latent_channels: 4,
            out_channels: 3,
            block_out_channels: vec![8, 16],
            layers_per_block: 1,
            norm_groups: 4,
            scaling_factor: 0.5,
            shift_factor: 0.25,
            batch_norm_eps: 1e-4,
        }
    }

    #[test]
    fn a_flux2_autoencoder_reads_no_scale_and_its_patch_norm() {
        // FLUX.2's config names no scaling factor. Falling back to Stable
        // Diffusion's 0.18215 divides the latent by it before decoding, which
        // washes the picture out; the model's own normalization is the batch
        // norm over the packed latent instead.
        let directory = std::env::temp_dir().join("rusting_brain_vae_flux2");
        std::fs::create_dir_all(&directory).unwrap();
        let config_path = directory.join("config.json");
        std::fs::write(
            &config_path,
            r#"{"_class_name": "AutoencoderKLFlux2", "latent_channels": 4,
                "block_out_channels": [8, 16], "layers_per_block": 1,
                "norm_num_groups": 4, "batch_norm_eps": 0.0001}"#,
        )
        .unwrap();
        let config = VaeConfig::from_file(&config_path).unwrap();
        assert_eq!(config.scaling_factor, 1.0);
        assert_eq!(config.shift_factor, 0.0);
        assert_eq!(config.batch_norm_eps, 1e-4);

        let path = directory.join("vae.safetensors");
        checkpoint_at(&config, &path, true);
        let decoder = VaeDecoder::load(&path, "decoder.", config.clone()).unwrap();
        assert!(decoder.patch_norm().is_none());

        // The statistics are over the packed channels, four per latent
        // channel for a 2x2 patch.
        let mut tensors = crate::safetensors::read_checkpoint(&path);
        let packed = config.latent_channels * 4;
        tensors.insert(
            "bn.running_mean".into(),
            (
                vec![packed],
                (0..packed).map(|index| index as f32).collect(),
            ),
        );
        tensors.insert(
            "bn.running_var".into(),
            (vec![packed], vec![3.9999; packed]),
        );
        crate::safetensors::write_checkpoint(&path, &tensors);
        let decoder = VaeDecoder::load(&path, "decoder.", config).unwrap();
        let (mean, std) = decoder.patch_norm().unwrap();
        assert_eq!(mean[5], 5.0);
        assert!((std[5] - 2.0).abs() < 1e-6);
    }

    #[test]
    fn a_decoder_runs_the_convolution_that_sits_in_front_of_its_stem() {
        // Reading `post_quant_conv` and not applying it changes no shape and
        // no edge: the picture comes back with the same composition and the
        // wrong colours, which is what every other test here would pass.
        let config = tiny();
        let latent = FeatureMap::from_vec(
            4,
            3,
            3,
            (0..36).map(|value| (value as f32 * 0.1).sin()).collect(),
        )
        .unwrap();

        let mut images = Vec::new();
        for (carries, name) in [(true, "with"), (false, "without")] {
            let path = std::env::temp_dir()
                .join(format!("rusting_brain_vae_post_quant_{name}.safetensors"));
            checkpoint_at(&config, &path, carries);
            let decoder = VaeDecoder::load(&path, "decoder.", config.clone()).unwrap();
            assert_eq!(decoder.post_quant.is_some(), carries);
            images.push(decoder.decode(&latent).unwrap());
        }

        let (with, without) = (&images[0], &images[1]);
        let apart = with
            .data
            .iter()
            .zip(&without.data)
            .map(|(with, without)| (with - without).abs())
            .fold(0.0f32, f32::max);
        assert!(
            apart > 1e-4,
            "the convolution in front of the stem changed nothing, so it was not applied"
        );
    }

    #[test]
    fn a_decoder_reads_a_checkpoint_and_turns_a_latent_into_an_image() {
        let config = tiny();
        let path = std::env::temp_dir().join("rusting_brain_vae_decode.safetensors");
        checkpoint(&config, &path);

        let decoder = VaeDecoder::load(&path, "decoder.", config.clone()).unwrap();
        assert_eq!(decoder.config().upscale(), 2);

        let latent = FeatureMap::from_vec(
            4,
            3,
            3,
            (0..36).map(|value| (value as f32 * 0.1).sin()).collect(),
        )
        .unwrap();
        let image = decoder.decode(&latent).unwrap();

        assert_eq!(image.channels, 3);
        assert_eq!((image.height, image.width), (6, 6));
        assert!(image.data.iter().all(|value| value.is_finite()));

        // A latent of the wrong depth is refused rather than reinterpreted.
        assert!(decoder.decode(&FeatureMap::new(3, 3, 3)).is_err());
        std::fs::remove_file(path).ok();
    }

    #[test]
    fn an_encoder_turns_an_image_into_a_latent_the_decoder_accepts() {
        let config = tiny();
        let path = std::env::temp_dir().join("rusting_brain_vae_encode.safetensors");
        checkpoint(&config, &path);

        let encoder = VaeEncoder::load(&path, "encoder.", config.clone()).unwrap();
        let decoder = VaeDecoder::load(&path, "decoder.", config.clone()).unwrap();

        let image = FeatureMap::from_vec(
            3,
            6,
            6,
            (0..108).map(|value| (value as f32 * 0.07).cos()).collect(),
        )
        .unwrap();
        let latent = encoder.encode(&image).unwrap();

        // The ladder halves once, so the latent is half the image's size and
        // as deep as the configuration says.
        assert_eq!(latent.channels, config.latent_channels);
        assert_eq!((latent.height, latent.width), (3, 3));
        assert!(latent.data.iter().all(|value| value.is_finite()));

        // What comes out is what the decoder takes, at the size it started.
        let round_trip = decoder.decode(&latent).unwrap();
        assert_eq!((round_trip.height, round_trip.width), (6, 6));

        // An image of the wrong depth is refused rather than reinterpreted.
        assert!(encoder.encode(&FeatureMap::new(1, 6, 6)).is_err());
        std::fs::remove_file(path).ok();
    }

    #[test]
    fn a_missing_layer_is_an_error_rather_than_a_silent_hole() {
        let config = tiny();
        let path = std::env::temp_dir().join("rusting_brain_vae_missing.safetensors");
        checkpoint(&config, &path);

        assert!(VaeDecoder::load(&path, "vae.decoder.", config.clone()).is_err());
        // The same file read with one rung too many looks for keys that are
        // not there.
        let mut deeper = config;
        deeper.block_out_channels.push(32);
        assert!(VaeDecoder::load(&path, "decoder.", deeper).is_err());
        std::fs::remove_file(path).ok();
    }

    #[test]
    fn tiles_blend_back_into_the_whole_image() {
        // A decode that only upsamples is local, so the stitched tiles must
        // reproduce decoding the whole latent, seams and edges included.
        let latent = FeatureMap::from_vec(
            2,
            11,
            7,
            (0..154).map(|value| (value as f32 * 0.37).sin()).collect(),
        )
        .unwrap();
        let decode = |map: &FeatureMap| Ok(crate::conv::upsample_nearest(map, 2));
        let whole = decode(&latent).unwrap();
        for (tile, overlap) in [(4, 1), (5, 2), (3, 0), (20, 4)] {
            let tiled = stitch_tiles(&latent, tile, overlap, 2, decode).unwrap();
            assert_eq!((tiled.height, tiled.width), (22, 14));
            for (a, b) in tiled.data.iter().zip(&whole.data) {
                assert!((a - b).abs() < 1e-5, "tile {tile} overlap {overlap}");
            }
        }
    }

    #[test]
    fn a_tiled_decode_matches_the_whole_decode_when_one_tile_covers_it() {
        let config = tiny();
        let path = std::env::temp_dir().join("rusting_brain_vae_tiled.safetensors");
        checkpoint(&config, &path);
        let decoder = VaeDecoder::load(&path, "decoder.", config).unwrap();
        let latent = FeatureMap::from_vec(
            4,
            5,
            4,
            (0..80).map(|value| (value as f32 * 0.1).cos()).collect(),
        )
        .unwrap();

        assert_eq!(
            decoder.decode_tiled(&latent, 5, 1).unwrap(),
            decoder.decode(&latent).unwrap()
        );
        let tiled = decoder.decode_tiled(&latent, 3, 1).unwrap();
        assert_eq!((tiled.channels, tiled.height, tiled.width), (3, 10, 8));
        assert!(tiled.data.iter().all(|value| value.is_finite()));
        assert!(decoder.decode_tiled(&latent, 3, 3).is_err());
        std::fs::remove_file(path).ok();
    }

    #[test]
    fn eight_bit_output_clamps_the_range_the_decoder_produces() {
        let image = FeatureMap::from_vec(3, 1, 2, vec![-1.0, 0.0, 1.0, 2.0, -5.0, 0.5]).unwrap();
        // Interleaved, so the first pixel takes one value from each channel.
        assert_eq!(to_rgb8(&image), vec![0, 255, 0, 128, 255, 191]);
    }

    #[test]
    fn the_flux_configuration_carries_its_own_latent_shape() {
        let flux = VaeConfig::flux();
        assert_eq!(flux.latent_channels, 16);
        assert_eq!(flux.upscale(), 8);
        assert!(flux.shift_factor > 0.0);
    }

    #[cfg(feature = "images")]
    #[test]
    fn png_bytes_are_the_file_save_png_writes() {
        for channels in [3, 1] {
            let mut image = FeatureMap::new(channels, 5, 7);
            for (index, value) in image.data.iter_mut().enumerate() {
                *value = (index % 11) as f32 / 5.0 - 1.0;
            }
            let path = std::env::temp_dir().join(format!(
                "rusting_brain_png_bytes_{}_{channels}.png",
                std::process::id()
            ));
            save_png(&image, &path).unwrap();
            let file = std::fs::read(&path).unwrap();
            std::fs::remove_file(&path).unwrap();
            assert_eq!(png_bytes(&image).unwrap(), file, "{channels} channels");
        }
        assert!(png_bytes(&FeatureMap::new(2, 1, 1)).is_err());
    }
}

#[cfg(feature = "images")]
#[test]
fn from_image_bytes_round_trips_and_resizes() {
    let mut image = FeatureMap::new(3, 5, 7);
    for (index, value) in image.data.iter_mut().enumerate() {
        *value = (index % 13) as f32 / 6.0 - 1.0;
    }
    let png = png_bytes(&image).unwrap();
    let same = from_image_bytes(&png, 7, 5).unwrap();
    assert_eq!(to_rgb8(&same), to_rgb8(&image));
    let resized = from_image_bytes(&png, 16, 9).unwrap();
    assert_eq!(
        (resized.channels, resized.width, resized.height),
        (3, 16, 9)
    );
    assert!(from_image_bytes(&png, 0, 9).is_err());
    assert!(from_image_bytes(b"nope", 4, 4).is_err());
}