rusting_brain 3.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
//! The CLIP text tower, which is the prompt encoder every Stable Diffusion
//! model and FLUX.1 read their pooled vector from.
//!
//! It is a small causal transformer with learned positions and LayerNorm,
//! rather than the rotary RMSNorm arrangement [`crate::text_encoder`] runs. The
//! two exist side by side because published models pair them: FLUX.1 takes its
//! per-token states from T5 and its pooled vector from here, and Stable
//! Diffusion XL concatenates the states of two of these.
//!
//! The pooled vector is the hidden state at the end-of-text token, not the last
//! position: a prompt is padded, and the padding has read the whole prompt too.
//!
//! ponytail: inference only, `f32` or one byte per weight, no image tower. The
//! image tower is a different model that happens to share a name, and nothing
//! in a text-to-image pipeline asks for it.

use crate::conv::Dense;
use crate::matrix::Matrix;
use crate::mmdit::{attention, layer_norm};
use crate::network::NetworkError;
use crate::safetensors::ShardedSafeTensors;
use crate::tokenizer::Bpe;
use crate::transformer::Precision;
use rayon::prelude::*;

/// The shape of a CLIP text tower, as its `config.json` states it.
#[derive(Clone, Debug, PartialEq)]
pub struct ClipTextConfig {
    pub vocab_size: usize,
    pub d_model: usize,
    pub layers: usize,
    pub num_heads: usize,
    pub mlp_dim: usize,
    /// How long the learned position table is, which is also how long a prompt
    /// is padded to.
    pub max_positions: usize,
    pub eps: f32,
    /// CLIP's own `x * sigmoid(1.702 * x)`, which the published towers use in
    /// place of the usual GELU.
    pub quick_gelu: bool,
    /// The width the pooled vector is projected to, when the checkpoint carries
    /// a projection at all.
    pub projection_dim: Option<usize>,
    pub bos_token: u32,
    pub eos_token: u32,
}

impl Default for ClipTextConfig {
    /// The CLIP ViT-L/14 text tower, which is the one Stable Diffusion 1.x and
    /// FLUX.1 carry.
    fn default() -> Self {
        Self {
            vocab_size: 49408,
            d_model: 768,
            layers: 12,
            num_heads: 12,
            mlp_dim: 3072,
            max_positions: 77,
            eps: 1e-5,
            quick_gelu: true,
            projection_dim: None,
            bos_token: 49406,
            eos_token: 49407,
        }
    }
}

impl ClipTextConfig {
    /// Reads a Hugging Face `text_encoder/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!("text encoder config.json: {error}"))
        })?;
        // A whole pipeline's configuration nests the tower's own.
        let json = json.get("text_config").unwrap_or(&json).clone();

        let default = Self::default();
        let number = |name: &str, fallback: usize| -> usize {
            json.get(name)
                .and_then(|value| value.as_u64())
                .map_or(fallback, |value| value as usize)
        };
        let token = |name: &str, fallback: u32| -> u32 {
            json.get(name)
                .and_then(|value| value.as_u64())
                .map_or(fallback, |value| value as u32)
        };

        Ok(Self {
            vocab_size: number("vocab_size", default.vocab_size),
            d_model: number("hidden_size", default.d_model),
            layers: number("num_hidden_layers", default.layers),
            num_heads: number("num_attention_heads", default.num_heads),
            mlp_dim: number("intermediate_size", default.mlp_dim),
            max_positions: number("max_position_embeddings", default.max_positions),
            eps: json
                .get("layer_norm_eps")
                .and_then(|value| value.as_f64())
                .unwrap_or(default.eps as f64) as f32,
            quick_gelu: json
                .get("hidden_act")
                .and_then(|value| value.as_str())
                .is_none_or(|name| name == "quick_gelu"),
            // A tower with no projection is not an error: only the ones used as
            // a pooled encoder on their own carry one.
            projection_dim: json
                .get("projection_dim")
                .and_then(|value| value.as_u64())
                .map(|value| value as usize),
            bos_token: token("bos_token_id", default.bos_token),
            eos_token: token("eos_token_id", default.eos_token),
        })
    }

    /// Dimensions per attention head.
    pub fn head_dim(&self) -> usize {
        self.d_model / self.num_heads.max(1)
    }
}

/// One transformer layer: attention, then feed-forward, each behind its own
/// layer norm.
pub(crate) struct Layer {
    pub(crate) attention_norm: Norm,
    pub(crate) query: Dense,
    pub(crate) key: Dense,
    pub(crate) value: Dense,
    pub(crate) output: Dense,
    pub(crate) mlp_norm: Norm,
    pub(crate) mlp_in: Dense,
    pub(crate) mlp_out: Dense,
}

