:- module(train, [mlp/3, step/6, tensor/3, on_device/3, train/6]).
:- use_module(library(array)).
:- use_module(library(array/api)).
:- use_module(library(array/buffer), [buffer_from_data/4, buffer_to_data/4]).

/** <module> Training an MLP by gradient descent, one handle per step

The use case of reverse mode with a handle of several outputs: the loss of a two-layer MLP
on a batch, its gradients in the weights by grads/2 of the overlay, and the weights after
one step of gradient descent are one program, compiled once by compile_all/3. A step is a
call of the handle: the batch and the weights in, the loss and the new weights out, names
realized on the device, given back as the weights of the next call. Nothing is allocated
or compiled between two steps but the results.

    mlp(+X, +Weights, -Y)
        Y = gelu(X W1 + B1) W2 + B2, Weights = [W1, B1, W2, B2].

    step(+Device, +dims(B, D, H, O), +Rate, -Exe, -Inputs, -Weights)
        Exe = step(Handle, Slots), the handle of a step on Device for batches of B inputs
        of D features, H hidden units and O outputs; B is a number, or an extent with an
        upper bound, one handle then serving every batch, scheduled for the least: its results are
        [Loss | NewWeights], the loss on host. Inputs = [X, T], the batch and its targets,
        names on host, and Weights the four names of the weights, on Device: the slots of
        the handle are those six names, Slots, in the order signature_all/4 gives.

    train(+Step, +Batch, +Weights0, +Steps, -Losses, -Weights)
        Steps calls of the handle of Step on Batch, Name-Realized pairs for the inputs, from the weights
        Weights0, Name-Realized pairs: the loss of each step, and the weights after the last.

    ?- B::integer(1, 64), step(pocl, dims(B, 4, 16, 2), 0.1, Exe, [X, T], Ws), ...
*/

mlp(X, [W1, B1, W2, B2], Y) :-
   H @= X @ W1 + B1,
   A @= H * (1 / (1 + exp(-1.702 * H))),
   Y @= A @ W2 + B2.

step(Device, dims(B, D, H, O), Rate, step(Exe, Slots), [Xh, Th], Weights) :-
   shape(Xh, [B, D]), device(Xh, host),
   shape(Th, [B, O]), device(Th, host),
   copy(Xh, X, Device),
   copy(Th, T, Device),
   Weights = [W1, B1, W2, B2],
   shape(W1, [D, H]), shape(B1, [H]), shape(W2, [H, O]), shape(B2, [O]),
   maplist(lives_on(Device), Weights),
   mlp(X, Weights, Y),
   L @= mean((Y - T) * (Y - T)),
   Gs @= grads(L, Weights),
   maplist(descent(Rate), Weights, Gs, News),
   copy(L, Lh, host),
   Outs = [Lh | News],
   compile_all(Outs, [device(Device)], Exe),
   signature_all(Outs, Slots0, _, _),
   maplist([slot(N, _, _, _), N]>>true, Slots0, Slots).

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

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

% tensor(+Shape, +Values, -Name): a float name realized on host with Values.
tensor(Shape, Values, Name) :-
   foldl([E, P0, P]>>(P is P0*E), Shape, 1, N),
   compound_name_arguments(Data, data, Values),
   buffer_from_data(Buffer, float32, N, Data),
   shape(Name, Shape),
   kind(Name, float),
   value(Name, Buffer).

% on_device(+Device, +Host, -Name): the elements of the realized name Host, realized on Device.
on_device(Device, Host, Name) :-
   copy(Host, Name, Device),
   realize([Name], [], [device(Device)]).

train(step(Exe, Slots), Batch, Weights0, Steps, Losses, Weights) :-
   pairs_keys(Weights0, Names),
   length(Losses, Steps),
   foldl(step_once(Exe, Slots, Batch, Names), Losses, Weights0, Weights).

step_once(Exe, Slots, Batch, Names, Loss, Weights0, Weights) :-
   append(Batch, Weights0, Bound),
   maplist(argument(Bound), Slots, Args),
   run(Exe, Args, [L | News]),
   run(L, [], [Loss], []),
   pairs_keys_values(Weights, Names, News).

argument(Bound, Slot, Arg) :-
   member(Name-Arg, Bound),
   Name == Slot,
   !.
