:- module(mnist, [mnist/1, data/2, net/3, cross_entropy/5, step/7, step_program/7, accuracy/5, weights/3]).
:- use_module(library(array)).
:- use_module(library(array/api)).
:- use_module(library(array/safetensors)).
:- use_module(library(array/handle), [signature/4]).
:- use_module(library(array/buffer), [buffer_from_data/4]).
:- use_module(library(random)).
:- use_module(train, [tensor/3, on_device/3]).
:- use_module(example_data).

/** <module> Training a classifier of the MNIST digits

An MLP of one hidden layer, trained by minibatch gradient descent on the 60000 digits of
MNIST and scored on the 10000 of its test set, everything on the device:

  - the images and the labels are read from mnist.safetensors, written by mnist.py or
    downloaded by example_file/2, copied
    to the device and realized there once: constants of the handles;
  - a step is one handle of several outputs, compile_all/3: the loss of a batch, its
    gradients by grads/2 of the overlay, and the weights after the step. Its batch is the
    int name Idx, the places of its images among the 60000: the program gathers them, so
    that a step uploads the indices of a batch and nothing else, and an epoch is a
    permutation of the places cut in batches;
  - the accuracy is another handle, the whole test set through the network at once, the
    count of the digits whose label has the greatest logit.

    mnist(+Options)
        trains and prints the loss as it goes and the accuracy after each epoch. Options:
        device(D), pocl by default; epochs(E), 1; batch(B), 100; rate(R), 0.1; hidden(H),
        128; report(K), the mean loss printed every K steps, 100; steps(S), an epoch cut
        short at S steps.

    ?- mnist([device(nvidia), epochs(3)]).

The loss is the cross-entropy of the softmax of the logits against the label, written from
the log of the sum of the exponentials, shifted by the greatest logit of each row for it not
to overflow: the shift changes nothing, so it is a constant of the derivative,
stop_gradient/1, and no gradient is computed through the max. The label takes its logit by
a comparison, where(J =:= Label, ...), not by a gather, so that the adjoint of the logits is
one equation, fused into the backward of the last layer.
*/

% data(+Device, -Data): the digits on Device: Data.train.images [60000, 784], floats in
% 0..1, Data.train.labels [60000], ints in 0..9, and Data.test the same of 10000.
data(Device, Data) :-
   example_file('mnist.safetensors', File),
   safetensors_read(File, Host, _),
   on_device(Device, Host.train.images, TrainX), on_device(Device, Host.train.labels, TrainY),
   on_device(Device, Host.test.images, TestX), on_device(Device, Host.test.labels, TestY),
   Data = _{train: _{images: TrainX, labels: TrainY}, test: _{images: TestX, labels: TestY}}.

% net(+X, +Weights, -Y): the logits Y = relu(X W1 + B1) W2 + B2, Weights = [W1, B1, W2, B2].
net(X, [W1, B1, W2, B2], Y) :-
   A @= maximum(X @ W1 + B1, 0),
   Y @= A @ W2 + B2.

% cross_entropy(+Y, +Label, +B, +Classes, -L): L, the mean over the B rows of Y of the
% cross-entropy of softmax(Y[I]) against its label: Label is the read of the label of row I,
% a value in I, as Labels[Idx[I]] is, in 0..Classes-1.
cross_entropy(Y, I-Label, B, Classes, L) :-
   M @= stop_gradient(max(Y, [axis(1), keepdims(true)])),
   Lse @= log(sum(exp(Y - M), [axis(1)])),
   shape(Nll, []),
   over([], [Nll := 0]),
   over([I:B, J:Classes], [Nll := Nll + where(J =:= Label, Lse[I] + M[I, 0] - Y[I, J], 0)]),
   L @= Nll / B.