/// LayerNorm with the learned scale and offset CLIP trains, which is the same
/// layer the UNet's transformer blocks use.
pub(crate) struct Norm {
    pub(crate) weight: Vec<f32>,
    pub(crate) bias: Vec<f32>,
}

impl Norm {
    pub(crate) fn forward(&self, tokens: &Matrix, eps: f32) -> Matrix {
        let mut output = layer_norm(tokens, eps);
        output.data.par_chunks_mut(tokens.cols).for_each(|row| {
            for ((value, weight), bias) in row.iter_mut().zip(&self.weight).zip(&self.bias) {
                *value = *value * weight + bias;
            }
        });
        output
    }
}

/// A CLIP text tower.
pub struct ClipTextEncoder {
    config: ClipTextConfig,
    tokens: Matrix,
    positions: Matrix,
    pub(crate) layers: Vec<Layer>,
    pub(crate) final_norm: Norm,
    projection: Option<Dense>,
    /// The same weights on a CUDA device, when one was attached.
    #[cfg(feature = "cuda")]
    device: Option<crate::cuda_image::DeviceClip>,
}

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

    /// Reads a tower out of a checkpoint.
    ///
    /// `prefix` is what the keys start with, which is empty for the files
    /// published as `text_encoder/model.safetensors`.
    pub fn load(
        path: impl AsRef<std::path::Path>,
        prefix: &str,
        config: ClipTextConfig,
    ) -> Result<Self, NetworkError> {
        Self::load_at(path, prefix, config, Precision::F32)
    }

    /// The same, holding the projections at a chosen precision.
    pub fn load_at(
        path: impl AsRef<std::path::Path>,
        prefix: &str,
        config: ClipTextConfig,
        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: ClipTextConfig,
        precision: Precision,
    ) -> Result<Self, NetworkError> {
        let base = format!("{prefix}text_model");
        let tokens = file.matrix(&format!("{base}.embeddings.token_embedding.weight"))?;
        let positions = file.matrix(&format!("{base}.embeddings.position_embedding.weight"))?;
        if tokens.cols != config.d_model {
            return Err(NetworkError::InvalidConfig(format!(
                "the checkpoint's embeddings are {} wide and the configuration says {}",
                tokens.cols, config.d_model
            )));
        }

        let layers = (0..config.layers)
            .map(|index| {
                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)?,
                })
            })
            .collect::<Result<Vec<_>, NetworkError>>()?;

        Ok(Self {
            final_norm: norm(file, &format!("{base}.final_layer_norm"))?,
            // The projection lives outside the tower and only some checkpoints
            // carry it, so its absence is read rather than required.
            projection: file
                .matrix(&format!("{prefix}text_projection.weight"))
                .ok()
                .map(|weight| Dense::new(weight, None))
                .transpose()?,
            config,
            tokens,
            positions,
            layers,
            #[cfg(feature = "cuda")]
            device: None,
        })
    }

    /// The token ids for a prompt: the start token, the prompt, the end token,
    /// and padding out to the length the position table covers.
    ///
    /// Padding is what the published pipelines feed, and the pooled vector is
    /// read from the end token rather than the last position because of it.
    /// The padding is end tokens: attention here is causal, so nothing after
    /// the first end token can reach the state that is pooled, whatever the
    /// padding is.
    pub fn tokenize(&self, tokenizer: &Bpe, prompt: &str) -> Result<Vec<u32>, NetworkError> {
        let mut ids = vec![self.config.bos_token];
        // Two of the positions are the start and end tokens.
        let room = self.config.max_positions.saturating_sub(2);
        ids.extend(tokenizer.encode(prompt)?.into_iter().take(room));
        ids.push(self.config.eos_token);
        ids.resize(self.config.max_positions, self.config.eos_token);
        Ok(ids)
    }

    /// The hidden states for a sequence of token ids, `[tokens, d_model]`.
    pub fn forward(&self, ids: &[u32]) -> Result<Matrix, NetworkError> {
        Ok(self.forward_skipping(ids, 0)?.1)
    }

    /// The same pass, also handing back the states as they were `skip` layers
    /// from the end.
    ///
    /// Stable Diffusion XL reads its prompt from the second-to-last layer and
    /// its pooled vector from the end of the tower, so both come back here and
    /// the tower runs once. `skip` of zero makes the two the same states.
    pub fn forward_skipping(
        &self,
        ids: &[u32],
        skip: usize,
    ) -> Result<(Matrix, Matrix), NetworkError> {
        if ids.is_empty() {
            return Err(NetworkError::InvalidConfig(
                "an empty prompt has no hidden states".into(),
            ));
        }
        if ids.len() > self.positions.rows {
            return Err(NetworkError::InvalidTarget {
                expected: self.positions.rows,
                actual: ids.len(),
            });
        }

        let mut hidden = Matrix::new(ids.len(), self.config.d_model);
        for (position, id) in ids.iter().enumerate() {
            if *id as usize >= self.tokens.rows {
                return Err(NetworkError::InvalidTarget {
                    expected: self.tokens.rows,
                    actual: *id as usize,
                });
            }
            let row = hidden.row_mut(position);
            row.copy_from_slice(self.tokens.row(*id as usize));
            for (value, learned) in row.iter_mut().zip(self.positions.row(position)) {
                *value += learned;
            }
        }

        #[cfg(feature = "cuda")]
        if let Some(device) = &self.device {
            // The embedding gather above is a table lookup per token, so it
            // stays here and the device gets the one buffer it produced.
            return device.forward(&hidden, skip);
        }

        let heads = self.config.num_heads;
        let stop = self.layers.len().saturating_sub(skip);
        let mut skipped = None;
        for (index, layer) in self.layers.iter().enumerate() {
            // The states as they were before this layer ran are what a
            // pipeline that skips the last layers reads.
            if index == stop {
                skipped = Some(hidden.clone());
            }
            run_layer(
                layer,
                &mut hidden,
                heads,
                self.config.eps,
                self.config.quick_gelu,
                true,
            )?;
        }

        let normalized = self.final_norm.forward(&hidden, self.config.eps);
        // The layers that were skipped were skipped before the final norm,
        // which is what the reference pipeline reads.
        Ok((skipped.unwrap_or_else(|| normalized.clone()), normalized))
    }

    /// Uploads every layer to a CUDA device and runs there from now on.
    ///
    /// Fails closed, leaving the tower 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(crate::cuda_image::DeviceClip::upload(&gpu, self)?);
        Ok(())
    }

    /// The pooled vector: the hidden state at the end token, through the
    /// projection if the checkpoint has one.
    pub fn pool(&self, ids: &[u32], hidden: &Matrix) -> Result<Vec<f32>, NetworkError> {
        // The first end token, because everything after it is padding.
        let position = ids
            .iter()
            .position(|id| *id == self.config.eos_token)
            .unwrap_or(hidden.rows - 1)
            .min(hidden.rows - 1);
        let pooled = hidden.row(position).to_vec();
        match &self.projection {
            Some(projection) => projection.apply(&pooled),
            None => Ok(pooled),
        }
    }

    /// Tokenizing, running and pooling in one call.
    pub fn encode(
        &self,
        tokenizer: &Bpe,
        prompt: &str,
    ) -> Result<(Matrix, Vec<f32>), NetworkError> {
        let ids = self.tokenize(tokenizer, prompt)?;
        let hidden = self.forward(&ids)?;
        let pooled = self.pool(&ids, &hidden)?;
        Ok((hidden, pooled))
    }
}

