"""The weights and the inputs of examples/classifier.pl, written from PyTorch.

    python classifier.py [DIR]

writes, in DIR (the directory of this script by default):

    classifier_weights.safetensors   the state_dict of the MLP, as torch saves it:
                                     fc1.weight [256, 784], fc1.bias [256], fc2.weight [128, 256],
                                     fc2.bias [128], fc3.weight [10, 128], fc3.bias [10];
    classifier_inputs.safetensors    batches.K [N_K, 784], the inputs of batch K, and
                                     logits.K [N_K, 10], what the model computes for them.

A torch Linear holds its weight as [out, in], and the Prolog program reads it that way. Both
files are float32, and the model is seeded, so that the files are the same on every run.

The files are not in the repository: the examples download them from the GitHub release
examples-data-1 where they are not beside the examples, see example_data.pl. A file written
again differs from its asset: upload it to a new release, and change release/1 and sha256/2
there.
"""

import sys
from pathlib import Path

import torch
from safetensors.torch import save_file

SIZES = [7, 32, 128]


class MLP(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = torch.nn.Linear(784, 256)
        self.fc2 = torch.nn.Linear(256, 128)
        self.fc3 = torch.nn.Linear(128, 10)

    def forward(self, x):
        return self.fc3(torch.relu(self.fc2(torch.relu(self.fc1(x)))))


def main(out_dir):
    torch.manual_seed(0)
    model = MLP()
    weights = {k: v.detach().contiguous() for k, v in model.state_dict().items()}
    save_file(weights, out_dir / "classifier_weights.safetensors", metadata={"format": "pt"})

    inputs = {}
    with torch.no_grad():
        for k, n in enumerate(SIZES):
            x = torch.rand(n, 784)
            inputs[f"batches.{k}"] = x
            inputs[f"logits.{k}"] = model(x)
    save_file(inputs, out_dir / "classifier_inputs.safetensors", metadata={"format": "pt"})


if __name__ == "__main__":
    main(Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent)