% step(+Device, +Data, +dims(B, H), +Rate, -Step, -Idx, -Weights): Step = step(Exe, Slots),
% the handle of a step of gradient descent on a batch of B digits of Data.train, an MLP of
% H hidden units: its results are [Loss | NewWeights], the loss on host. Idx[B], on host,
% holds the places of the batch among the digits; Weights are the four names of the weights,
% on Device; Slots are those five names in the order of the handle's arguments.
step(Device, Data, Dims, Rate, step(Exe, Slots), Idxh, Weights) :-
   step_program(Device, Data, Dims, Rate, Idxh, Weights, Outs),
   compile_all(Outs, [device(Device)], Exe),
   signature_all(Outs, Slots0, _, _),
   maplist(slot_name, Slots0, Slots).

% step_program(+Device, +Data, +dims(B, H), +Rate, -Idx, -Weights, -Outs): the program of a
% step, not compiled: Outs = [Loss | NewWeights], the loss on host.
step_program(Device, Data, dims(B, H), Rate, Idxh, Weights, Outs) :-
   Images = Data.train.images, Labels = Data.train.labels,
   shape(Images, [N, D]),
   shape(Idxh, [B]), kind(Idxh, int), device(Idxh, host), elements(Idxh, 0-(N-1)),
   copy(Idxh, Idx, Device),
   shape(X, [B, D]),
   over([I:B, K:D], [X[I, K] := Images[Idx[I], K]]),
   weight_names(Device, D, H, 10, Weights),
   net(X, Weights, Y),
   cross_entropy(Y, I2-Labels[Idx[I2]], B, 10, L),
   Gs @= grads(L, Weights),
   maplist(descent(Rate), Weights, Gs, News),
   copy(L, Lh, host),
   Outs = [Lh | News].

slot_name(slot(Name, _, _, _), Name).

descent(Rate, W, G, New) :-
   New @= W - Rate * G.

weight_names(Device, D, H, O, [W1, B1, W2, B2]) :-
   shape(W1, [D, H]), shape(B1, [H]), shape(W2, [H, O]), shape(B2, [O]),
   maplist(lives_on(Device), [W1, B1, W2, B2]).

lives_on(Device, W) :-
   device(W, Device).

% accuracy(+Device, +Data, +H, -Score, -Weights): Score = score(Exe, Slots), the handle of
% the accuracy on Data.test of the MLP of H hidden units: the fraction of the digits whose
% label has the greatest logit, on host.
accuracy(Device, Data, H, score(Exe, Slots), Weights) :-
   Images = Data.test.images, Labels = Data.test.labels,
   shape(Images, [N, D]),
   weight_names(Device, D, H, 10, Weights),
   net(Images, Weights, Y),
   M @= max(Y, [axis(1)]),
   shape(Hits, []),
   over([], [Hits := 0]),
   over([I:N], [Hits := Hits + where(Y[I, Labels[I]] >= M[I], 1.0, 0.0)]),
   A @= Hits / N,
   copy(A, Ah, host),
   compile(Ah, [device(Device)], Exe),
   signature(Ah, Slots0, _, _),
   maplist(slot_name, Slots0, Slots).

% weights(+Device, +H, -Weights): the weights of the MLP of H hidden units before training,
% realized on Device: uniform within 1/sqrt of the inputs of their layer, the biases zero.
weights(Device, H, Weights) :-
   uniform([784, H], 784, W1), zeros([H], B1),
   uniform([H, 10], H, W2), zeros([10], B2),
   maplist(on_device(Device), [W1, B1, W2, B2], Weights).

uniform(Shape, FanIn, Name) :-
   foldl([E, P0, P]>>(P is P0*E), Shape, 1, N),
   Bound is 1 / sqrt(FanIn),
   length(Values, N),
   maplist({Bound}/[V]>>(V is (2*random_float - 1) * Bound), Values),
   tensor(Shape, Values, Name).

zeros(Shape, Name) :-
   foldl([E, P0, P]>>(P is P0*E), Shape, 1, N),
   length(Values, N),
   maplist(=(0.0), Values),
   tensor(Shape, Values, Name).

