Skip to main content

numcodecs_fourier_network/
lib.rs

1//! [![CI Status]][workflow] [![MSRV]][repo] [![Latest Version]][crates.io] [![Rust Doc Crate]][docs.rs] [![Rust Doc Main]][docs]
2//!
3//! [CI Status]: https://img.shields.io/github/actions/workflow/status/juntyr/numcodecs-rs/ci.yml?branch=main
4//! [workflow]: https://github.com/juntyr/numcodecs-rs/actions/workflows/ci.yml?query=branch%3Amain
5//!
6//! [MSRV]: https://img.shields.io/badge/MSRV-1.88.0-blue
7//! [repo]: https://github.com/juntyr/numcodecs-rs
8//!
9//! [Latest Version]: https://img.shields.io/crates/v/numcodecs-fourier-network
10//! [crates.io]: https://crates.io/crates/numcodecs-fourier-network
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-fourier-network
13//! [docs.rs]: https://docs.rs/numcodecs-fourier-network/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_fourier_network
17//!
18//! Fourier feature neural network codec implementation for the [`numcodecs`] API.
19
20#![allow(clippy::multiple_crate_versions)]
21
22use std::{borrow::Cow, num::NonZeroUsize, ops::AddAssign};
23
24use burn::{
25    backend::{Autodiff, NdArray, ndarray::NdArrayDevice},
26    module::{Module, Param},
27    nn::loss::{MseLoss, Reduction},
28    optim::{AdamConfig, GradientsParams, Optimizer},
29    prelude::Backend,
30    record::{
31        BinBytesRecorder, DoublePrecisionSettings, FullPrecisionSettings, PrecisionSettings,
32        Record, Recorder, RecorderError,
33    },
34    tensor::{
35        Distribution, Element as BurnElement, Float, Tensor, TensorData, backend::AutodiffBackend,
36    },
37};
38use itertools::Itertools;
39use ndarray::{Array, ArrayBase, ArrayView, ArrayViewMut, Data, Dimension, Ix1, Order, Zip};
40use num_traits::{ConstOne, ConstZero, Float as FloatTrait, FromPrimitive};
41use numcodecs::{
42    AnyArray, AnyArrayAssignError, AnyArrayDType, AnyArrayView, AnyArrayViewMut, AnyCowArray,
43    Codec, StaticCodec, StaticCodecConfig, StaticCodecVersion,
44};
45use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
46use serde::{Deserialize, Deserializer, Serialize, Serializer};
47use thiserror::Error;
48
49// FIXME: bytemuck 1.24 fails to compile on 1.88
50use ::bytemuck as _;
51
52// FIXME: burn-core depends on uuid which from 1.27 onwards requires MSRV 1.89
53use ::uuid as _;
54
55// FIXME: burn-common -> cubecl-common brings in wasm-bindgen
56//        wasm-bindgen v0.2.115 has an unresolved import in wasm32-wasi
57use ::wasm_bindgen as _;
58
59#[cfg(test)]
60use ::serde_json as _;
61
62mod modules;
63
64use modules::{Model, ModelConfig, ModelExtra, ModelRecord};
65
66type FourierNetworkCodecVersion = StaticCodecVersion<0, 1, 0>;
67
68#[derive(Clone, Serialize, Deserialize, JsonSchema)]
69#[serde(deny_unknown_fields)]
70/// Fourier network codec which trains and overfits a fourier feature neural
71/// network on encoding and predicts during decoding.
72///
73/// The approach is based on the papers by Tancik et al. 2020
74/// (<https://dl.acm.org/doi/abs/10.5555/3495724.3496356>)
75/// and by Huang and Hoefler 2020 (<https://arxiv.org/abs/2210.12538>).
76pub struct FourierNetworkCodec {
77    /// The number of Fourier features that the data coordinates are projected to
78    pub fourier_features: NonZeroUsize,
79    /// The standard deviation of the Fourier features
80    pub fourier_scale: Positive<f64>,
81    /// The number of blocks in the network
82    pub num_blocks: NonZeroUsize,
83    /// The learning rate for the `Adam` optimizer
84    pub learning_rate: Positive<f64>,
85    /// The number of epochs for which the network is trained
86    pub num_epochs: usize,
87    /// The optional mini-batch size used during training
88    ///
89    /// Setting the mini-batch size to `None` disables the use of batching,
90    /// i.e. the network is trained using one large batch that includes the
91    /// full data.
92    #[serde(deserialize_with = "deserialize_required_option")]
93    #[schemars(required, extend("type" = ["integer", "null"]))]
94    pub mini_batch_size: Option<NonZeroUsize>,
95    /// The seed for the random number generator used during encoding
96    pub seed: u64,
97    /// The codec's encoding format version. Do not provide this parameter explicitly.
98    #[serde(default, rename = "_version")]
99    pub version: FourierNetworkCodecVersion,
100}
101
102// using this wrapper function makes an Option<T> required
103fn deserialize_required_option<'de, T: serde::Deserialize<'de>, D: serde::Deserializer<'de>>(
104    deserializer: D,
105) -> Result<Option<T>, D::Error> {
106    Option::<T>::deserialize(deserializer)
107}
108
109impl Codec for FourierNetworkCodec {
110    type Error = FourierNetworkCodecError;
111
112    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
113        match data {
114            AnyCowArray::F32(data) => Ok(AnyArray::U8(
115                encode::<f32, _, _, Autodiff<NdArray<f32>>>(
116                    &NdArrayDevice::Cpu,
117                    data,
118                    self.fourier_features,
119                    self.fourier_scale,
120                    self.num_blocks,
121                    self.learning_rate,
122                    self.num_epochs,
123                    self.mini_batch_size,
124                    self.seed,
125                )?
126                .into_dyn(),
127            )),
128            AnyCowArray::F64(data) => Ok(AnyArray::U8(
129                encode::<f64, _, _, Autodiff<NdArray<f64>>>(
130                    &NdArrayDevice::Cpu,
131                    data,
132                    self.fourier_features,
133                    self.fourier_scale,
134                    self.num_blocks,
135                    self.learning_rate,
136                    self.num_epochs,
137                    self.mini_batch_size,
138                    self.seed,
139                )?
140                .into_dyn(),
141            )),
142            encoded => Err(FourierNetworkCodecError::UnsupportedDtype(encoded.dtype())),
143        }
144    }
145
146    fn decode(&self, _encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
147        Err(FourierNetworkCodecError::MissingDecodingOutput)
148    }
149
150    fn decode_into(
151        &self,
152        encoded: AnyArrayView,
153        decoded: AnyArrayViewMut,
154    ) -> Result<(), Self::Error> {
155        let AnyArrayView::U8(encoded) = encoded else {
156            return Err(FourierNetworkCodecError::EncodedDataNotBytes {
157                dtype: encoded.dtype(),
158            });
159        };
160
161        let Ok(encoded): Result<ArrayBase<_, Ix1>, _> = encoded.view().into_dimensionality() else {
162            return Err(FourierNetworkCodecError::EncodedDataNotOneDimensional {
163                shape: encoded.shape().to_vec(),
164            });
165        };
166
167        match decoded {
168            AnyArrayViewMut::F32(decoded) => decode_into::<f32, _, _, NdArray<f32>>(
169                &NdArrayDevice::Cpu,
170                encoded,
171                decoded,
172                self.fourier_features,
173                self.num_blocks,
174            ),
175            AnyArrayViewMut::F64(decoded) => decode_into::<f64, _, _, NdArray<f64>>(
176                &NdArrayDevice::Cpu,
177                encoded,
178                decoded,
179                self.fourier_features,
180                self.num_blocks,
181            ),
182            decoded => Err(FourierNetworkCodecError::UnsupportedDtype(decoded.dtype())),
183        }
184    }
185}
186
187impl StaticCodec for FourierNetworkCodec {
188    const CODEC_ID: &'static str = "fourier-network.rs";
189
190    type Config<'de> = Self;
191
192    fn from_config(config: Self::Config<'_>) -> Self {
193        config
194    }
195
196    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
197        StaticCodecConfig::from(self)
198    }
199}
200
201#[expect(clippy::derive_partial_eq_without_eq)] // floats are not Eq
202#[derive(Copy, Clone, PartialEq, PartialOrd, Hash)]
203/// Positive floating point number
204pub struct Positive<T: FloatTrait>(T);
205
206impl Serialize for Positive<f64> {
207    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
208        serializer.serialize_f64(self.0)
209    }
210}
211
212impl<'de> Deserialize<'de> for Positive<f64> {
213    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
214        let x = f64::deserialize(deserializer)?;
215
216        if x > 0.0 {
217            Ok(Self(x))
218        } else {
219            Err(serde::de::Error::invalid_value(
220                serde::de::Unexpected::Float(x),
221                &"a positive value",
222            ))
223        }
224    }
225}
226
227impl JsonSchema for Positive<f64> {
228    fn inline_schema() -> bool {
229        true
230    }
231
232    fn schema_name() -> Cow<'static, str> {
233        Cow::Borrowed("PositiveF64")
234    }
235
236    fn schema_id() -> Cow<'static, str> {
237        Cow::Borrowed(concat!(module_path!(), "::", "Positive<f64>"))
238    }
239
240    fn json_schema(_gen: &mut SchemaGenerator) -> Schema {
241        json_schema!({
242            "type": "number",
243            "exclusiveMinimum": 0.0
244        })
245    }
246}
247
248#[derive(Debug, Error)]
249/// Errors that may occur when applying the [`FourierNetworkCodec`].
250pub enum FourierNetworkCodecError {
251    /// [`FourierNetworkCodec`] does not support the dtype
252    #[error("FourierNetwork does not support the dtype {0}")]
253    UnsupportedDtype(AnyArrayDType),
254    /// [`FourierNetworkCodec`] does not support non-finite (infinite or NaN) floating
255    /// point data
256    #[error("FourierNetwork does not support non-finite (infinite or NaN) floating point data")]
257    NonFiniteData,
258    /// [`FourierNetworkCodec`] failed during a neural network computation
259    #[error("FourierNetwork failed during a neural network computation")]
260    NeuralNetworkError {
261        /// The source of the error
262        #[from]
263        source: NeuralNetworkError,
264    },
265    /// [`FourierNetworkCodec`] must be provided the output array during decoding
266    #[error("FourierNetwork must be provided the output array during decoding")]
267    MissingDecodingOutput,
268    /// [`FourierNetworkCodec`] can only decode one-dimensional byte arrays but
269    /// received an array of a different dtype
270    #[error(
271        "FourierNetwork can only decode one-dimensional byte arrays but received an array of dtype {dtype}"
272    )]
273    EncodedDataNotBytes {
274        /// The unexpected dtype of the encoded array
275        dtype: AnyArrayDType,
276    },
277    /// [`FourierNetworkCodec`] can only decode one-dimensional byte arrays but
278    /// received an array of a different shape
279    #[error(
280        "FourierNetwork can only decode one-dimensional byte arrays but received a byte array of shape {shape:?}"
281    )]
282    EncodedDataNotOneDimensional {
283        /// The unexpected shape of the encoded array
284        shape: Vec<usize>,
285    },
286    /// [`FourierNetworkCodec`] cannot decode into the provided array
287    #[error("FourierNetwork cannot decode into the provided array")]
288    MismatchedDecodeIntoArray {
289        /// The source of the error
290        #[from]
291        source: AnyArrayAssignError,
292    },
293}
294
295#[derive(Debug, Error)]
296#[error(transparent)]
297/// Opaque error for when an error occurs in the neural network
298pub struct NeuralNetworkError(RecorderError);
299
300/// Floating point types.
301pub trait FloatExt:
302    AddAssign + BurnElement + ConstOne + ConstZero + FloatTrait + FromPrimitive
303{
304    /// The precision of this floating point type
305    type Precision: PrecisionSettings;
306
307    /// Convert a usize to a floating point number
308    fn from_usize(x: usize) -> Self;
309}
310
311impl FloatExt for f32 {
312    type Precision = FullPrecisionSettings;
313
314    #[expect(clippy::cast_precision_loss)]
315    fn from_usize(x: usize) -> Self {
316        x as Self
317    }
318}
319
320impl FloatExt for f64 {
321    type Precision = DoublePrecisionSettings;
322
323    #[expect(clippy::cast_precision_loss)]
324    fn from_usize(x: usize) -> Self {
325        x as Self
326    }
327}
328
329#[expect(clippy::similar_names)] // train_xs and train_ys
330#[expect(clippy::missing_panics_doc)] // only panics on implementation bugs
331#[expect(clippy::too_many_arguments)] // FIXME
332/// Encodes the `data` by training a fourier feature neural network.
333///
334/// The `fourier_features` are randomly sampled from a normal distribution with
335/// zero mean and `fourier_scale` standard deviation.
336///
337/// The neural network consists of `num_blocks` blocks.
338///
339/// The network is trained for `num_epochs` using the `learning_rate`
340/// and mini-batches of `mini_batch_size` if mini-batching is enabled.
341///
342/// All random numbers are generated using the provided `seed`.
343///
344/// # Errors
345///
346/// Errors with
347/// - [`FourierNetworkCodecError::NonFiniteData`] if any data element is
348///   non-finite (infinite or NaN)
349/// - [`FourierNetworkCodecError::NeuralNetworkError`] if an error occurs during
350///   the neural network computation
351pub fn encode<T: FloatExt, S: Data<Elem = T>, D: Dimension, B: AutodiffBackend<FloatElem = T>>(
352    device: &B::Device,
353    data: ArrayBase<S, D>,
354    fourier_features: NonZeroUsize,
355    fourier_scale: Positive<f64>,
356    num_blocks: NonZeroUsize,
357    learning_rate: Positive<f64>,
358    num_epochs: usize,
359    mini_batch_size: Option<NonZeroUsize>,
360    seed: u64,
361) -> Result<Array<u8, Ix1>, FourierNetworkCodecError> {
362    let Some(mean) = data.mean() else {
363        return Ok(Array::from_vec(Vec::new()));
364    };
365    let stdv = data.std(T::ZERO);
366    let stdv = if stdv == T::ZERO { T::ONE } else { stdv };
367
368    if !Zip::from(&data).all(|x| x.is_finite()) {
369        return Err(FourierNetworkCodecError::NonFiniteData);
370    }
371
372    B::seed(seed);
373
374    let b_t = Tensor::<B, 2, Float>::random(
375        [data.ndim(), fourier_features.get()],
376        Distribution::Normal(0.0, fourier_scale.0),
377        device,
378    );
379
380    let train_xs = flat_grid_like(&data, device);
381    let train_xs = fourier_mapping(train_xs, b_t.clone());
382
383    let train_ys_shape = [data.len(), 1];
384    let mut train_ys = data.into_owned();
385    train_ys.mapv_inplace(|x| (x - mean) / stdv);
386    #[expect(clippy::unwrap_used)] // reshape with one extra new axis cannot fail
387    let train_ys = train_ys
388        .into_shape_clone((train_ys_shape, Order::RowMajor))
389        .unwrap();
390    let train_ys = Tensor::from_data(
391        TensorData::new(train_ys.into_raw_vec_and_offset().0, train_ys_shape),
392        device,
393    );
394
395    let model = train(
396        device,
397        &train_xs,
398        &train_ys,
399        fourier_features,
400        num_blocks,
401        learning_rate,
402        num_epochs,
403        mini_batch_size,
404        stdv,
405    );
406
407    let extra = ModelExtra {
408        model: model.into_record(),
409        b_t: Param::from_tensor(b_t).set_require_grad(false),
410        mean: Param::from_tensor(Tensor::from_data(
411            TensorData::new(vec![mean], vec![1]),
412            device,
413        ))
414        .set_require_grad(false),
415        stdv: Param::from_tensor(Tensor::from_data(
416            TensorData::new(vec![stdv], vec![1]),
417            device,
418        ))
419        .set_require_grad(false),
420        version: StaticCodecVersion,
421    };
422
423    let recorder = BinBytesRecorder::<T::Precision>::new();
424    let encoded = recorder.record(extra, ()).map_err(NeuralNetworkError)?;
425
426    Ok(Array::from_vec(encoded))
427}
428
429#[expect(clippy::missing_panics_doc)] // only panics on implementation bugs
430/// Decodes the `encoded` data into the `decoded` output array by making a
431/// prediction using the fourier feature neural network.
432///
433/// The network must have been trained during [`encode`] using the same number
434/// of `feature_features` and `num_blocks`.
435///
436/// # Errors
437///
438/// Errors with
439/// - [`FourierNetworkCodecError::MismatchedDecodeIntoArray`] if the encoded
440///   array is empty but the decoded array is not
441/// - [`FourierNetworkCodecError::NeuralNetworkError`] if an error occurs during
442///   the neural network computation
443pub fn decode_into<T: FloatExt, S: Data<Elem = u8>, D: Dimension, B: Backend<FloatElem = T>>(
444    device: &B::Device,
445    encoded: ArrayBase<S, Ix1>,
446    mut decoded: ArrayViewMut<T, D>,
447    fourier_features: NonZeroUsize,
448    num_blocks: NonZeroUsize,
449) -> Result<(), FourierNetworkCodecError> {
450    if encoded.is_empty() {
451        if decoded.is_empty() {
452            return Ok(());
453        }
454
455        return Err(FourierNetworkCodecError::MismatchedDecodeIntoArray {
456            source: AnyArrayAssignError::ShapeMismatch {
457                src: encoded.shape().to_vec(),
458                dst: decoded.shape().to_vec(),
459            },
460        });
461    }
462
463    let encoded = encoded.into_owned().into_raw_vec_and_offset().0;
464
465    let recorder = BinBytesRecorder::<T::Precision>::new();
466    let record: ModelExtra<B> = recorder.load(encoded, device).map_err(NeuralNetworkError)?;
467
468    let model = ModelConfig::new(fourier_features, num_blocks)
469        .init(device)
470        .load_record(record.model);
471    let b_t = record.b_t.into_value();
472    let mean = record.mean.into_value().into_scalar();
473    let stdv = record.stdv.into_value().into_scalar();
474
475    let test_xs = flat_grid_like(&decoded, device);
476    let test_xs = fourier_mapping(test_xs, b_t);
477
478    let prediction = model.forward(test_xs).into_data();
479    #[expect(clippy::unwrap_used)] // same generic type, check must succeed
480    let prediction = prediction.as_slice().unwrap();
481
482    #[expect(clippy::unwrap_used)] // prediction shape is flattened
483    decoded.assign(&ArrayView::from_shape(decoded.shape(), prediction).unwrap());
484    decoded.mapv_inplace(|x| (x * stdv) + mean);
485
486    Ok(())
487}
488
489fn flat_grid_like<T: FloatExt, S: Data<Elem = T>, D: Dimension, B: Backend<FloatElem = T>>(
490    a: &ArrayBase<S, D>,
491    device: &B::Device,
492) -> Tensor<B, 2, Float> {
493    let grid = a
494        .shape()
495        .iter()
496        .copied()
497        .map(|s| {
498            // (0..s).into_iter(), fixed in 1.97
499            #[allow(clippy::useless_conversion)]
500            (0..s)
501                .into_iter()
502                .map(move |x| <T as FloatExt>::from_usize(x) / <T as FloatExt>::from_usize(s))
503        })
504        .multi_cartesian_product()
505        .flatten()
506        .collect::<Vec<_>>();
507
508    Tensor::from_data(TensorData::new(grid, [a.len(), a.ndim()]), device)
509}
510
511fn fourier_mapping<B: Backend>(
512    xs: Tensor<B, 2, Float>,
513    b_t: Tensor<B, 2, Float>,
514) -> Tensor<B, 2, Float> {
515    let xs_proj = xs.mul_scalar(core::f64::consts::TAU).matmul(b_t);
516
517    Tensor::cat(vec![xs_proj.clone().sin(), xs_proj.cos()], 1)
518}
519
520#[expect(clippy::similar_names)] // train_xs and train_ys
521#[expect(clippy::too_many_arguments)] // FIXME
522fn train<T: FloatExt, B: AutodiffBackend<FloatElem = T>>(
523    device: &B::Device,
524    train_xs: &Tensor<B, 2, Float>,
525    train_ys: &Tensor<B, 2, Float>,
526    fourier_features: NonZeroUsize,
527    num_blocks: NonZeroUsize,
528    learning_rate: Positive<f64>,
529    num_epochs: usize,
530    mini_batch_size: Option<NonZeroUsize>,
531    stdv: T,
532) -> Model<B> {
533    let num_samples = train_ys.shape().num_elements();
534    let num_batches = mini_batch_size.map(|b| num_samples.div_ceil(b.get()));
535
536    let mut model = ModelConfig::new(fourier_features, num_blocks).init(device);
537    let mut optim = AdamConfig::new().init();
538
539    let mut best_loss = T::infinity();
540    let mut best_epoch = 0;
541    let mut best_model_checkpoint = model.clone().into_record().into_item::<T::Precision>();
542
543    for epoch in 1..=num_epochs {
544        #[expect(clippy::option_if_let_else)]
545        let (train_xs_batches, train_ys_batches) = match num_batches {
546            Some(num_batches) => {
547                let shuffle = Tensor::<B, 1, Float>::random(
548                    [num_samples],
549                    Distribution::Uniform(0.0, 1.0),
550                    device,
551                );
552                let shuffle_indices = shuffle.argsort(0);
553
554                let train_xs_shuffled = train_xs.clone().select(0, shuffle_indices.clone());
555                let train_ys_shuffled = train_ys.clone().select(0, shuffle_indices);
556
557                (
558                    train_xs_shuffled.chunk(num_batches, 0),
559                    train_ys_shuffled.chunk(num_batches, 0),
560                )
561            }
562            None => (vec![train_xs.clone()], vec![train_ys.clone()]),
563        };
564
565        let mut loss_sum = T::ZERO;
566
567        let mut se_sum = T::ZERO;
568        let mut ae_sum = T::ZERO;
569        let mut l_inf = T::ZERO;
570
571        for (train_xs_batch, train_ys_batch) in train_xs_batches.into_iter().zip(train_ys_batches) {
572            let prediction = model.forward(train_xs_batch);
573            let loss =
574                MseLoss::new().forward(prediction.clone(), train_ys_batch.clone(), Reduction::Mean);
575
576            let grads = GradientsParams::from_grads(loss.backward(), &model);
577            model = optim.step(learning_rate.0, model, grads);
578
579            loss_sum += loss.into_scalar();
580
581            let err = prediction - train_ys_batch;
582
583            se_sum += (err.clone() * err.clone()).sum().into_scalar();
584            ae_sum += err.clone().abs().sum().into_scalar();
585            l_inf = l_inf.max(err.abs().max().into_scalar());
586        }
587
588        let loss_mean = loss_sum / <T as FloatExt>::from_usize(num_batches.unwrap_or(1));
589
590        if loss_mean < best_loss {
591            best_loss = loss_mean;
592            best_epoch = epoch;
593            best_model_checkpoint = model.clone().into_record().into_item::<T::Precision>();
594        }
595
596        let rmse = stdv * (se_sum / <T as FloatExt>::from_usize(num_samples)).sqrt();
597        let mae = stdv * ae_sum / <T as FloatExt>::from_usize(num_samples);
598        let l_inf = stdv * l_inf;
599
600        log::info!(
601            "[{epoch}/{num_epochs}]: loss={loss_mean:0.3} MAE={mae:0.3} RMSE={rmse:0.3} Linf={l_inf:0.3}"
602        );
603    }
604
605    if best_epoch != num_epochs {
606        model = model.load_record(ModelRecord::from_item(best_model_checkpoint, device));
607
608        log::info!("restored from epoch {best_epoch} with lowest loss={best_loss:0.3}");
609    }
610
611    model
612}
613
614#[cfg(test)]
615#[expect(clippy::unwrap_used)]
616mod tests {
617    use super::*;
618
619    #[test]
620    fn empty() {
621        std::mem::drop(simple_logger::init());
622
623        let encoded = encode::<f32, _, _, Autodiff<NdArray<f32>>>(
624            &NdArrayDevice::Cpu,
625            Array::<f32, _>::zeros((0,)),
626            NonZeroUsize::MIN,
627            Positive(1.0),
628            NonZeroUsize::MIN,
629            Positive(1e-4),
630            10,
631            None,
632            42,
633        )
634        .unwrap();
635        assert!(encoded.is_empty());
636        let mut decoded = Array::<f32, _>::zeros((0,));
637        decode_into::<f32, _, _, NdArray<f32>>(
638            &NdArrayDevice::Cpu,
639            encoded,
640            decoded.view_mut(),
641            NonZeroUsize::MIN,
642            NonZeroUsize::MIN,
643        )
644        .unwrap();
645    }
646
647    #[test]
648    fn ones() {
649        std::mem::drop(simple_logger::init());
650
651        let encoded = encode::<f32, _, _, Autodiff<NdArray<f32>>>(
652            &NdArrayDevice::Cpu,
653            Array::<f32, _>::zeros((1, 1, 1, 1)),
654            NonZeroUsize::MIN,
655            Positive(1.0),
656            NonZeroUsize::MIN,
657            Positive(1e-4),
658            10,
659            None,
660            42,
661        )
662        .unwrap();
663        let mut decoded = Array::<f32, _>::zeros((1, 1, 1, 1));
664        decode_into::<f32, _, _, NdArray<f32>>(
665            &NdArrayDevice::Cpu,
666            encoded,
667            decoded.view_mut(),
668            NonZeroUsize::MIN,
669            NonZeroUsize::MIN,
670        )
671        .unwrap();
672    }
673
674    #[test]
675    fn r#const() {
676        std::mem::drop(simple_logger::init());
677
678        let encoded = encode::<f32, _, _, Autodiff<NdArray<f32>>>(
679            &NdArrayDevice::Cpu,
680            Array::<f32, _>::from_elem((2, 1, 3), 42.0),
681            NonZeroUsize::MIN,
682            Positive(1.0),
683            NonZeroUsize::MIN,
684            Positive(1e-4),
685            10,
686            None,
687            42,
688        )
689        .unwrap();
690        let mut decoded = Array::<f32, _>::zeros((2, 1, 3));
691        decode_into::<f32, _, _, NdArray<f32>>(
692            &NdArrayDevice::Cpu,
693            encoded,
694            decoded.view_mut(),
695            NonZeroUsize::MIN,
696            NonZeroUsize::MIN,
697        )
698        .unwrap();
699    }
700
701    #[test]
702    fn const_batched() {
703        std::mem::drop(simple_logger::init());
704
705        let encoded = encode::<f32, _, _, Autodiff<NdArray<f32>>>(
706            &NdArrayDevice::Cpu,
707            Array::<f32, _>::from_elem((2, 1, 3), 42.0),
708            NonZeroUsize::MIN,
709            Positive(1.0),
710            NonZeroUsize::MIN,
711            Positive(1e-4),
712            10,
713            Some(NonZeroUsize::MIN.saturating_add(1)),
714            42,
715        )
716        .unwrap();
717        let mut decoded = Array::<f32, _>::zeros((2, 1, 3));
718        decode_into::<f32, _, _, NdArray<f32>>(
719            &NdArrayDevice::Cpu,
720            encoded,
721            decoded.view_mut(),
722            NonZeroUsize::MIN,
723            NonZeroUsize::MIN,
724        )
725        .unwrap();
726    }
727
728    #[test]
729    fn linspace() {
730        std::mem::drop(simple_logger::init());
731
732        let data = Array::linspace(0.0_f64, 100.0_f64, 100);
733
734        let fourier_features = NonZeroUsize::new(16).unwrap();
735        let fourier_scale = Positive(10.0);
736        let num_blocks = NonZeroUsize::new(2).unwrap();
737        let learning_rate = Positive(1e-4);
738        let num_epochs = 100;
739        let seed = 42;
740
741        for mini_batch_size in [
742            None,                                         // no mini-batching
743            Some(NonZeroUsize::MIN),                      // stochastic
744            Some(NonZeroUsize::MIN.saturating_add(6)),    // mini-batched, remainder
745            Some(NonZeroUsize::MIN.saturating_add(9)),    // mini-batched
746            Some(NonZeroUsize::MIN.saturating_add(1000)), // mini-batched, truncated
747        ] {
748            let mut decoded = Array::<f64, _>::zeros(data.shape());
749            let encoded = encode::<f64, _, _, Autodiff<NdArray<f64>>>(
750                &NdArrayDevice::Cpu,
751                data.view(),
752                fourier_features,
753                fourier_scale,
754                num_blocks,
755                learning_rate,
756                num_epochs,
757                mini_batch_size,
758                seed,
759            )
760            .unwrap();
761
762            decode_into::<f64, _, _, NdArray<f64>>(
763                &NdArrayDevice::Cpu,
764                encoded,
765                decoded.view_mut(),
766                fourier_features,
767                num_blocks,
768            )
769            .unwrap();
770        }
771    }
772}