Skip to main content

trustformers_models/fnet/
model.rs

1use crate::common::ActivationType;
2use crate::fnet::config::FNetConfig;
3use crate::weight_loading::binding::{
4    bind_embedding, bind_head_layer_norm, bind_head_linear, bind_linear, take_norm_bias,
5    take_norm_weight, BoundNamespaces,
6};
7use crate::weight_loading::checkpoint::{Checkpoint, LoadReport, UnusedTensors};
8use std::io::Read;
9use trustformers_core::{
10    device::Device,
11    errors::{tensor_op_error, Result},
12    layers::{Embedding, LayerNorm, Linear},
13    tensor::Tensor,
14    traits::{Config, Layer, Model},
15};
16
17/// Fourier Transform layer that replaces self-attention
18/// Applies 2D DFT along sequence and feature dimensions
19pub struct FourierTransform {
20    fourier_type: String,
21    #[allow(dead_code)]
22    use_bias: bool,
23    bias: Option<Linear>,
24    #[allow(dead_code)]
25    dropout: f32,
26    device: Device,
27}
28
29impl FourierTransform {
30    pub fn new(config: &FNetConfig) -> Result<Self> {
31        Self::new_with_device(config, Device::CPU)
32    }
33
34    pub fn new_with_device(config: &FNetConfig, device: Device) -> Result<Self> {
35        let bias = if config.use_bias_in_fourier {
36            Some(Linear::new_with_device(
37                config.hidden_size,
38                config.hidden_size,
39                true,
40                device,
41            ))
42        } else {
43            None
44        };
45
46        Ok(Self {
47            fourier_type: config.fourier_transform_type.clone(),
48            use_bias: config.use_bias_in_fourier,
49            bias,
50            dropout: config.fourier_dropout_prob,
51            device,
52        })
53    }
54
55    pub fn device(&self) -> Device {
56        self.device
57    }
58
59    pub fn parameter_count(&self) -> usize {
60        if let Some(ref bias_layer) = self.bias {
61            bias_layer.parameter_count()
62        } else {
63            0
64        }
65    }
66
67    /// Apply the 2-D Discrete Fourier Transform and keep its real part.
68    ///
69    /// This is FNet's token-mixing operation: `Re(F_seq(F_hidden(x)))`.
70    ///
71    /// # Why this needs complex arithmetic
72    ///
73    /// A previous revision built a single matrix holding only
74    /// `cos(-2πkj/N)/√N` and applied it twice. That is **not** the real part of
75    /// the 2-D DFT. Writing the 1-D basis as `e^{-2πi kn/N} = c - i·s`, the
76    /// separable 2-D transform gives
77    ///
78    /// ```text
79    /// Re(X)[k, l] = Σ_n Σ_m x[n, m] · (c_kn·c_lm − s_kn·s_lm)
80    /// ```
81    ///
82    /// The dropped `−s·s` term is exactly what the cosine-only version threw
83    /// away, so its output was a *different linear map* — cosine mixing, not a
84    /// Fourier transform. Both the sine and the cosine components are carried
85    /// through here, so the imaginary part produced by the first axis
86    /// contributes to the real part after the second, as it must.
87    ///
88    /// # Errors
89    ///
90    /// Fails when the input is neither 2-D (`[seq, hidden]`) nor 3-D
91    /// (`[batch, seq, hidden]`), or when an intermediate reshape fails.
92    fn apply_dft(&self, x: &Tensor) -> Result<Tensor> {
93        // x: [batch_size, seq_len, hidden_size] or [seq_len, hidden_size]
94        // Normalise to 3-D so all downstream math is consistent.
95        let (x3d, was_2d) =
96            if x.shape().len() == 2 { (x.unsqueeze(0)?, true) } else { (x.clone(), false) };
97        if x3d.shape().len() != 3 {
98            return Err(tensor_op_error(
99                "FourierTransform::apply_dft",
100                format!(
101                    "expected a [seq, hidden] or [batch, seq, hidden] tensor, got shape {:?}",
102                    x.shape()
103                ),
104            ));
105        }
106
107        // DFT along the sequence axis. The input is real, so the transform's
108        // imaginary part starts here.
109        let (real_seq, imag_seq) = self.dft_1d_complex(&x3d, None, 1)?;
110
111        // DFT along the hidden axis, carrying the complex intermediate.
112        let (real_both, _imag_both) = self.dft_1d_complex(&real_seq, Some(&imag_seq), 2)?;
113
114        // Take the real part (FNet discards the imaginary component).
115        let out3d = real_both;
116
117        // Restore original rank if input was 2-D
118        if was_2d {
119            out3d.squeeze(0)
120        } else {
121            Ok(out3d)
122        }
123    }
124
125    /// Apply Real DFT (more efficient variant)
126    ///
127    /// For a real-valued input the negative frequencies are the conjugates of
128    /// the positive ones, so the real part of the full transform is identical to
129    /// the real part of the half-spectrum transform. The result is therefore the
130    /// same as [`FourierTransform::apply_dft`], and this variant delegates to it
131    /// rather than pretending to a different numeric result.
132    ///
133    /// # Errors
134    ///
135    /// See [`FourierTransform::apply_dft`].
136    fn apply_real_dft(&self, x: &Tensor) -> Result<Tensor> {
137        self.apply_dft(x)
138    }
139
140    /// Apply Discrete Cosine Transform (DCT)
141    fn apply_dct(&self, x: &Tensor) -> Result<Tensor> {
142        // DCT is real-valued and often more efficient than DFT
143        // For now, approximate with cosine-based transformation
144        // Normalise to 3-D so all downstream math is consistent.
145        let (x, was_2d) =
146            if x.shape().len() == 2 { (x.unsqueeze(0)?, true) } else { (x.clone(), false) };
147        let batch_size = x.shape()[0];
148        let seq_len = x.shape()[1];
149        let hidden_size = x.shape()[2];
150
151        // Create DCT basis matrices
152        let seq_dct_matrix = self.create_dct_matrix(seq_len)?;
153        let hidden_dct_matrix = self.create_dct_matrix(hidden_size)?;
154
155        // Apply DCT along sequence dimension using reshape to keep matmul 2-D.
156        // Transpose to [batch, hidden_size, seq_len], flatten to [batch*hidden, seq_len],
157        // apply DCT matrix, then restore original shape.
158        let seq_shape = seq_dct_matrix.shape();
159        let seq_dim0 = seq_shape.len().saturating_sub(2);
160        let seq_dim1 = seq_shape.len().saturating_sub(1);
161        let seq_dct_t = seq_dct_matrix.transpose(seq_dim0, seq_dim1)?;
162        let x_t = x.transpose(1, 2)?; // [batch, hidden, seq]
163        let x_t_flat = x_t.reshape(&[batch_size * hidden_size, seq_len])?;
164        let seq_out_flat = x_t_flat.matmul(&seq_dct_t)?;
165        let seq_out_t = seq_out_flat.reshape(&[batch_size, hidden_size, seq_len])?;
166        let x_seq_dct = seq_out_t.transpose(1, 2)?; // back to [batch, seq, hidden]
167
168        // Apply DCT along hidden dimension
169        // For hidden dimension: reshape, apply DCT, reshape back
170        let reshaped = x_seq_dct.reshape(&[batch_size * seq_len, hidden_size])?;
171        let hidden_shape = hidden_dct_matrix.shape();
172        let hidden_dim0 = hidden_shape.len().saturating_sub(2);
173        let hidden_dim1 = hidden_shape.len().saturating_sub(1);
174        let hidden_dct =
175            reshaped.matmul(&hidden_dct_matrix.transpose(hidden_dim0, hidden_dim1)?)?;
176        let out3d = hidden_dct.reshape(&[batch_size, seq_len, hidden_size])?;
177
178        // Restore original rank if input was 2-D
179        if was_2d {
180            out3d.squeeze(0)
181        } else {
182            Ok(out3d)
183        }
184    }
185
186    /// Create DCT transformation matrix
187    fn create_dct_matrix(&self, n: usize) -> Result<Tensor> {
188        let mut matrix = Vec::new();
189        let pi = std::f32::consts::PI;
190
191        for k in 0..n {
192            for i in 0..n {
193                let value = if k == 0 {
194                    (1.0 / n as f32).sqrt()
195                } else {
196                    (2.0 / n as f32).sqrt()
197                        * (pi * k as f32 * (2 * i + 1) as f32 / (2 * n) as f32).cos()
198                };
199                matrix.push(value);
200            }
201        }
202
203        Tensor::from_vec(matrix, &[n, n])
204    }
205
206    /// Orthonormal 1-D DFT basis matrices `C[k, j] = cos(2πkj/n)/√n` and
207    /// `S[k, j] = sin(2πkj/n)/√n`.
208    ///
209    /// The forward transform is `X[k] = Σ_j x[j] e^{-2πi kj/n} / √n`, i.e.
210    /// `Re(X) = C·x` and `Im(X) = −S·x` for a real `x`.
211    ///
212    /// # Errors
213    ///
214    /// Fails when `n` is 0 or when the basis tensors cannot be built.
215    fn dft_basis(&self, n: usize) -> Result<(Tensor, Tensor)> {
216        if n == 0 {
217            return Err(tensor_op_error(
218                "FourierTransform::dft_basis",
219                "cannot build a DFT basis for a zero-length axis".to_string(),
220            ));
221        }
222        let mut cos_matrix = Vec::with_capacity(n * n);
223        let mut sin_matrix = Vec::with_capacity(n * n);
224        let scale = 1.0 / (n as f32).sqrt();
225        let two_pi = 2.0 * std::f32::consts::PI;
226        for k in 0..n {
227            for j in 0..n {
228                // (k*j) mod n keeps the angle small for long axes, which matters
229                // for f32 precision once k*j exceeds 2^24.
230                let angle = two_pi * ((k * j) % n) as f32 / n as f32;
231                cos_matrix.push(angle.cos() * scale);
232                sin_matrix.push(angle.sin() * scale);
233            }
234        }
235        Ok((
236            Tensor::from_vec(cos_matrix, &[n, n])?,
237            Tensor::from_vec(sin_matrix, &[n, n])?,
238        ))
239    }
240
241    /// Apply a 1-D DFT along `dim` to a complex-valued 3-D tensor.
242    ///
243    /// The input is `real + i·imag` (`imag = None` means a real input). The
244    /// transform is the orthonormal forward DFT, so with `C = cos` and
245    /// `S = sin` bases:
246    ///
247    /// ```text
248    /// Re(out) = C·real + S·imag
249    /// Im(out) = C·imag − S·real
250    /// ```
251    ///
252    /// Both components are returned, because dropping the imaginary part between
253    /// the two axes of a 2-D transform changes the result — that omission is
254    /// what made the previous cosine-only implementation something other than a
255    /// Fourier transform.
256    ///
257    /// # Errors
258    ///
259    /// Fails when `dim` is not 1 or 2, when the tensor is not 3-D, or when a
260    /// reshape / matmul fails.
261    fn dft_1d_complex(
262        &self,
263        real: &Tensor,
264        imag: Option<&Tensor>,
265        dim: usize,
266    ) -> Result<(Tensor, Tensor)> {
267        let shape = real.shape();
268        if shape.len() != 3 {
269            return Err(tensor_op_error(
270                "FourierTransform::dft_1d_complex",
271                format!("expected a 3-D tensor, got shape {shape:?}"),
272            ));
273        }
274        if dim != 1 && dim != 2 {
275            return Err(tensor_op_error(
276                "FourierTransform::dft_1d_complex",
277                format!("DFT axis must be 1 (sequence) or 2 (hidden), got {dim}"),
278            ));
279        }
280        let batch_size = shape[0];
281        let seq_len = shape[1];
282        let hidden_size = shape[2];
283        let n = shape[dim];
284
285        let (cos_basis, sin_basis) = self.dft_basis(n)?;
286        // The rows of the basis are frequencies; a right-multiply `x @ Bᵀ`
287        // computes `Σ_j x[.., j] B[k, j]` for every k, which is the transform.
288        let cos_t = cos_basis.transpose(0, 1)?;
289        let sin_t = sin_basis.transpose(0, 1)?;
290
291        // Flatten so the axis under transform is the last one and the matmul is 2-D.
292        let flatten = |t: &Tensor| -> Result<Tensor> {
293            if dim == 1 {
294                // [batch, seq, hidden] -> [batch, hidden, seq] -> [batch*hidden, seq]
295                t.transpose(1, 2)?.reshape(&[batch_size * hidden_size, seq_len])
296            } else {
297                t.reshape(&[batch_size * seq_len, hidden_size])
298            }
299        };
300        let restore = |t: Tensor| -> Result<Tensor> {
301            if dim == 1 {
302                t.reshape(&[batch_size, hidden_size, seq_len])?.transpose(1, 2)
303            } else {
304                t.reshape(&[batch_size, seq_len, hidden_size])
305            }
306        };
307
308        let real_flat = flatten(real)?;
309        let real_cos = real_flat.matmul(&cos_t)?;
310        let real_sin = real_flat.matmul(&sin_t)?;
311
312        let (out_real_flat, out_imag_flat) = match imag {
313            Some(imag) => {
314                let imag_flat = flatten(imag)?;
315                let imag_cos = imag_flat.matmul(&cos_t)?;
316                let imag_sin = imag_flat.matmul(&sin_t)?;
317                // Re = C·re + S·im ; Im = C·im − S·re
318                (real_cos.add(&imag_sin)?, imag_cos.sub(&real_sin)?)
319            },
320            // Real input: Re = C·re ; Im = −S·re
321            None => (real_cos, real_sin.scalar_mul(-1.0)?),
322        };
323
324        Ok((restore(out_real_flat)?, restore(out_imag_flat)?))
325    }
326}
327
328impl Layer for FourierTransform {
329    type Input = Tensor;
330    type Output = Tensor;
331
332    fn forward(&self, input: Self::Input) -> Result<Self::Output> {
333        // Apply the appropriate Fourier transform
334        let fourier_output = match self.fourier_type.as_str() {
335            "dft" => self.apply_dft(&input)?,
336            "real_dft" => self.apply_real_dft(&input)?,
337            "dct" => self.apply_dct(&input)?,
338            _ => self.apply_dft(&input)?, // Default to DFT
339        };
340
341        // Apply bias if configured
342        let output = if let Some(ref bias_layer) = self.bias {
343            bias_layer.forward(fourier_output)?
344        } else {
345            fourier_output
346        };
347
348        // Apply dropout if configured (in training mode)
349        // For inference, we skip dropout
350        Ok(output)
351    }
352}
353
354/// FNet feed-forward network (same as BERT)
355pub struct FNetFeedForward {
356    pub(crate) dense1: Linear,
357    pub(crate) dense2: Linear,
358    activation: ActivationType,
359    #[allow(dead_code)]
360    dropout: f32,
361    device: Device,
362}
363
364impl FNetFeedForward {
365    pub fn new(config: &FNetConfig) -> Result<Self> {
366        Self::new_with_device(config, Device::CPU)
367    }
368
369    pub fn new_with_device(config: &FNetConfig, device: Device) -> Result<Self> {
370        let dense1 =
371            Linear::new_with_device(config.hidden_size, config.intermediate_size, true, device);
372        let dense2 =
373            Linear::new_with_device(config.intermediate_size, config.hidden_size, true, device);
374
375        Ok(Self {
376            dense1,
377            dense2,
378            activation: ActivationType::from_config_str_or(
379                &config.hidden_act,
380                ActivationType::Identity,
381            ),
382            dropout: config.hidden_dropout_prob,
383            device,
384        })
385    }
386
387    pub fn device(&self) -> Device {
388        self.device
389    }
390
391    pub fn parameter_count(&self) -> usize {
392        self.dense1.parameter_count() + self.dense2.parameter_count()
393    }
394
395    fn apply_activation(&self, x: &Tensor) -> Result<Tensor> {
396        self.activation.apply(x)
397    }
398}
399
400impl Layer for FNetFeedForward {
401    type Input = Tensor;
402    type Output = Tensor;
403
404    fn forward(&self, input: Self::Input) -> Result<Self::Output> {
405        let hidden = self.dense1.forward(input)?;
406        let hidden = self.apply_activation(&hidden)?;
407        self.dense2.forward(hidden)
408    }
409}
410
411/// FNet encoder layer (Fourier + FFN)
412pub struct FNetLayer {
413    fourier_transform: FourierTransform,
414    pub(crate) feed_forward: FNetFeedForward,
415    pub(crate) fourier_norm: LayerNorm,
416    pub(crate) output_norm: LayerNorm,
417    device: Device,
418}
419
420impl FNetLayer {
421    pub fn new(config: &FNetConfig) -> Result<Self> {
422        Self::new_with_device(config, Device::CPU)
423    }
424
425    pub fn new_with_device(config: &FNetConfig, device: Device) -> Result<Self> {
426        let fourier_transform = FourierTransform::new_with_device(config, device)?;
427        let feed_forward = FNetFeedForward::new_with_device(config, device)?;
428        let fourier_norm =
429            LayerNorm::new_with_device(vec![config.hidden_size], config.layer_norm_eps, device)?;
430        let output_norm =
431            LayerNorm::new_with_device(vec![config.hidden_size], config.layer_norm_eps, device)?;
432
433        Ok(Self {
434            fourier_transform,
435            feed_forward,
436            fourier_norm,
437            output_norm,
438            device,
439        })
440    }
441
442    pub fn device(&self) -> Device {
443        self.device
444    }
445
446    pub fn parameter_count(&self) -> usize {
447        self.fourier_transform.parameter_count()
448            + self.feed_forward.parameter_count()
449            + self.fourier_norm.parameter_count()
450            + self.output_norm.parameter_count()
451    }
452}
453
454impl Layer for FNetLayer {
455    type Input = Tensor;
456    type Output = Tensor;
457
458    fn forward(&self, input: Self::Input) -> Result<Self::Output> {
459        // Fourier transform with residual connection and layer norm
460        let fourier_output = self.fourier_transform.forward(input.clone())?;
461        let fourier_output = input.add(&fourier_output)?; // Residual
462        let fourier_output = self.fourier_norm.forward(fourier_output)?;
463
464        // Feed-forward with residual connection and layer norm
465        let ff_output = self.feed_forward.forward(fourier_output.clone())?;
466        let output = fourier_output.add(&ff_output)?; // Residual
467        self.output_norm.forward(output)
468    }
469}
470
471/// FNet embeddings (same as BERT)
472pub struct FNetEmbeddings {
473    pub(crate) word_embeddings: Embedding,
474    pub(crate) position_embeddings: Embedding,
475    pub(crate) token_type_embeddings: Embedding,
476    pub(crate) layer_norm: LayerNorm,
477    #[allow(dead_code)]
478    dropout: f32,
479    device: Device,
480}
481
482impl FNetEmbeddings {
483    pub fn new(config: &FNetConfig) -> Result<Self> {
484        Self::new_with_device(config, Device::CPU)
485    }
486
487    pub fn new_with_device(config: &FNetConfig, device: Device) -> Result<Self> {
488        let word_embeddings = Embedding::new_with_device(
489            config.vocab_size,
490            config.hidden_size,
491            Some(config.pad_token_id as usize),
492            device,
493        )?;
494        let position_embeddings = Embedding::new_with_device(
495            config.max_position_embeddings,
496            config.hidden_size,
497            None,
498            device,
499        )?;
500        let token_type_embeddings =
501            Embedding::new_with_device(config.type_vocab_size, config.hidden_size, None, device)?;
502        let layer_norm =
503            LayerNorm::new_with_device(vec![config.hidden_size], config.layer_norm_eps, device)?;
504
505        Ok(Self {
506            word_embeddings,
507            position_embeddings,
508            token_type_embeddings,
509            layer_norm,
510            dropout: config.hidden_dropout_prob,
511            device,
512        })
513    }
514
515    pub fn device(&self) -> Device {
516        self.device
517    }
518
519    pub fn parameter_count(&self) -> usize {
520        self.word_embeddings.parameter_count()
521            + self.position_embeddings.parameter_count()
522            + self.token_type_embeddings.parameter_count()
523            + self.layer_norm.parameter_count()
524    }
525}
526
527impl Layer for FNetEmbeddings {
528    type Input = (Vec<u32>, Option<Vec<u32>>, Option<Vec<u32>>);
529    type Output = Tensor;
530
531    fn forward(&self, input: Self::Input) -> Result<Self::Output> {
532        let (input_ids, token_type_ids, position_ids) = input;
533        let seq_len = input_ids.len();
534
535        let words_embeddings = self.word_embeddings.forward(input_ids)?;
536
537        let position_ids = position_ids.unwrap_or_else(|| (0..seq_len as u32).collect());
538        let position_embeddings = self.position_embeddings.forward(position_ids)?;
539
540        let token_type_ids = token_type_ids.unwrap_or_else(|| vec![0; seq_len]);
541        let token_type_embeddings = self.token_type_embeddings.forward(token_type_ids)?;
542
543        let embeddings = words_embeddings.add(&position_embeddings)?.add(&token_type_embeddings)?;
544        let embeddings = self.layer_norm.forward(embeddings)?;
545
546        Ok(embeddings)
547    }
548}
549
550/// FNet encoder
551pub struct FNetEncoder {
552    pub(crate) layers: Vec<FNetLayer>,
553    device: Device,
554}
555
556impl FNetEncoder {
557    pub fn new(config: &FNetConfig) -> Result<Self> {
558        Self::new_with_device(config, Device::CPU)
559    }
560
561    pub fn new_with_device(config: &FNetConfig, device: Device) -> Result<Self> {
562        let mut layers = Vec::new();
563        for _ in 0..config.num_hidden_layers {
564            layers.push(FNetLayer::new_with_device(config, device)?);
565        }
566
567        Ok(Self { layers, device })
568    }
569
570    pub fn device(&self) -> Device {
571        self.device
572    }
573
574    pub fn parameter_count(&self) -> usize {
575        self.layers.iter().map(|layer| layer.parameter_count()).sum()
576    }
577}
578
579impl Layer for FNetEncoder {
580    type Input = Tensor;
581    type Output = Tensor;
582
583    fn forward(&self, input: Self::Input) -> Result<Self::Output> {
584        let mut hidden_states = input;
585
586        for layer in &self.layers {
587            hidden_states = layer.forward(hidden_states)?;
588        }
589
590        Ok(hidden_states)
591    }
592}
593
594/// FNet model
595pub struct FNetModel {
596    config: FNetConfig,
597    embeddings: FNetEmbeddings,
598    encoder: FNetEncoder,
599    device: Device,
600}
601
602impl FNetModel {
603    pub fn new(config: FNetConfig) -> Result<Self> {
604        Self::new_with_device(config, Device::CPU)
605    }
606
607    pub fn new_with_device(config: FNetConfig, device: Device) -> Result<Self> {
608        config.validate()?;
609
610        let embeddings = FNetEmbeddings::new_with_device(&config, device)?;
611        let encoder = FNetEncoder::new_with_device(&config, device)?;
612
613        Ok(Self {
614            config,
615            embeddings,
616            encoder,
617            device,
618        })
619    }
620
621    pub fn device(&self) -> Device {
622        self.device
623    }
624}
625
626impl Model for FNetModel {
627    type Config = FNetConfig;
628    type Input = (Vec<u32>, Option<Vec<u32>>, Option<Vec<u32>>);
629    type Output = Tensor;
630
631    fn forward(&self, input: Self::Input) -> Result<Self::Output> {
632        let embeddings = self.embeddings.forward(input)?;
633        let sequence_output = self.encoder.forward(embeddings)?;
634        Ok(sequence_output)
635    }
636
637    /// Load a HuggingFace FNet checkpoint (safetensors or `torch.save`).
638    ///
639    /// A previous revision was `Ok(())` — the reader was never touched, so every
640    /// "load" left the model randomly initialised while reporting success. See
641    /// [`FNetModel::load_from_checkpoint`] for the name map.
642    fn load_pretrained(&mut self, reader: &mut dyn Read) -> Result<()> {
643        self.load_pretrained_report(reader).map(|_| ())
644    }
645
646    fn get_config(&self) -> &Self::Config {
647        &self.config
648    }
649
650    fn num_parameters(&self) -> usize {
651        self.embeddings.parameter_count() + self.encoder.parameter_count()
652    }
653}
654
655/// FNet for sequence classification
656pub struct FNetForSequenceClassification {
657    fnet: FNetModel,
658    classifier: Linear,
659    #[allow(dead_code)]
660    num_labels: usize,
661    device: Device,
662}
663
664impl FNetForSequenceClassification {
665    pub fn new(config: FNetConfig, num_labels: usize) -> Result<Self> {
666        Self::new_with_device(config, num_labels, Device::CPU)
667    }
668
669    pub fn new_with_device(config: FNetConfig, num_labels: usize, device: Device) -> Result<Self> {
670        let fnet = FNetModel::new_with_device(config.clone(), device)?;
671        let classifier = Linear::new_with_device(config.hidden_size, num_labels, true, device);
672
673        Ok(Self {
674            fnet,
675            classifier,
676            num_labels,
677            device,
678        })
679    }
680
681    pub fn device(&self) -> Device {
682        self.device
683    }
684}
685
686impl Model for FNetForSequenceClassification {
687    type Config = FNetConfig;
688    type Input = (Vec<u32>, Option<Vec<u32>>, Option<Vec<u32>>);
689    type Output = Tensor;
690
691    fn forward(&self, input: Self::Input) -> Result<Self::Output> {
692        let sequence_output = self.fnet.forward(input)?;
693        // Extract CLS token (position 0 of sequence dimension).
694        // sequence_output may be 2-D [seq_len, hidden] or 3-D [batch, seq_len, hidden].
695        let cls_output = if sequence_output.shape().len() == 3 {
696            // 3-D: [batch, seq_len, hidden] → slice seq dim → [batch, 1, hidden] → squeeze → [batch, hidden]
697            let sliced = sequence_output.slice(1, 0, 1)?;
698            sliced.squeeze(1)?
699        } else {
700            // 2-D: [seq_len, hidden] → slice first row → [1, hidden] (keep 2-D for Linear)
701            sequence_output.slice(0, 0, 1)?
702        };
703        self.classifier.forward(cls_output)
704    }
705
706    /// Load the encoder and, when the checkpoint carries one, the classifier head.
707    ///
708    /// # Errors
709    ///
710    /// See [`FNetForSequenceClassification::load_pretrained_report`].
711    fn load_pretrained(&mut self, reader: &mut dyn Read) -> Result<()> {
712        self.load_pretrained_report(reader).map(|_| ())
713    }
714
715    fn get_config(&self) -> &Self::Config {
716        self.fnet.get_config()
717    }
718
719    fn num_parameters(&self) -> usize {
720        self.fnet.num_parameters() + self.classifier.parameter_count()
721    }
722}
723
724impl FNetForSequenceClassification {
725    /// The checkpoint namespaces this wrapper binds, and therefore must fully
726    /// consume.
727    ///
728    /// See [`BoundNamespaces`] for why a wrapper is stricter than the bare
729    /// encoder over the very names it binds.
730    const BOUND_NAMESPACES: BoundNamespaces<'static> = BoundNamespaces::new(&["classifier."]);
731
732    /// Load the encoder and the classification head, reporting what was bound.
733    ///
734    /// A previous revision delegated straight to `FNetModel::load_pretrained`,
735    /// which binds the encoder only. `FNetModel`'s unused-tensor policy tolerates
736    /// the `classifier.` namespace, so a fine-tuned checkpoint's head was
737    /// silently dropped: inference then ran through a constructor-initialised
738    /// classifier while `load_pretrained` returned `Ok(())`.
739    ///
740    /// A checkpoint that carries no head at all — a plain pretrained encoder — is
741    /// still accepted, but the absent head tensors are recorded in
742    /// [`LoadReport::missing`] so the caller can see the layer kept its
743    /// initialisation rather than being told everything was loaded.
744    ///
745    /// # Errors
746    ///
747    /// Fails when the checkpoint cannot be parsed, when an encoder parameter is
748    /// missing, or when the head is present with the wrong shape.
749    pub fn load_pretrained_report(&mut self, reader: &mut dyn Read) -> Result<LoadReport> {
750        let checkpoint = Checkpoint::from_reader(reader)?;
751        let mut report = self.fnet.load_from_checkpoint(&checkpoint)?;
752        let hidden = self.fnet.get_config().hidden_size;
753        bind_head_linear(
754            &checkpoint,
755            &mut report,
756            "classifier",
757            [self.num_labels, hidden],
758            &mut self.classifier,
759        )?;
760        Self::BOUND_NAMESPACES.verify(&report)?;
761        Ok(report)
762    }
763}
764
765/// FNet's masked-language-modelling prediction head.
766///
767/// HuggingFace's `FNetLMPredictionHead` is a `transform` block — a square dense
768/// projection, GELU and a `LayerNorm` — followed by a `decoder` back to the
769/// vocabulary, exactly the layout BERT uses. A previous revision of this crate
770/// collapsed the head to a single `Linear`, which meant a real
771/// `FNetForMaskedLM` checkpoint could not be represented at all: its
772/// `cls.predictions.transform.*` tensors had nowhere to land and were dropped
773/// while the load reported success.
774pub struct FNetLMHead {
775    dense: Linear,
776    layer_norm: LayerNorm,
777    decoder: Linear,
778}
779
780impl FNetLMHead {
781    /// Build the head for `config` on `device`.
782    ///
783    /// # Errors
784    ///
785    /// Fails when the LayerNorm cannot be constructed for `hidden_size`.
786    pub fn new_with_device(config: &FNetConfig, device: Device) -> Result<Self> {
787        Ok(Self {
788            dense: Linear::new_with_device(config.hidden_size, config.hidden_size, true, device),
789            layer_norm: LayerNorm::new_with_device(
790                vec![config.hidden_size],
791                config.layer_norm_eps,
792                device,
793            )?,
794            decoder: Linear::new_with_device(config.hidden_size, config.vocab_size, true, device),
795        })
796    }
797
798    /// dense → GELU → LayerNorm → decoder.
799    ///
800    /// # Errors
801    ///
802    /// Propagates any layer failure.
803    pub fn forward(&self, hidden_states: Tensor) -> Result<Tensor> {
804        let hidden_states = self.dense.forward(hidden_states)?;
805        let hidden_states = trustformers_core::ops::activations::gelu(&hidden_states)?;
806        let hidden_states = self.layer_norm.forward(hidden_states)?;
807        self.decoder.forward(hidden_states)
808    }
809
810    /// Total learnable parameters of the head.
811    pub fn parameter_count(&self) -> usize {
812        self.dense.parameter_count()
813            + self.layer_norm.parameter_count()
814            + self.decoder.parameter_count()
815    }
816}
817
818/// FNet for masked language modeling
819pub struct FNetForMaskedLM {
820    fnet: FNetModel,
821    mlm_head: FNetLMHead,
822    device: Device,
823}
824
825impl FNetForMaskedLM {
826    /// The checkpoint namespaces this wrapper binds, and therefore must fully
827    /// consume.
828    ///
829    /// See [`BoundNamespaces`] for why a wrapper is stricter than the bare
830    /// encoder over the very names it binds.
831    const BOUND_NAMESPACES: BoundNamespaces<'static> = BoundNamespaces::new(&["cls.predictions."]);
832
833    pub fn new(config: FNetConfig) -> Result<Self> {
834        Self::new_with_device(config, Device::CPU)
835    }
836
837    pub fn new_with_device(config: FNetConfig, device: Device) -> Result<Self> {
838        let fnet = FNetModel::new_with_device(config.clone(), device)?;
839        let mlm_head = FNetLMHead::new_with_device(&config, device)?;
840
841        Ok(Self {
842            fnet,
843            mlm_head,
844            device,
845        })
846    }
847
848    pub fn device(&self) -> Device {
849        self.device
850    }
851
852    /// Load the encoder and the masked-LM head, reporting what was bound.
853    ///
854    /// A previous revision delegated straight to `FNetModel::load_pretrained`,
855    /// which binds the encoder only. `FNetModel`'s unused-tensor policy tolerates
856    /// the `cls.` namespace, so the whole prediction head was silently dropped
857    /// while `load_pretrained` returned `Ok(())`.
858    ///
859    /// HuggingFace declares the decoder with `bias=False` and aliases
860    /// `decoder.bias` onto a separate `cls.predictions.bias` parameter, so a real
861    /// checkpoint may spell the output bias either way; both are accepted, and
862    /// the canonical `cls.predictions.bias` wins when the checkpoint has both.
863    ///
864    /// # Errors
865    ///
866    /// Fails when the checkpoint cannot be parsed, when an encoder parameter is
867    /// missing, or when a head tensor is present with the wrong shape.
868    pub fn load_pretrained_report(&mut self, reader: &mut dyn Read) -> Result<LoadReport> {
869        let checkpoint = Checkpoint::from_reader(reader)?;
870        let mut report = self.fnet.load_from_checkpoint(&checkpoint)?;
871
872        let config = self.fnet.get_config().clone();
873        let hidden = config.hidden_size;
874        let vocab = config.vocab_size;
875
876        bind_head_linear(
877            &checkpoint,
878            &mut report,
879            "cls.predictions.transform.dense",
880            [hidden, hidden],
881            &mut self.mlm_head.dense,
882        )?;
883        bind_head_layer_norm(
884            &checkpoint,
885            &mut report,
886            "cls.predictions.transform.LayerNorm",
887            hidden,
888            &mut self.mlm_head.layer_norm,
889        )?;
890
891        let decoder_weight = "cls.predictions.decoder.weight";
892        match checkpoint.take_shaped(decoder_weight, &[vocab, hidden])? {
893            Some(weight) => {
894                self.mlm_head.decoder.set_weight(weight)?;
895                report.mark_loaded(decoder_weight);
896            },
897            None => report.note_absent(decoder_weight),
898        }
899
900        let canonical_bias = "cls.predictions.bias";
901        let aliased_bias = "cls.predictions.decoder.bias";
902        let bias_name =
903            if checkpoint.contains(canonical_bias) { canonical_bias } else { aliased_bias };
904        match checkpoint.take_shaped(bias_name, &[vocab])? {
905            Some(bias) => {
906                self.mlm_head.decoder.set_bias(bias)?;
907                report.mark_loaded(bias_name);
908                // The two spellings alias one parameter; note the other as
909                // consumed so a checkpoint carrying both is fully accounted for.
910                if checkpoint.contains(aliased_bias) && bias_name == canonical_bias {
911                    report.mark_loaded(aliased_bias);
912                }
913            },
914            None => report.note_absent(canonical_bias),
915        }
916
917        Self::BOUND_NAMESPACES.verify(&report)?;
918        Ok(report)
919    }
920}
921
922impl Model for FNetForMaskedLM {
923    type Config = FNetConfig;
924    type Input = (Vec<u32>, Option<Vec<u32>>, Option<Vec<u32>>);
925    type Output = Tensor;
926
927    fn forward(&self, input: Self::Input) -> Result<Self::Output> {
928        let sequence_output = self.fnet.forward(input)?;
929        self.mlm_head.forward(sequence_output)
930    }
931
932    /// Load the encoder and, when the checkpoint carries one, the prediction head.
933    ///
934    /// # Errors
935    ///
936    /// See [`FNetForMaskedLM::load_pretrained_report`].
937    fn load_pretrained(&mut self, reader: &mut dyn Read) -> Result<()> {
938        self.load_pretrained_report(reader).map(|_| ())
939    }
940
941    fn get_config(&self) -> &Self::Config {
942        self.fnet.get_config()
943    }
944
945    fn num_parameters(&self) -> usize {
946        self.fnet.num_parameters() + self.mlm_head.parameter_count()
947    }
948}
949
950impl FNetModel {
951    /// Checkpoint namespaces an FNet encoder legitimately does not consume.
952    pub(crate) const ALLOWED_UNUSED_PREFIXES: &'static [&'static str] =
953        &["cls.", "classifier.", "qa_outputs.", "pooler."];
954
955    /// Non-parameter buffers HuggingFace stores alongside FNet's weights.
956    pub(crate) const ALLOWED_UNUSED_SUFFIXES: &'static [&'static str] =
957        &["embeddings.position_ids", "embeddings.token_type_ids"];
958
959    /// Load pretrained weights and report exactly what was bound.
960    ///
961    /// # Errors
962    ///
963    /// See [`FNetModel::load_from_checkpoint`].
964    pub fn load_pretrained_report(&mut self, reader: &mut dyn Read) -> Result<LoadReport> {
965        let checkpoint = Checkpoint::from_reader(reader)?;
966        self.load_from_checkpoint(&checkpoint)
967    }
968
969    /// Bind an already-parsed checkpoint into this model.
970    ///
971    /// FNet is BERT with self-attention replaced by a parameter-free 2-D Fourier
972    /// transform, so its checkpoints carry BERT's embedding and feed-forward
973    /// tensors and simply *omit* every `attention.self.*` / `attention.output.*`
974    /// projection — the mixing layer has no weights to store. The two per-layer
975    /// norms keep their HuggingFace spellings (`fourier.output.LayerNorm` and
976    /// `output.LayerNorm`).
977    ///
978    /// # Errors
979    ///
980    /// Fails when the checkpoint does not look like an FNet checkpoint, when a
981    /// tensor has the wrong shape, when a parameter is missing, or when the
982    /// checkpoint carries weights this architecture does not recognise.
983    pub fn load_from_checkpoint(&mut self, checkpoint: &Checkpoint) -> Result<LoadReport> {
984        let prefix =
985            checkpoint.detect_prefix(&["", "fnet."], "embeddings.word_embeddings.weight")?;
986        let mut binder = checkpoint.binder(&prefix);
987
988        let config = self.config.clone();
989        let hidden = config.hidden_size;
990        let intermediate = config.intermediate_size;
991
992        bind_embedding(
993            &mut binder,
994            "embeddings.word_embeddings",
995            config.vocab_size,
996            hidden,
997            &mut self.embeddings.word_embeddings,
998        )?;
999        bind_embedding(
1000            &mut binder,
1001            "embeddings.position_embeddings",
1002            config.max_position_embeddings,
1003            hidden,
1004            &mut self.embeddings.position_embeddings,
1005        )?;
1006        bind_embedding(
1007            &mut binder,
1008            "embeddings.token_type_embeddings",
1009            config.type_vocab_size,
1010            hidden,
1011            &mut self.embeddings.token_type_embeddings,
1012        )?;
1013        if let Some(w) = take_norm_weight(&mut binder, "embeddings.LayerNorm", hidden)? {
1014            self.embeddings.layer_norm.set_weight(w)?;
1015        }
1016        if let Some(b) = take_norm_bias(&mut binder, "embeddings.LayerNorm", hidden)? {
1017            self.embeddings.layer_norm.set_bias(b)?;
1018        }
1019
1020        for (index, layer) in self.encoder.layers.iter_mut().enumerate() {
1021            let base = format!("encoder.layer.{index}");
1022
1023            // The Fourier mixing layer itself has no parameters; only the
1024            // residual norm that follows it does.
1025            let fourier_norm = format!("{base}.fourier.output.LayerNorm");
1026            if let Some(w) = take_norm_weight(&mut binder, &fourier_norm, hidden)? {
1027                layer.fourier_norm.set_weight(w)?;
1028            }
1029            if let Some(b) = take_norm_bias(&mut binder, &fourier_norm, hidden)? {
1030                layer.fourier_norm.set_bias(b)?;
1031            }
1032
1033            bind_linear(
1034                &mut binder,
1035                &format!("{base}.intermediate.dense"),
1036                intermediate,
1037                hidden,
1038                true,
1039                &mut layer.feed_forward.dense1,
1040            )?;
1041            bind_linear(
1042                &mut binder,
1043                &format!("{base}.output.dense"),
1044                hidden,
1045                intermediate,
1046                true,
1047                &mut layer.feed_forward.dense2,
1048            )?;
1049
1050            let output_norm = format!("{base}.output.LayerNorm");
1051            if let Some(w) = take_norm_weight(&mut binder, &output_norm, hidden)? {
1052                layer.output_norm.set_weight(w)?;
1053            }
1054            if let Some(b) = take_norm_bias(&mut binder, &output_norm, hidden)? {
1055                layer.output_norm.set_bias(b)?;
1056            }
1057        }
1058
1059        binder.finish(UnusedTensors::new(
1060            Self::ALLOWED_UNUSED_PREFIXES,
1061            Self::ALLOWED_UNUSED_SUFFIXES,
1062        ))
1063    }
1064}
1065
1066// ─────────────────────────────────────────────────────────────────────────────
1067// Tests
1068// ─────────────────────────────────────────────────────────────────────────────
1069
1070#[cfg(test)]
1071mod tests {
1072    use super::*;
1073    use crate::fnet::config::FNetConfig;
1074    use trustformers_core::{
1075        tensor::Tensor,
1076        traits::{Config, Model},
1077    };
1078
1079    fn tiny_config() -> FNetConfig {
1080        FNetConfig {
1081            vocab_size: 64,
1082            hidden_size: 16,
1083            num_hidden_layers: 2,
1084            intermediate_size: 32,
1085            hidden_act: "gelu".to_string(),
1086            hidden_dropout_prob: 0.0,
1087            max_position_embeddings: 32,
1088            type_vocab_size: 2,
1089            initializer_range: 0.02,
1090            layer_norm_eps: 1e-12,
1091            pad_token_id: 0,
1092            position_embedding_type: "absolute".to_string(),
1093            use_fourier_transform: true,
1094            use_tpu_optimized_fft: false,
1095            fourier_transform_type: "dft".to_string(),
1096            use_bias_in_fourier: false,
1097            fourier_dropout_prob: 0.0,
1098        }
1099    }
1100
1101    fn make_input(seq_len: usize) -> (Vec<u32>, Option<Vec<u32>>, Option<Vec<u32>>) {
1102        let ids: Vec<u32> = (0..seq_len as u32).collect();
1103        (ids, None, None)
1104    }
1105
1106    // ── Fourier transform correctness ────────────────────────────────────────
1107
1108    /// Reference orthonormal 2-D DFT real part, computed directly from the
1109    /// definition with `f64` complex accumulation.
1110    fn reference_dft_real(values: &[f32], rows: usize, cols: usize) -> Vec<f32> {
1111        let mut out = vec![0.0f32; rows * cols];
1112        let scale = 1.0 / ((rows as f64).sqrt() * (cols as f64).sqrt());
1113        for k in 0..rows {
1114            for l in 0..cols {
1115                let mut re = 0.0f64;
1116                for n in 0..rows {
1117                    for m in 0..cols {
1118                        let angle = -2.0
1119                            * std::f64::consts::PI
1120                            * ((k * n) as f64 / rows as f64 + (l * m) as f64 / cols as f64);
1121                        re += values[n * cols + m] as f64 * angle.cos();
1122                    }
1123                }
1124                out[k * cols + l] = (re * scale) as f32;
1125            }
1126        }
1127        out
1128    }
1129
1130    fn fourier_layer(kind: &str) -> FourierTransform {
1131        let mut config = tiny_config();
1132        config.fourier_transform_type = kind.to_string();
1133        config.use_bias_in_fourier = false;
1134        FourierTransform::new(&config).expect("Fourier layer must build")
1135    }
1136
1137    /// Regression: `apply_dft` used a cosine-only basis applied twice, dropping
1138    /// the `−sin·sin` cross term of the separable 2-D transform. That is a
1139    /// different linear map, so its output does not match the real part of a
1140    /// genuine 2-D DFT and this comparison fails against it.
1141    #[test]
1142    fn dft_matches_the_real_part_of_a_direct_2d_fourier_transform() {
1143        let rows = 6usize;
1144        let cols = 4usize;
1145        // A deterministic, non-symmetric signal: a symmetric one would hide the
1146        // missing sine term because its sine components vanish.
1147        let values: Vec<f32> = (0..rows * cols)
1148            .map(|i| ((i * 7) % 13) as f32 - 6.0 + 0.25 * i as f32)
1149            .collect();
1150        let input = Tensor::from_vec(values.clone(), &[rows, cols]).expect("input must build");
1151
1152        let layer = fourier_layer("dft");
1153        let output = layer.forward(input).expect("Fourier transform must succeed");
1154        let got = output.data().expect("output must be readable");
1155        let want = reference_dft_real(&values, rows, cols);
1156
1157        assert_eq!(got.len(), want.len());
1158        for (idx, (g, w)) in got.iter().zip(want.iter()).enumerate() {
1159            assert!(
1160                (g - w).abs() < 1e-3,
1161                "element {idx}: FNet produced {g}, the true 2-D DFT real part is {w}"
1162            );
1163        }
1164    }
1165
1166    /// Parseval / DC sanity: the `[0, 0]` output bin of an orthonormal 2-D DFT
1167    /// is the signal's sum divided by `sqrt(rows*cols)`, for any signal.
1168    #[test]
1169    fn dft_dc_bin_equals_the_normalised_signal_sum() {
1170        let rows = 4usize;
1171        let cols = 8usize;
1172        let values: Vec<f32> = (0..rows * cols).map(|i| (i as f32) * 0.3 - 2.0).collect();
1173        let input = Tensor::from_vec(values.clone(), &[rows, cols]).expect("input must build");
1174
1175        let layer = fourier_layer("dft");
1176        let output = layer.forward(input).expect("Fourier transform must succeed");
1177        let got = output.data().expect("output must be readable");
1178
1179        let expected_dc =
1180            values.iter().sum::<f32>() / ((rows as f32).sqrt() * (cols as f32).sqrt());
1181        assert!(
1182            (got[0] - expected_dc).abs() < 1e-3,
1183            "DC bin {} must equal the normalised sum {expected_dc}",
1184            got[0]
1185        );
1186    }
1187
1188    #[test]
1189    fn dft_preserves_the_input_shape_for_batched_input() {
1190        let layer = fourier_layer("dft");
1191        let input = Tensor::from_vec((0..2 * 5 * 3).map(|i| i as f32).collect(), &[2, 5, 3])
1192            .expect("input must build");
1193        let output = layer.forward(input).expect("Fourier transform must succeed");
1194        assert_eq!(output.shape(), vec![2, 5, 3]);
1195    }
1196
1197    #[test]
1198    fn real_dft_agrees_with_the_full_dft_for_real_input() {
1199        let values: Vec<f32> = (0..4 * 4).map(|i| ((i * 5) % 7) as f32).collect();
1200        let full = fourier_layer("dft")
1201            .forward(Tensor::from_vec(values.clone(), &[4, 4]).expect("input must build"))
1202            .expect("dft must succeed")
1203            .data()
1204            .expect("readable");
1205        let real = fourier_layer("real_dft")
1206            .forward(Tensor::from_vec(values, &[4, 4]).expect("input must build"))
1207            .expect("real_dft must succeed")
1208            .data()
1209            .expect("readable");
1210        for (a, b) in full.iter().zip(real.iter()) {
1211            assert!(
1212                (a - b).abs() < 1e-5,
1213                "real_dft diverged from dft: {a} vs {b}"
1214            );
1215        }
1216    }
1217
1218    // ── Config tests ─────────────────────────────────────────────────────────
1219
1220    #[test]
1221    fn test_config_validate_ok() {
1222        tiny_config().validate().expect("tiny_config should be valid");
1223    }
1224
1225    #[test]
1226    fn test_config_invalid_fourier_type_fails() {
1227        let mut cfg = tiny_config();
1228        cfg.fourier_transform_type = "unknown_type".to_string();
1229        assert!(
1230            cfg.validate().is_err(),
1231            "unknown fourier type must fail validation"
1232        );
1233    }
1234
1235    #[test]
1236    fn test_config_fft_no_attention_heads_field() {
1237        // FNet has no num_attention_heads — validates without attention constraints
1238        tiny_config().validate().expect("fnet config has no attention head constraint");
1239    }
1240
1241    // ── FourierTransform tests ────────────────────────────────────────────────
1242
1243    #[test]
1244    fn test_fourier_transform_dft_output_shape_preserved() {
1245        let cfg = tiny_config();
1246        let ft = FourierTransform::new(&cfg).expect("fourier transform creation should succeed");
1247        // DFT 1D creates an n×n matrix for each dimension.
1248        // To make matmul work both ways (seq and hidden must be equal for simplicity),
1249        // use seq_len == hidden_size.
1250        let seq_len = cfg.hidden_size;
1251        let hidden_size = cfg.hidden_size;
1252        let data = vec![0.5_f32; seq_len * hidden_size];
1253        let input = Tensor::from_vec(data, &[1, seq_len, hidden_size])
1254            .expect("tensor creation should succeed");
1255        match ft.forward(input) {
1256            Ok(output) => {
1257                let shape = output.shape();
1258                assert_eq!(shape[0], 1, "batch dim must be preserved");
1259                // The DFT along seq dim changes effective shape but output batch stays 1
1260                assert!(shape[0] >= 1, "batch must be at least 1");
1261            },
1262            Err(_) => { /* Known shape limitation in test configs */ },
1263        }
1264    }
1265
1266    #[test]
1267    fn test_fourier_transform_dct_output_shape_preserved() {
1268        let mut cfg = tiny_config();
1269        cfg.fourier_transform_type = "dct".to_string();
1270        let ft = FourierTransform::new(&cfg).expect("fourier transform creation should succeed");
1271        // DCT: seq_len must equal hidden_size for the matmul to work correctly in the impl
1272        let seq_len = cfg.hidden_size;
1273        let data = vec![0.2_f32; seq_len * cfg.hidden_size];
1274        let input = Tensor::from_vec(data, &[1, seq_len, cfg.hidden_size])
1275            .expect("tensor creation should succeed");
1276        match ft.forward(input) {
1277            Ok(output) => {
1278                let shape = output.shape();
1279                assert_eq!(shape[0], 1, "batch preserved");
1280            },
1281            Err(_) => { /* Known shape limitation in test configs */ },
1282        }
1283    }
1284
1285    #[test]
1286    fn test_fourier_has_no_attention_weights() {
1287        // FNet's fundamental property: no learnable attention parameters
1288        let cfg = tiny_config();
1289        let ft = FourierTransform::new(&cfg).expect("creation should succeed");
1290        assert_eq!(
1291            ft.parameter_count(),
1292            0,
1293            "Fourier transform without bias has 0 parameters (no attention weights)"
1294        );
1295    }
1296
1297    // ── FNetLayer tests ────────────────────────────────────────────────────────
1298
1299    #[test]
1300    fn test_fnet_layer_output_shape_preserved() {
1301        let cfg = tiny_config();
1302        let layer = FNetLayer::new(&cfg).expect("fnet layer creation should succeed");
1303        // DFT requires seq_len == hidden_size due to matrix dimension constraints
1304        let seq_len = cfg.hidden_size;
1305        let data = vec![0.1_f32; seq_len * cfg.hidden_size];
1306        let input = Tensor::from_vec(data, &[1, seq_len, cfg.hidden_size])
1307            .expect("tensor creation should succeed");
1308        match layer.forward(input) {
1309            Ok(output) => {
1310                let shape = output.shape();
1311                assert_eq!(shape[0], 1, "batch preserved");
1312                assert_eq!(shape[1], seq_len, "seq_len preserved");
1313                assert_eq!(shape[2], cfg.hidden_size, "hidden_size preserved");
1314            },
1315            Err(_) => { /* Known shape limitation in test configs */ },
1316        }
1317    }
1318
1319    #[test]
1320    fn test_fnet_layer_fourier_plus_ffn() {
1321        // An FNetLayer contains both a FourierTransform and a FeedForward
1322        let cfg = tiny_config();
1323        let layer = FNetLayer::new(&cfg).expect("creation should succeed");
1324        // Parameter count includes FFN (dense1 + dense2) but not FourierTransform
1325        assert!(layer.parameter_count() > 0, "fnet layer has FFN parameters");
1326    }
1327
1328    // ── FNetModel tests ────────────────────────────────────────────────────────
1329
1330    #[test]
1331    fn test_model_creation() {
1332        let cfg = tiny_config();
1333        FNetModel::new(cfg).expect("model creation should succeed");
1334    }
1335
1336    #[test]
1337    fn test_model_forward_output_shape() {
1338        let cfg = tiny_config();
1339        let model = FNetModel::new(cfg.clone()).expect("model creation should succeed");
1340        // DFT requires seq_len == hidden_size due to matrix dimension constraints
1341        let seq_len = cfg.hidden_size;
1342        let input = make_input(seq_len);
1343        match model.forward(input) {
1344            Ok(output) => {
1345                let shape = output.shape();
1346                // Output: [batch, seq_len, hidden_size] or [seq_len, hidden_size]
1347                assert_eq!(
1348                    shape[shape.len() - 1],
1349                    cfg.hidden_size,
1350                    "last dim must be hidden_size"
1351                );
1352            },
1353            Err(_) => { /* Known shape limitation in test configs */ },
1354        }
1355    }
1356
1357    #[test]
1358    fn test_model_linear_complexity_no_attention() {
1359        // FNet's primary property: O(n log n) vs O(n²) for attention.
1360        // Verify no attention layers exist (parameter structure test)
1361        let cfg = tiny_config();
1362        let model = FNetModel::new(cfg).expect("model creation should succeed");
1363        // Parameter count should not contain query/key projections from attention
1364        let total = model.num_parameters();
1365        assert!(total > 0, "model must have non-zero parameters");
1366    }
1367
1368    // ── FNetForMaskedLM tests ─────────────────────────────────────────────────
1369
1370    #[test]
1371    fn test_masked_lm_creation() {
1372        let cfg = tiny_config();
1373        FNetForMaskedLM::new(cfg).expect("masked lm creation should succeed");
1374    }
1375
1376    #[test]
1377    fn test_masked_lm_output_vocab_size() {
1378        let cfg = tiny_config();
1379        let vocab_size = cfg.vocab_size;
1380        let model = FNetForMaskedLM::new(cfg.clone()).expect("creation should succeed");
1381        // DFT requires seq_len == hidden_size
1382        let input = make_input(cfg.hidden_size);
1383        match model.forward(input) {
1384            Ok(output) => {
1385                let shape = output.shape();
1386                assert_eq!(
1387                    shape[shape.len() - 1],
1388                    vocab_size,
1389                    "masked lm output last dim must equal vocab_size"
1390                );
1391            },
1392            Err(_) => { /* Known shape limitation in test configs */ },
1393        }
1394    }
1395
1396    // ── FNetForSequenceClassification tests ───────────────────────────────────
1397
1398    #[test]
1399    fn test_sequence_classification_creation() {
1400        let cfg = tiny_config();
1401        FNetForSequenceClassification::new(cfg, 3)
1402            .expect("sequence classification creation should succeed");
1403    }
1404
1405    #[test]
1406    fn test_sequence_classification_output_num_labels() {
1407        let cfg = tiny_config();
1408        let num_labels = 5;
1409        let model = FNetForSequenceClassification::new(cfg.clone(), num_labels)
1410            .expect("creation should succeed");
1411        // DFT requires seq_len == hidden_size
1412        let input = make_input(cfg.hidden_size);
1413        match model.forward(input) {
1414            Ok(output) => {
1415                let shape = output.shape();
1416                assert_eq!(
1417                    shape[shape.len() - 1],
1418                    num_labels,
1419                    "classifier output last dim must equal num_labels"
1420                );
1421            },
1422            Err(_) => { /* Known shape limitation in test configs */ },
1423        }
1424    }
1425
1426    // ── FNetEmbeddings tests ───────────────────────────────────────────────────
1427
1428    #[test]
1429    fn test_embeddings_creation() {
1430        let cfg = tiny_config();
1431        FNetEmbeddings::new(&cfg).expect("embeddings creation should succeed");
1432    }
1433
1434    #[test]
1435    fn test_embeddings_forward_shape() {
1436        let cfg = tiny_config();
1437        let emb = FNetEmbeddings::new(&cfg).expect("creation should succeed");
1438        let seq_len = 4usize;
1439        let ids: Vec<u32> = (0..seq_len as u32).collect();
1440        let output = emb.forward((ids, None, None)).expect("embeddings forward should succeed");
1441        let shape = output.shape();
1442        assert_eq!(
1443            shape[shape.len() - 1],
1444            cfg.hidden_size,
1445            "embedding dim must match hidden_size"
1446        );
1447    }
1448
1449    // ── Real checkpoint loading (regression for the silent `Ok(())`) ────────
1450
1451    use crate::weight_loading::test_support::{build_safetensors, F32Tensor};
1452
1453    fn loading_config() -> FNetConfig {
1454        FNetConfig {
1455            vocab_size: 16,
1456            hidden_size: 8,
1457            num_hidden_layers: 2,
1458            intermediate_size: 16,
1459            max_position_embeddings: 8,
1460            type_vocab_size: 2,
1461            ..tiny_config()
1462        }
1463    }
1464
1465    /// Every tensor an FNet checkpoint of this shape carries.
1466    ///
1467    /// Note the absence of any `attention.*` projection: FNet's mixing layer is
1468    /// a parameter-free Fourier transform, so those tensors simply do not exist.
1469    fn fnet_tensors(config: &FNetConfig, prefix: &str) -> Vec<F32Tensor> {
1470        let hidden = config.hidden_size;
1471        let intermediate = config.intermediate_size;
1472        let mut seed = 0.0f32;
1473        let mut next = || {
1474            seed += 1.0;
1475            seed
1476        };
1477
1478        let mut tensors = vec![
1479            F32Tensor::ramp(
1480                &format!("{prefix}embeddings.word_embeddings.weight"),
1481                &[config.vocab_size, hidden],
1482                next(),
1483            ),
1484            F32Tensor::ramp(
1485                &format!("{prefix}embeddings.position_embeddings.weight"),
1486                &[config.max_position_embeddings, hidden],
1487                next(),
1488            ),
1489            F32Tensor::ramp(
1490                &format!("{prefix}embeddings.token_type_embeddings.weight"),
1491                &[config.type_vocab_size, hidden],
1492                next(),
1493            ),
1494            F32Tensor::ramp(
1495                &format!("{prefix}embeddings.LayerNorm.weight"),
1496                &[hidden],
1497                next(),
1498            ),
1499            F32Tensor::ramp(
1500                &format!("{prefix}embeddings.LayerNorm.bias"),
1501                &[hidden],
1502                next(),
1503            ),
1504        ];
1505
1506        for layer in 0..config.num_hidden_layers {
1507            let base = format!("{prefix}encoder.layer.{layer}");
1508            tensors.push(F32Tensor::ramp(
1509                &format!("{base}.fourier.output.LayerNorm.weight"),
1510                &[hidden],
1511                next(),
1512            ));
1513            tensors.push(F32Tensor::ramp(
1514                &format!("{base}.fourier.output.LayerNorm.bias"),
1515                &[hidden],
1516                next(),
1517            ));
1518            tensors.push(F32Tensor::ramp(
1519                &format!("{base}.intermediate.dense.weight"),
1520                &[intermediate, hidden],
1521                next(),
1522            ));
1523            tensors.push(F32Tensor::ramp(
1524                &format!("{base}.intermediate.dense.bias"),
1525                &[intermediate],
1526                next(),
1527            ));
1528            tensors.push(F32Tensor::ramp(
1529                &format!("{base}.output.dense.weight"),
1530                &[hidden, intermediate],
1531                next(),
1532            ));
1533            tensors.push(F32Tensor::ramp(
1534                &format!("{base}.output.dense.bias"),
1535                &[hidden],
1536                next(),
1537            ));
1538            tensors.push(F32Tensor::ramp(
1539                &format!("{base}.output.LayerNorm.weight"),
1540                &[hidden],
1541                next(),
1542            ));
1543            tensors.push(F32Tensor::ramp(
1544                &format!("{base}.output.LayerNorm.bias"),
1545                &[hidden],
1546                next(),
1547            ));
1548        }
1549
1550        tensors
1551    }
1552
1553    /// Regression: `load_pretrained` was `Ok(())`, so the reader was never read
1554    /// and the model kept its random initialisation while reporting success.
1555    #[test]
1556    fn load_pretrained_binds_the_checkpoint_instead_of_returning_ok() {
1557        let config = loading_config();
1558        let tensors = fnet_tensors(&config, "fnet.");
1559        let bytes = build_safetensors(&tensors);
1560
1561        let mut model = FNetModel::new(config).expect("model must build");
1562        let report = model
1563            .load_pretrained_report(&mut bytes.as_slice())
1564            .expect("a matching checkpoint must load");
1565        assert!(
1566            report.is_complete(),
1567            "every parameter must be bound, missing: {:?}",
1568            report.missing
1569        );
1570        assert_eq!(
1571            report.loaded.len(),
1572            tensors.len(),
1573            "every fixture tensor must reach the model"
1574        );
1575    }
1576
1577    #[test]
1578    fn load_pretrained_reports_a_missing_parameter_instead_of_inventing_it() {
1579        let config = loading_config();
1580        let mut tensors = fnet_tensors(&config, "fnet.");
1581        tensors.retain(|t| t.name != "fnet.encoder.layer.1.output.dense.weight");
1582        let bytes = build_safetensors(&tensors);
1583
1584        let mut model = FNetModel::new(config).expect("model must build");
1585        let err = model
1586            .load_pretrained(&mut bytes.as_slice())
1587            .expect_err("an incomplete checkpoint must not load silently");
1588        assert!(
1589            err.to_string().contains("encoder.layer.1.output.dense.weight"),
1590            "the error must name the gap: {err}"
1591        );
1592    }
1593
1594    #[test]
1595    fn load_pretrained_rejects_a_foreign_tensor() {
1596        let config = loading_config();
1597        let mut tensors = fnet_tensors(&config, "fnet.");
1598        // An attention projection has no place in an FNet checkpoint.
1599        tensors.push(F32Tensor::ramp(
1600            "fnet.encoder.layer.0.attention.self.query.weight",
1601            &[8, 8],
1602            42.0,
1603        ));
1604        let bytes = build_safetensors(&tensors);
1605
1606        let mut model = FNetModel::new(config).expect("model must build");
1607        let err = model
1608            .load_pretrained(&mut bytes.as_slice())
1609            .expect_err("an unrecognised weight must fail the load");
1610        assert!(
1611            err.to_string().contains("attention.self.query"),
1612            "unexpected: {err}"
1613        );
1614    }
1615
1616    #[test]
1617    fn load_pretrained_rejects_bytes_that_are_not_a_checkpoint() {
1618        let mut model = FNetModel::new(loading_config()).expect("model must build");
1619        let garbage = vec![0xABu8; 4096];
1620        let err = model
1621            .load_pretrained(&mut garbage.as_slice())
1622            .expect_err("garbage must not be accepted as weights");
1623        assert!(
1624            err.to_string().contains("unrecognised checkpoint container"),
1625            "unexpected: {err}"
1626        );
1627    }
1628
1629    // ── Task heads (regression for the head-dropping delegation) ────────────
1630
1631    /// The tensors a fine-tuned `FNetForSequenceClassification` export adds on
1632    /// top of the encoder.
1633    fn classifier_tensors(config: &FNetConfig, num_labels: usize) -> Vec<F32Tensor> {
1634        vec![
1635            F32Tensor::ramp("classifier.weight", &[num_labels, config.hidden_size], 90.0),
1636            F32Tensor::ramp("classifier.bias", &[num_labels], 95.0),
1637        ]
1638    }
1639
1640    /// The tensors a `FNetForMaskedLM` export adds on top of the encoder.
1641    fn prediction_head_tensors(config: &FNetConfig, aliased_bias: bool) -> Vec<F32Tensor> {
1642        let hidden = config.hidden_size;
1643        let bias_name = if aliased_bias {
1644            "cls.predictions.decoder.bias"
1645        } else {
1646            "cls.predictions.bias"
1647        };
1648        vec![
1649            F32Tensor::ramp(
1650                "cls.predictions.transform.dense.weight",
1651                &[hidden, hidden],
1652                60.0,
1653            ),
1654            F32Tensor::ramp("cls.predictions.transform.dense.bias", &[hidden], 65.0),
1655            F32Tensor::ramp(
1656                "cls.predictions.transform.LayerNorm.weight",
1657                &[hidden],
1658                70.0,
1659            ),
1660            F32Tensor::ramp("cls.predictions.transform.LayerNorm.bias", &[hidden], 75.0),
1661            F32Tensor::ramp(
1662                "cls.predictions.decoder.weight",
1663                &[config.vocab_size, hidden],
1664                80.0,
1665            ),
1666            F32Tensor::ramp(bias_name, &[config.vocab_size], 85.0),
1667        ]
1668    }
1669
1670    /// Regression: the wrapper delegated to `FNetModel::load_pretrained`, whose
1671    /// unused-tensor policy tolerates the `classifier.` namespace. The head was
1672    /// therefore dropped on the floor while the load returned `Ok(())`.
1673    #[test]
1674    fn sequence_classification_load_pretrained_binds_the_classifier_head() {
1675        let config = loading_config();
1676        let num_labels = 3;
1677        let mut tensors = fnet_tensors(&config, "fnet.");
1678        tensors.extend(classifier_tensors(&config, num_labels));
1679        let bytes = build_safetensors(&tensors);
1680
1681        let mut model =
1682            FNetForSequenceClassification::new(config, num_labels).expect("model must build");
1683        let report = model
1684            .load_pretrained_report(&mut bytes.as_slice())
1685            .expect("a matching checkpoint must load");
1686
1687        assert!(
1688            report.is_complete(),
1689            "every parameter must be bound, missing: {:?}",
1690            report.missing
1691        );
1692        assert!(
1693            report.loaded.contains(&"classifier.weight".to_string())
1694                && report.loaded.contains(&"classifier.bias".to_string()),
1695            "the classification head must be among the loaded tensors: {:?}",
1696            report.loaded
1697        );
1698    }
1699
1700    /// A plain pretrained encoder ships without a fine-tuned head. That is
1701    /// accepted, but the gap is reported rather than passed off as a full load.
1702    #[test]
1703    fn sequence_classification_load_pretrained_records_an_absent_head() {
1704        let config = loading_config();
1705        let bytes = build_safetensors(&fnet_tensors(&config, "fnet."));
1706
1707        let mut model = FNetForSequenceClassification::new(config, 3).expect("model must build");
1708        let report = model
1709            .load_pretrained_report(&mut bytes.as_slice())
1710            .expect("a head-less encoder checkpoint must still load");
1711        assert!(
1712            !report.is_complete(),
1713            "a checkpoint without a head must not be reported as complete"
1714        );
1715        assert!(
1716            report.missing.contains(&"classifier.weight".to_string()),
1717            "the absent head must be named: {:?}",
1718            report.missing
1719        );
1720    }
1721
1722    #[test]
1723    fn sequence_classification_load_pretrained_rejects_a_head_of_the_wrong_width() {
1724        let config = loading_config();
1725        let mut tensors = fnet_tensors(&config, "fnet.");
1726        tensors.extend(classifier_tensors(&config, 7));
1727        let bytes = build_safetensors(&tensors);
1728
1729        let mut model = FNetForSequenceClassification::new(config, 3).expect("model must build");
1730        let err = model
1731            .load_pretrained(&mut bytes.as_slice())
1732            .expect_err("a 7-label head must not be reshaped into a 3-label model");
1733        assert!(
1734            err.to_string().contains("classifier.weight"),
1735            "unexpected: {err}"
1736        );
1737    }
1738
1739    /// Regression: the masked-LM wrapper delegated to the encoder loader, whose
1740    /// policy tolerates the whole `cls.` namespace, so the prediction head was
1741    /// silently discarded.
1742    #[test]
1743    fn masked_lm_load_pretrained_binds_the_prediction_head() {
1744        let config = loading_config();
1745        let mut tensors = fnet_tensors(&config, "fnet.");
1746        tensors.extend(prediction_head_tensors(&config, false));
1747        let bytes = build_safetensors(&tensors);
1748
1749        let mut model = FNetForMaskedLM::new(config).expect("model must build");
1750        let report = model
1751            .load_pretrained_report(&mut bytes.as_slice())
1752            .expect("a matching checkpoint must load");
1753
1754        assert!(
1755            report.is_complete(),
1756            "every parameter must be bound, missing: {:?}",
1757            report.missing
1758        );
1759        for name in [
1760            "cls.predictions.transform.dense.weight",
1761            "cls.predictions.transform.LayerNorm.weight",
1762            "cls.predictions.decoder.weight",
1763            "cls.predictions.bias",
1764        ] {
1765            assert!(
1766                report.loaded.contains(&name.to_string()),
1767                "{name} must be among the loaded tensors: {:?}",
1768                report.loaded
1769            );
1770        }
1771    }
1772
1773    /// HuggingFace aliases `cls.predictions.decoder.bias` onto
1774    /// `cls.predictions.bias`; an export may carry either spelling.
1775    #[test]
1776    fn masked_lm_load_pretrained_accepts_the_aliased_decoder_bias() {
1777        let config = loading_config();
1778        let mut tensors = fnet_tensors(&config, "fnet.");
1779        tensors.extend(prediction_head_tensors(&config, true));
1780        let bytes = build_safetensors(&tensors);
1781
1782        let mut model = FNetForMaskedLM::new(config).expect("model must build");
1783        let report = model
1784            .load_pretrained_report(&mut bytes.as_slice())
1785            .expect("the aliased bias spelling must load");
1786        assert!(
1787            report.loaded.contains(&"cls.predictions.decoder.bias".to_string()),
1788            "the aliased bias must be consumed: {:?}",
1789            report.loaded
1790        );
1791    }
1792
1793    #[test]
1794    fn masked_lm_load_pretrained_records_an_absent_head() {
1795        let config = loading_config();
1796        let bytes = build_safetensors(&fnet_tensors(&config, "fnet."));
1797
1798        let mut model = FNetForMaskedLM::new(config).expect("model must build");
1799        let report = model
1800            .load_pretrained_report(&mut bytes.as_slice())
1801            .expect("a head-less encoder checkpoint must still load");
1802        assert!(
1803            report.missing.contains(&"cls.predictions.decoder.weight".to_string()),
1804            "the absent prediction head must be named: {:?}",
1805            report.missing
1806        );
1807    }
1808
1809    #[test]
1810    fn masked_lm_load_pretrained_rejects_a_head_for_a_different_vocabulary() {
1811        let config = loading_config();
1812        let wider = FNetConfig {
1813            vocab_size: config.vocab_size * 2,
1814            ..config.clone()
1815        };
1816        let mut tensors = fnet_tensors(&config, "fnet.");
1817        tensors.extend(prediction_head_tensors(&wider, false));
1818        let bytes = build_safetensors(&tensors);
1819
1820        let mut model = FNetForMaskedLM::new(config).expect("model must build");
1821        let err = model
1822            .load_pretrained(&mut bytes.as_slice())
1823            .expect_err("a head for a bigger vocabulary must not be reshaped into place");
1824        assert!(
1825            err.to_string().contains("cls.predictions.decoder.weight"),
1826            "unexpected: {err}"
1827        );
1828    }
1829
1830    // ── Contextual strictness: wrapper path vs bare-encoder path ────────────
1831
1832    /// A task wrapper must refuse a checkpoint entry it does not recognise
1833    /// inside a namespace it binds itself.
1834    ///
1835    /// [`FNetModel::ALLOWED_UNUSED_PREFIXES`] tolerates `cls.` and
1836    /// `classifier.` so that a *bare encoder* can be lifted out of a fine-tuned
1837    /// checkpoint. The task wrappers used to inherit that tolerance even though
1838    /// they bind those namespaces, so a misspelling such as
1839    /// `cls.predictions.transform.dens.weight` was reported as merely
1840    /// `ignored`: the load returned `Ok` and the dense layer the typo was meant
1841    /// to fill kept its random initialisation. See
1842    /// [`crate::weight_loading::binding::BoundNamespaces`].
1843    #[test]
1844    fn a_wrapper_rejects_an_unknown_tensor_inside_a_namespace_it_binds() {
1845        // Masked LM: a misspelling one level below the namespace it binds.
1846        let config = loading_config();
1847        let hidden = config.hidden_size;
1848        let mut tensors = fnet_tensors(&config, "fnet.");
1849        tensors.extend(prediction_head_tensors(&config, false));
1850        tensors.push(F32Tensor::ramp(
1851            "cls.predictions.transform.dens.weight",
1852            &[hidden, hidden],
1853            96.0,
1854        ));
1855        let bytes = build_safetensors(&tensors);
1856        let mut model = FNetForMaskedLM::new(config).expect("model must build");
1857        let err = model
1858            .load_pretrained(&mut bytes.as_slice())
1859            .expect_err("a misspelt head tensor must not be tolerated by the head's own binder");
1860        let message = err.to_string();
1861        assert!(
1862            message.contains("cls.predictions.transform.dens.weight"),
1863            "the offending name must be reported: {message}"
1864        );
1865        // The refusal must come from the wrapper's own namespace check, not
1866        // from a shape or missing-parameter error that happens to mention the
1867        // name: only `BoundNamespaces::verify` phrases it this way.
1868        assert!(
1869            message.contains("does not recognise inside the head namespace"),
1870            "the refusal must be the bound-namespace check: {message}"
1871        );
1872
1873        // Sequence classification: a misspelling under `classifier.`.
1874        let config = loading_config();
1875        let hidden = config.hidden_size;
1876        let mut tensors = fnet_tensors(&config, "fnet.");
1877        tensors.extend(classifier_tensors(&config, 3));
1878        tensors.push(F32Tensor::ramp("classifier.weigth", &[3, hidden], 97.0));
1879        let bytes = build_safetensors(&tensors);
1880        let mut model = FNetForSequenceClassification::new(config, 3).expect("model must build");
1881        let err = model
1882            .load_pretrained(&mut bytes.as_slice())
1883            .expect_err("a misspelt classifier tensor must be refused");
1884        assert!(
1885            err.to_string().contains("classifier.weigth"),
1886            "unexpected: {err}"
1887        );
1888    }
1889
1890    /// The strictness above must not turn into "every checkpoint entry must be
1891    /// consumed": a pretraining checkpoint legitimately carries heads a
1892    /// particular model does not bind, and the bare encoder binds none of them.
1893    #[test]
1894    fn namespaces_a_model_does_not_bind_stay_tolerated() {
1895        let config = loading_config();
1896        let hidden = config.hidden_size;
1897        let mut tensors = fnet_tensors(&config, "fnet.");
1898        tensors.extend(prediction_head_tensors(&config, false));
1899        // A next-sentence head under `cls.`, which the masked-LM wrapper does
1900        // not bind: it claims `cls.predictions.`, not `cls.` as a whole.
1901        tensors.push(F32Tensor::ramp(
1902            "cls.seq_relationship.weight",
1903            &[2, hidden],
1904            98.0,
1905        ));
1906        tensors.push(F32Tensor::ramp("cls.seq_relationship.bias", &[2], 99.0));
1907        let bytes = build_safetensors(&tensors);
1908
1909        let mut model = FNetForMaskedLM::new(config).expect("model must build");
1910        let report = model
1911            .load_pretrained_report(&mut bytes.as_slice())
1912            .expect("a next-sentence head this model does not bind must stay tolerated");
1913        assert!(
1914            report.ignored.iter().any(|name| name == "cls.seq_relationship.weight"),
1915            "the unbound head must be reported as ignored: {:?}",
1916            report.ignored
1917        );
1918
1919        // The same checkpoint through the bare encoder: `cls.` as a whole is not
1920        // bound there, so the entire namespace stays tolerated.
1921        let mut encoder = FNetModel::new(loading_config()).expect("model must build");
1922        let encoder_report = encoder
1923            .load_pretrained_report(&mut bytes.as_slice())
1924            .expect("the bare encoder must keep tolerating a head namespace it never binds");
1925        for name in [
1926            "cls.predictions.transform.dense.weight",
1927            "cls.seq_relationship.weight",
1928        ] {
1929            assert!(
1930                encoder_report.ignored.iter().any(|ignored| ignored == name),
1931                "{name} must stay tolerated on the bare-encoder path: {:?}",
1932                encoder_report.ignored
1933            );
1934        }
1935    }
1936}