:- module(classifier, [classifier/4, weights/1, weights/2, inputs/2, serve/1]).
:- use_module(library(array)).
:- use_module(library(array/safetensors)).
:- use_module(library(array/buffer), [buffer_to_data/4]).
:- use_module(library(clpBNR)).
:- use_module(example_data).

/** <module> Inference of an MLP classifier, its weights and inputs from safetensors files

The use case of a handle: a classifier whose batch size is unknown is compiled once, and runs
on batch after batch of new inputs, each of its own size, the weights the same every time.
The weights are read from a safetensors file, names realized on host, copied to a device
and realized there, once; the inputs are read from another, a batch a name on host; the
program copies a batch to the device, runs the network there, and copies the logits back.

    classifier(+Net, -X, -Y, ?Device)
        X[B, 784] a name on host, the inputs, B an extent in 1..1024; Y[B, 10] a name on
        host, the logits; Net the weights, the tree of the state_dict torch saves,
        fc1.weight [256, 784], fc1.bias [256], fc2.weight [128, 256], fc2.bias [128],
        fc3.weight [10, 128], fc3.bias [10], a torch Linear holding its weight as [out, in]:
        Y = relu(relu(X W1' + B1) W2' + B2) W3' + B3.
        Device is where the network runs: the device of the weights when they are
        realized on one, else a variable, placed by the device(D) of compile/3 or run/4.

Both files are written by classifier.py, from a seeded torch model, and downloaded from the
release examples-data-1 by example_file/2 where they are not beside this file:

    classifier_weights.safetensors   the state_dict, read by weights/1, on host, or by
                                     weights/2, realized on a device;
    classifier_inputs.safetensors    batches.K, the inputs of batch K, and logits.K, what
                                     torch computes for them, read by inputs/2.

B stays symbolic: run(Y, [X-Batch], Logits, [result(name)]) runs the program on a batch, a
name read from the file, binding B for that run alone. The first run compiles the program,
once, for every batch size, and keeps its handle on Y; every run after is a launch. serve/1
does so for every batch of the inputs file, and writes the logits to
classifier_logits.safetensors, logits.K the logits of batch K.

    ?- weights(pocl, Net), classifier(Net, X, Y, D),
       inputs([X0 | _], _), run(Y, [X-X0], Logits, [result(name)]).
*/

classifier(Net, Xh, Yh, Device) :-
   B::integer(1, 1024),
   shape(Xh, [B, 784]),
   device(Xh, host),
   copy(Xh, X, Device),
   dense(X, Net.fc1.weight, Net.fc1.bias, H1, B, 784, 256), relu(H1, A1, B, 256),
   dense(A1, Net.fc2.weight, Net.fc2.bias, H2, B, 256, 128), relu(H2, A2, B, 128),
   dense(A2, Net.fc3.weight, Net.fc3.bias, Y, B, 128, 10),
   copy(Y, Yh, host).

% dense(+X, +W, +Bias, -Y, +B, +In, +Out): Y = X W' + Bias, X of B rows of In, W of Out rows
% of In, as torch holds a Linear's weight.
dense(X, W, Bias, Y, B, In, Out) :-
   shape(W, [Out, In]), shape(Bias, [Out]), shape(Y, [B, Out]),
   over([I:B, J:Out], [Y[I, J] := Bias[J]]),
   over([I:B, J:Out, K:In], [Y[I, J] := Y[I, J] + X[I, K] * W[J, K]]).

relu(X, Y, B, N) :-
   shape(Y, [B, N]),
   over([I:B, J:N], [Y[I, J] := max(0, X[I, J])]).

% weights(-Net): the tree of classifier_weights.safetensors, its names realized on host.
weights(Net) :-
   example_file('classifier_weights.safetensors', File),
   safetensors_read(File, Net, _).

% weights(+Device, -Net): the tree of classifier_weights.safetensors realized on Device: each
% name of the file copied there, and the copies realized, their elements uploaded once.
weights(Device, Net) :-
   weights(Host),
   on_device(Device, Host, Net, Names, []),
   realize(Names, [], [device(Device)]).

% on_device(+Device, +Tree, -Copy, -Names, ?Tail): Copy is Tree with each name copied to Device,
% Names the copies.
on_device(Device, T, C, Ns0, Ns), var(T) =>
   copy(T, C, Device),
   Ns0 = [C | Ns].
on_device(Device, T, C, Ns0, Ns), is_dict(T) =>
   dict_pairs(T, Tag, Pairs),
   foldl([K-V, K-Cv, N0, N]>>on_device(Device, V, Cv, N0, N), Pairs, Copies, Ns0, Ns),
   dict_pairs(C, Tag, Copies).
on_device(Device, T, C, Ns0, Ns), is_list(T) =>
   foldl([V, Cv, N0, N]>>on_device(Device, V, Cv, N0, N), T, C, Ns0, Ns).

% inputs(-Batches, -Logits): the batches of classifier_inputs.safetensors, names on host, and
% the logits torch computed for each.
inputs(Batches, Logits) :-
   example_file('classifier_inputs.safetensors', File),
   safetensors_read(File, _{batches: Batches, logits: Logits}, _).

data_file(Name, File) :-
   module_property(classifier, file(Here)),
   file_directory_name(Here, Dir),
   directory_file_path(Dir, Name, File).

% serve(+Options): the weights realized on the device of device(D), pocl by default, and the
% classifier run on every batch of the inputs file, the first run compiling it; prints the
% seconds each run takes and its greatest difference from the logits of torch, checks the
% smallest batch against eval/3, and writes the logits to classifier_logits.safetensors.
serve(Options) :-
   option(device(Device), Options, pocl),
   weights(Device, Net),
   inputs(Batches, Logits),
   classifier(Net, Xh, Yh, _),
   foldl(serve_batch(Xh, Yh, Logits, Options), Batches, 0-[], _-Results),
   reverse(Results, Ordered),
   data_file('classifier_logits.safetensors', File),
   safetensors_write(File, _{logits: Ordered}, _{format: pt}),
   shape(Xh, [B, _]), var(B).

serve_batch(Xh, Yh, Logits, Options, Xb, K-Rs, K1-[R | Rs]) :-
   K1 is K + 1,
   nth0(K, Logits, Expected),
   shape(Xb, [N, _]),
   statistics(cputime, T0), get_time(W0),
   run(Yh, [Xh-Xb], R, [result(name) | Options]),
   statistics(cputime, T1), get_time(W1),
   Cpu is T1 - T0, Wall is W1 - W0,
   host_elements(R, Values),
   host_elements(Expected, Torch),
   max_error(Values, Torch, Err),
   format("batch ~d: ~3f s cpu, ~3f s wall, max error against torch ~e~n", [N, Cpu, Wall, Err]),
   (  K =:= 0
   -> eval(Yh, [Xh-Xb], Ref),
      max_error(Values, Ref, RefErr),
      format("  against eval/3: max error ~e~n", [RefErr])
   ;  true
   ).

% host_elements(+Name, -Values): the elements of a realized name on host, row-major.
host_elements(Name, Values) :-
   value(Name, Buffer),
   shape(Name, Shape),
   foldl([E, P0, P]>>(P is P0*E), Shape, 1, N),
   buffer_to_data(Buffer, float32, N, Data),
   compound_name_arguments(Data, _, Values).

max_error(Values, Reference, Err) :-
   maplist([A, R, D]>>(D is abs(A - R)), Values, Reference, Ds),
   max_list(Ds, Err).
