use burn::{
    module::Module,
    nn::{Embedding, EmbeddingConfig},
    tensor::{Device, Int, Tensor},
};

#[derive(Module, Debug)]
pub struct Net {
    embed: Embedding,
}

impl Net {
    /// Create a new model.
    pub fn init(device: &Device) -> Self {
        let embed = EmbeddingConfig::new(10, 3).init(device);
        Self { embed }
    }

    /// Forward pass of the model.
    pub fn forward(&self, x: Tensor<2, Int>) -> Tensor<3> {
        self.embed.forward(x)
    }
}

#[cfg(test)]
mod tests {

    use burn::tensor::Tolerance;
    use burn_store::{ModuleSnapshot, PytorchStore};

    use super::*;

    fn embedding(model: Net, precision: f32) {
        let device = Default::default();

        let input = Tensor::<2, Int>::from_data([[1, 2, 4, 5], [4, 3, 2, 9]], &device);

        let output = model.forward(input);

        let expected = Tensor::<3>::from_data(
            [
                [
                    [-1.609_484_9, -0.10016718, -0.609_188_9],
                    [-0.97977227, -1.609_096_3, -0.712_144_6],
                    [-0.22227049, 1.687_113_4, -0.32062083],
                    [-0.29934573, 1.879_345_7, -0.07213178],
                ],
                [
                    [-0.22227049, 1.687_113_4, -0.32062083],
                    [0.303_722, -0.777_314_3, -0.25145486],
                    [-0.97977227, -1.609_096_3, -0.712_144_6],
                    [-0.02878714, 2.357_111, -1.037_338_7],
                ],
            ],
            &device,
        );

        output
            .to_data()
            .assert_approx_eq::<f32>(&expected.to_data(), Tolerance::absolute(precision));
    }

    #[test]
    fn embedding_full_precision() {
        let device = Default::default();
        let mut model = Net::init(&device);
        let mut store = PytorchStore::from_file("tests/embedding/embedding.pt");
        model
            .load_from(&mut store)
            .expect("Should decode state successfully");

        embedding(model, 1e-3);
    }

    #[test]
    fn embedding_half_precision() {
        let device = Default::default();
        let mut model = Net::init(&device);
        let mut store = PytorchStore::from_file("tests/embedding/embedding.pt");
        model
            .load_from(&mut store)
            .expect("Should decode state successfully");

        embedding(model, 1e-3);
    }
}
