:- module(bench_train, [go_train/1, go_train/2]).
:- use_module(library(array)).
:- use_module('../examples/train').

% One step of gradient descent on the MLP of examples/train.pl, the batch 256 by 768, 3072
% hidden units: the loss, the four gradients and the four new weights in one handle.
% Compare with bench_train.py.
%
%   swipl -g "go_train(nvidia)" -t halt bench/bench_train.pl

go_train(Device) :-
   go_train(Device, dims(256, 768, 3072, 768)).

go_train(Device, dims(B, D, H, O)) :-
   step(Device, dims(B, D, H, O), 0.01, Step, [X, T], Ws),
   BD is B*D, BO is B*O, DH is D*H, HO is H*O,
   random_tensor([B, D], BD, 1.0, 0.0, Xt),
   random_tensor([B, O], BO, 1.0, 0.0, Tt),
   random_tensor([D, H], DH, 0.02, -0.01, W1), random_tensor([H], H, 1.0, 0.0, B1),
   random_tensor([H, O], HO, 0.02, -0.01, W2), random_tensor([O], O, 1.0, 0.0, B2),
   maplist(on_device(Device), [W1, B1, W2, B2], Devs),
   pairs_keys_values(Weights0, Ws, Devs),
   train(Step, [X-Xt, T-Tt], Weights0, 2, Warm, Weights1),
   findall(Ms, ( between(1, 5, _),
                 statistics(walltime, [T0, _]),
                 train(Step, [X-Xt, T-Tt], Weights1, 5, _, _),
                 statistics(walltime, [T1, _]),
                 Ms is (T1 - T0) / 5 ),
           Times),
   min_list(Times, Best),
   format("train step ~dx~dx~dx~d  ~w  best=~3f ms  (losses ~w)~n", [B, D, H, O, Device, Best, Warm]).

random_tensor(Shape, N, Scale, Shift, Name) :-
   length(Values, N),
   maplist({Scale, Shift}/[V]>>(V is random_float * Scale + Shift), Values),
   tensor(Shape, Values, Name).