/// Runs one layer in place: attention behind its norm, then the feed-forward
/// behind its own.
///
/// Shared with the image tower in [`crate::vit_encoder`], which is the same
/// layer with `causal` off. The two towers differ in what they put in front of
/// the stack, not in the stack.
pub(crate) fn run_layer(
    layer: &Layer,
    hidden: &mut Matrix,
    heads: usize,
    eps: f32,
    quick_gelu: bool,
    causal: bool,
) -> Result<(), NetworkError> {
    let normed = layer.attention_norm.forward(hidden, eps);
    let attended = attention(
        &layer.query.forward(&normed)?,
        &layer.key.forward(&normed)?,
        &layer.value.forward(&normed)?,
        heads,
        heads,
        causal,
    );
    add(hidden, &layer.output.forward(&attended)?);

    let normed = layer.mlp_norm.forward(hidden, eps);
    let mut wide = layer.mlp_in.forward(&normed)?;
    wide.data.par_iter_mut().for_each(|value| {
        *value = match quick_gelu {
            true => quick_gelu_value(*value),
            false => crate::ffn::gelu(*value),
        }
    });
    add(hidden, &layer.mlp_out.forward(&wide)?);
    Ok(())
}

/// `x * sigmoid(1.702 * x)`, the activation the published towers were trained
/// with.
fn quick_gelu_value(value: f32) -> f32 {
    value / (1.0 + (-1.702 * value).exp())
}

pub(crate) fn add(target: &mut Matrix, source: &Matrix) {
    target
        .data
        .par_iter_mut()
        .zip(source.data.par_iter())
        .for_each(|(target, source)| *target += source);
}