mnist(Options) :-
   option(device(Device), Options, pocl),
   option(epochs(Epochs), Options, 1),
   option(batch(B), Options, 100),
   option(rate(Rate), Options, 0.1),
   option(hidden(H), Options, 128),
   option(report(Report), Options, 100),
   data(Device, Data),
   shape(Data.train.images, [N, _]),
   Most is N // B,
   option(steps(Steps), Options, Most),
   step(Device, Data, dims(B, H), Rate, Step, Idx, Ws),
   accuracy(Device, Data, H, Score, Vs),
   weights(Device, H, Weights0),
   scored(Score, Vs, Weights0, Acc0),
   format("before training: accuracy ~4f~n", [Acc0]),
   numlist(1, Epochs, Es),
   foldl(epoch(Step, Idx, Ws, Score, Vs, N, B, Steps, Report), Es, Weights0, _).

% epoch(+Step, +Idx, +Ws, +Score, +Vs, +N, +B, +Steps, +Report, +E, +Weights0, -Weights):
% Steps batches of B of a permutation of the N places, then the accuracy.
epoch(Step, Idx, Ws, Score, Vs, N, B, Steps, Report, E, Weights0, Weights) :-
   Last is N - 1,
   numlist(0, Last, Places0),
   random_permutation(Places0, Places),
   get_time(T0),
   batches(Steps, B, Places, Step, Idx, Ws, Report, 1, [], Weights0, Weights),
   get_time(T1),
   scored(Score, Vs, Weights, Acc),
   Ms is 1000 * (T1 - T0) / Steps,
   format("epoch ~d: accuracy ~4f, ~3f ms a step~n", [E, Acc, Ms]).

batches(0, _, _, _, _, _, _, _, _, Weights0, Weights) =>
   Weights = Weights0.
batches(Left, B, Places, Step, Idx, Ws, Report, K, Losses0, Weights0, Weights) =>
   length(Batch, B),
   append(Batch, Rest, Places),
   step_once(Step, Idx, Ws, Batch, Weights0, Loss, Weights1),
   reported(Report, K, [Loss | Losses0], Losses),
   Left1 is Left - 1,
   K1 is K + 1,
   batches(Left1, B, Rest, Step, Idx, Ws, Report, K1, Losses, Weights1, Weights).

% step_once(+Step, +Idx, +Ws, +Batch, +Weights0, -Loss, -Weights): one call of the handle on
% the places Batch from Weights0: the loss, a name realized on host, and the new weights.
step_once(step(Exe, Slots), Idx, Ws, Batch, Weights0, Loss, Weights) :-
   length(Batch, B),
   compound_name_arguments(Data, data, Batch),
   buffer_from_data(Buffer, int32, B, Data),
   shape(Arg, [B]), kind(Arg, int), value(Arg, Buffer),
   pairs_keys_values(Bound, [Idx | Ws], [Arg | Weights0]),
   maplist(argument(Bound), Slots, Args),
   run(Exe, Args, [Loss | Weights]).

% argument(+Bound, +Slot, -Arg): the argument of a slot: the name Bound gives it, else the
% slot's own name, one realized, the images and the labels of the data.
argument(Bound, Slot, Arg), member(Name-Arg0, Bound), Name == Slot => Arg = Arg0.
argument(_, Slot, Arg) => Arg = Slot.

% reported(+Report, +K, +Losses0, -Losses): every Report steps, the mean of the losses since
% the last time is printed: the losses stay names until then, read back together.
reported(Report, K, Losses0, Losses), K mod Report =:= 0 =>
   maplist([L, V]>>run(L, [], [V], []), Losses0, Values),
   sum_list(Values, Sum),
   length(Values, Count),
   Mean is Sum / Count,
   format("  step ~d: loss ~4f~n", [K, Mean]),
   Losses = [].
reported(_, _, Losses0, Losses) => Losses = Losses0.

% scored(+Score, +Vs, +Weights, -Accuracy): the accuracy of Weights on the test set.
scored(score(Exe, Slots), Vs, Weights, Accuracy) :-
   pairs_keys_values(Bound, Vs, Weights),
   maplist(argument(Bound), Slots, Args),
   run(Exe, Args, R),
   run(R, [], [Accuracy], []).