pub(crate) fn norm(file: &mut ShardedSafeTensors, name: &str) -> Result<Norm, NetworkError> {
    Ok(Norm {
        weight: file.tensor(&format!("{name}.weight"))?.0,
        bias: file.tensor(&format!("{name}.bias"))?.0,
    })
}

pub(crate) fn dense(
    file: &mut ShardedSafeTensors,
    name: &str,
    precision: Precision,
) -> Result<Dense, NetworkError> {
    let (values, shape) = file.tensor(&format!("{name}.weight"))?;
    if shape.len() != 2 {
        return Err(NetworkError::InvalidConfig(format!(
            "{name}.weight is {shape:?}, which is not a linear layer"
        )));
    }
    let bias = file
        .tensor(&format!("{name}.bias"))
        .ok()
        .map(|(bias, _)| bias);
    let mut layer = Dense::new(Matrix::from_vec(shape[0], shape[1], values), bias)?;
    if precision == Precision::Q8 {
        layer.quantize();
    }
    Ok(layer)
}

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

    pub(crate) fn tiny() -> ClipTextConfig {
        ClipTextConfig {
            vocab_size: 24,
            d_model: 16,
            layers: 2,
            num_heads: 4,
            mlp_dim: 32,
            max_positions: 8,
            eps: 1e-5,
            quick_gelu: true,
            projection_dim: None,
            bos_token: 20,
            eos_token: 21,
        }
    }

    pub(crate) fn checkpoint(config: &ClipTextConfig, path: &std::path::Path, projection: bool) {
        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>();
            let values = (0..count)
                .map(|index| ((index % 11) as f32 - 5.0) * 0.05)
                .collect();
            tensors.insert(name, (shape, values));
        };

        add(
            "text_model.embeddings.token_embedding.weight".into(),
            vec![config.vocab_size, config.d_model],
        );
        add(
            "text_model.embeddings.position_embedding.weight".into(),
            vec![config.max_positions, config.d_model],
        );
        for index in 0..config.layers {
            let base = format!("text_model.encoder.layers.{index}");
            for norm in ["layer_norm1", "layer_norm2"] {
                add(format!("{base}.{norm}.weight"), vec![config.d_model]);
                add(format!("{base}.{norm}.bias"), vec![config.d_model]);
            }
            for name in ["q_proj", "k_proj", "v_proj", "out_proj"] {
                add(
                    format!("{base}.self_attn.{name}.weight"),
                    vec![config.d_model, config.d_model],
                );
                add(
                    format!("{base}.self_attn.{name}.bias"),
                    vec![config.d_model],
                );
            }
            add(
                format!("{base}.mlp.fc1.weight"),
                vec![config.mlp_dim, config.d_model],
            );
            add(format!("{base}.mlp.fc1.bias"), vec![config.mlp_dim]);
            add(
                format!("{base}.mlp.fc2.weight"),
                vec![config.d_model, config.mlp_dim],
            );
            add(format!("{base}.mlp.fc2.bias"), vec![config.d_model]);
        }
        add(
            "text_model.final_layer_norm.weight".into(),
            vec![config.d_model],
        );
        add(
            "text_model.final_layer_norm.bias".into(),
            vec![config.d_model],
        );
        if let Some(width) = config.projection_dim.filter(|_| projection) {
            add("text_projection.weight".into(), vec![width, config.d_model]);
        }

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

    fn encoder(config: &ClipTextConfig, name: &str, precision: Precision) -> ClipTextEncoder {
        let path = std::env::temp_dir().join(name);
        checkpoint(config, &path, true);
        let encoder = ClipTextEncoder::load_at(&path, "", config.clone(), precision).unwrap();
        std::fs::remove_file(path).ok();
        encoder
    }

    #[test]
    fn a_prompt_becomes_one_hidden_state_per_position() {
        let config = tiny();
        let encoder = encoder(
            &config,
            "rusting_brain_clip_forward.safetensors",
            Precision::F32,
        );
        let hidden = encoder.forward(&[20, 3, 7, 21]).unwrap();

        assert_eq!((hidden.rows, hidden.cols), (4, config.d_model));
        assert!(hidden.data.iter().all(|value| value.is_finite()));
    }

    #[test]
    fn the_pooled_vector_is_read_at_the_end_token_and_not_the_last_position() {
        let config = tiny();
        let encoder = encoder(
            &config,
            "rusting_brain_clip_pool.safetensors",
            Precision::F32,
        );
        // Two real tokens, an end token, and then padding.
        let ids = [20, 3, 7, 21, 21, 21, 21, 21];
        let hidden = encoder.forward(&ids).unwrap();
        let pooled = encoder.pool(&ids, &hidden).unwrap();

        assert_eq!(pooled, hidden.row(3).to_vec());
        assert_ne!(pooled, hidden.row(hidden.rows - 1).to_vec());
    }

    #[test]
    fn a_prompt_is_wrapped_and_padded_to_the_position_table() {
        let config = tiny();
        let encoder = encoder(
            &config,
            "rusting_brain_clip_tokens.safetensors",
            Precision::F32,
        );
        let tokenizer = crate::tokenizer::tests::tokenizer(&["h i"], &["hi"], None);
        let ids = encoder.tokenize(&tokenizer, "hi").unwrap();

        assert_eq!(ids.len(), config.max_positions);
        assert_eq!(ids[0], config.bos_token);
        assert!(ids[1..].contains(&config.eos_token));
        // A prompt longer than the table still fits, with room kept for both
        // of the markers.
        let long = encoder.tokenize(&tokenizer, "hihihihihihi").unwrap();
        assert_eq!(long.len(), config.max_positions);
        assert_eq!(long[config.max_positions - 1], config.eos_token);
    }

    #[test]
    fn a_projection_widens_the_pooled_vector() {
        let mut config = tiny();
        config.projection_dim = Some(6);
        let encoder = encoder(
            &config,
            "rusting_brain_clip_projection.safetensors",
            Precision::F32,
        );
        let ids = [20, 3, 21];
        let hidden = encoder.forward(&ids).unwrap();

        assert_eq!(encoder.pool(&ids, &hidden).unwrap().len(), 6);
    }

    #[test]
    fn a_quantized_tower_says_what_the_float_one_does() {
        let config = tiny();
        let ids = [20, 3, 7, 12, 21];
        let float = encoder(
            &config,
            "rusting_brain_clip_f32.safetensors",
            Precision::F32,
        )
        .forward(&ids)
        .unwrap();
        let quantized = encoder(&config, "rusting_brain_clip_q8.safetensors", Precision::Q8)
            .forward(&ids)
            .unwrap();

        for (float, quantized) in float.data.iter().zip(&quantized.data) {
            assert!(
                (float - quantized).abs() < 0.05,
                "{float} against {quantized}"
            );
        }
    }

    #[test]
    fn a_published_config_states_the_shape() {
        let path = std::env::temp_dir().join("rusting_brain_clip_config.json");
        std::fs::write(
            &path,
            r#"{"hidden_size": 1280, "num_hidden_layers": 32, "num_attention_heads": 20,
                "intermediate_size": 5120, "max_position_embeddings": 77, "vocab_size": 49408,
                "layer_norm_eps": 1e-5, "hidden_act": "gelu", "projection_dim": 1280,
                "eos_token_id": 2}"#,
        )
        .unwrap();
        let config = ClipTextConfig::from_file(&path).unwrap();
        std::fs::remove_file(path).ok();

        assert_eq!(config.d_model, 1280);
        assert_eq!(config.layers, 32);
        assert_eq!(config.head_dim(), 64);
        assert_eq!(config.projection_dim, Some(1280));
        assert_eq!(config.eos_token, 2);
        assert!(!config.quick_gelu);
    }

    #[test]
    fn a_token_past_the_vocabulary_is_refused() {
        let config = tiny();
        let encoder = encoder(
            &config,
            "rusting_brain_clip_range.safetensors",
            Precision::F32,
        );

        assert!(encoder.forward(&[20, 900, 21]).is_err());
        assert!(encoder.forward(&[]).is_err());
        assert!(encoder.forward(&[20; 9]).is_err());
    }

    #[test]
    fn skipping_the_last_layer_reads_a_state_the_end_of_the_tower_does_not() {
        let config = ClipTextConfig {
            vocab_size: 320,
            bos_token: 300,
            eos_token: 301,
            ..tiny()
        };
        let encoder = encoder(
            &config,
            "rusting_brain_clip_skip.safetensors",
            Precision::F32,
        );
        let ids = encoder
            .tokenize(
                &crate::tokenizer::tests::tokenizer(&["h i"], &["hi"], None),
                "a lighthouse",
            )
            .unwrap();
        let (skipped, normalized) = encoder.forward_skipping(&ids, 1).unwrap();

        assert_eq!(skipped.rows, normalized.rows);
        assert_ne!(skipped.data, normalized.data);
        // Skipping nothing hands back the end of the tower twice.
        let (states, end) = encoder.forward_skipping(&ids, 0).unwrap();
        assert_eq!(states.data, end.data);
        assert_eq!(end.data, normalized.data);
    }
}