:- module(grad_tests, []).

:- use_module(library(array)).
:- use_module(library(array/grad)).
:- use_module(library(array/api)).
:- use_module(library(array/compile), [kernels/3]).
:- use_module(library(array/opencl), [opencl_device/2]).
:- use_module(test_devices, [test_device/2]).
:- use_module('../examples/ukf', [cv_range_model/3]).
:- use_module('../examples/train').
:- use_module('../examples/mnist', [mnist/1]).
:- use_module('../examples/example_data', [example_file_present/1]).
:- use_module('../examples/linalg', [differentiable_cholesky/3]).
:- use_module(library(clpBNR)).
:- op(20, yf, []).

% The references are evaluated once for every program and data, then read from the disk:
% see reference.pl.
:- set_prolog_flag(eval_cache, true).

% A derivative is checked against central differences of the reference evaluation: the
% vector-Jacobian product OutBar . dOut/dIn element by element of In, and the Jacobian column
% by column.

vals(N, Seed, Vs) :-
   numlist(1, N, Is),
   maplist(val(Seed), Is, Vs).

val(Seed, I, V) :- V is sin(I*Seed + 0.3).

data_of(N, Data, Xs) :-
   member(M-Xs, Data), M == N, !.

replaced(Data, In, Xs, Data1) :-
   maplist(replace(In, Xs), Data, Data1).

replace(In, Xs, N-_, R), N == In => R = N-Xs.
replace(_, _, NV, R) => R = NV.

bump(Xs, K, H, Ys) :-
   nth1(K, Xs, X, Rest),
   X1 is X + H,
   nth1(K, Ys, X1, Rest).

% column(+Out, +Data, +In, +K, -Col): dOut/dIn[K] by central differences.
column(Out, Data, In, K, Col) :-
   H = 1.0e-6,
   data_of(In, Data, Xs),
   bump(Xs, K, H, Xp), bump(Xs, K, -H, Xm),
   replaced(Data, In, Xp, Dp), replaced(Data, In, Xm, Dm),
   eval(Out, Dp, Yp), eval(Out, Dm, Ym),
   maplist({H}/[P, M, D]>>(D is (P - M) / (2*H)), Yp, Ym, Col).

% fd_vjp(+Out, +Data, +In, +Bar, -G): Bar . dOut/dIn.
fd_vjp(Out, Data, In, Bar, G) :-
   data_of(In, Data, Xs), length(Xs, L),
   numlist(1, L, Ks),
   maplist(fd_dot(Out, Data, In, Bar), Ks, G).

fd_dot(Out, Data, In, Bar, K, G) :-
   column(Out, Data, In, K, Col),
   foldl([B, C, S0, S]>>(S is S0 + B*C), Bar, Col, 0.0, G).

near(Xs, Ys) :-
   maplist([X, Y]>>(abs(X - Y) < 1.0e-4 * (1 + abs(Y))), Xs, Ys).

% vjp_matches(+Out, +Data, +Params): the reverse mode of Out agrees with the differences.
vjp_matches(Out, Data, Params) :-
   eval(Out, Data, Ys), length(Ys, NOut), vals(NOut, 0.7, Bar),
   vjp([Out], Params, [OutBar], Grads),
   maplist(grad_matches(Out, [OutBar-Bar | Data], Data, Bar), Params, Grads).

grad_matches(Out, GData, Data, Bar, P, G) :-
   eval(G, GData, Gv),
   fd_vjp(Out, Data, P, Bar, Fd),
   near(Gv, Fd).

matmul(A, B, C) :-
   shape(A, [3, 4]), shape(B, [4, 2]),
   over([I:3, J:2], [C[I, J] := 0]),
   over([I:3, J:2, K:4], [C[I, J] := C[I, J] + A[I, K] * B[K, J]]).

softmax(X, Y) :-
   shape(X, [2, 5]),
   over([I:2], [M[I] := -1.0e30]),
   over([I:2, K:5], [M[I] := max(M[I], X[I, K])]),
   over([I:2], [S[I] := 0]),
   over([I:2, K:5], [S[I] := S[I] + exp(X[I, K] - M[I])]),
   over([I:2, J:5], [Y[I, J] := exp(X[I, J] - M[I]) / S[I]]).

% The same by the overlay: its max starts from the element at 0.
api_softmax(X, Y) :-
   shape(X, [2, 5]),
   E @= exp(X - max(X, [axis(1), keepdims(true)])),
   Y @= E / sum(E, [axis(1), keepdims(true)]).

recurrence(X, C) :-
   shape(X, [6, 2]),
   over([J:2], [C[0, J] := X[0, J]]),
   over([T:5, J:2], [C[T+1, J] := C[T, J] * 0.9 + X[T+1, J]]).

layer_norm(X, G, Xn) :-
   shape(X, [3, 4]), shape(G, [4]),
   over([I:3], [Mu[I] := 0]),
   over([I:3, J:4], [Mu[I] := Mu[I] + X[I, J]]),
   over([I:3], [Var[I] := 0]),
   over([I:3, K:4], [Var[I] := Var[I] + (X[I, K] - Mu[I] / 4) * (X[I, K] - Mu[I] / 4)]),
   over([I:3, J:4], [Xn[I, J] := (X[I, J] - Mu[I] / 4) / sqrt(Var[I] / 4 + 1.0e-5) * G[J]]).

% An embedding looked up, weighted and summed: a gather whose adjoint is a scatter.
embedding(E, Idx, W, Y) :-
   shape(E, [5, 3]), shape(Idx, [4]), kind(Idx, int), elements(Idx, 0-4), shape(W, [4]),
   over([J:3], [Y[J] := 0]),
   over([K:4, J:3], [Y[J] := Y[J] + E[Idx[K], J] * W[K]]).

% Two slabs of one name written by two boxes, and a write of the first overwritten.
slabs(X, Z, Y) :-
   shape(X, [3]), shape(Z, [3]), shape(Y, [6]),
   over([I:3], [Y[I] := X[I] * X[I]]),
   over([I:3], [Y[I+3] := exp(X[I])]),
   over([I:2], [Y[I] := Z[I] * 3]).

:- begin_tests(grad_partials).

test(product, [timeout(10), true(D == B)]) :-
   shape(A, []), shape(B, []),
   partial(A * B, A, D).
test(quotient, [timeout(10), true(D == -(A / (B * B)))]) :-
   shape(A, []), shape(B, []),
   partial(A / B, B, D).
test(where_selects, [timeout(10), true(D == where(A < 0, -1, 1))]) :-
   shape(A, []),
   partial(where(A < 0, -A, A), A, D).
test(subscript_is_constant, [timeout(10), true(D == 1)]) :-
   shape(X, [4]), shape(P, [4]),
   partial(X[P[0]], X[P[0]], D).
test(erf_is_a_gaussian, [timeout(10), true(D == 1.1283791670955126 * exp(-(A * A)))]) :-
   shape(A, []),
   partial(erf(A), A, D).
test(comparison_is_constant, [timeout(10), true(D == 0)]) :-
   shape(A, []),
   partial(A >= 2, A, D).

:- end_tests(grad_partials).

:- begin_tests(grad_reverse).

test(matmul, [timeout(60)]) :-
   matmul(A, B, C), vals(12, 1.1, Av), vals(8, 1.3, Bv),
   vjp_matches(C, [A-Av, B-Bv], [A, B]).
test(softmax_through_a_max_fold, [timeout(60)]) :-
   softmax(X, Y), vals(10, 0.9, Xv),
   vjp_matches(Y, [X-Xv], [X]).
test(softmax_of_the_overlay, [timeout(60)]) :-
   api_softmax(X, Y), vals(10, 0.9, Xv),
   vjp_matches(Y, [X-Xv], [X]).
test(recurrence_runs_backwards, [timeout(60)]) :-
   recurrence(X, C), vals(12, 0.5, Xv),
   vjp_matches(C, [X-Xv], [X]).
test(layer_norm, [timeout(60)]) :-
   layer_norm(X, G, Y), vals(12, 0.4, Xv), vals(4, 2.1, Gv),
   vjp_matches(Y, [X-Xv, G-Gv], [X, G]).
test(gather_gives_a_scatter, [timeout(60)]) :-
   embedding(E, Idx, W, Y), vals(15, 0.6, Ev), vals(4, 1.7, Wv),
   vjp_matches(Y, [E-Ev, Idx-[1, 4, 1, 0], W-Wv], [E, W]).
test(slabs_and_an_overwritten_write, [timeout(60)]) :-
   slabs(X, Z, Y), vals(3, 0.8, Xv), vals(3, 1.9, Zv),
   vjp_matches(Y, [X-Xv, Z-Zv], [X, Z]).
% An elementwise maximum is not a fold: a ReLU between two layers.
test(relu, [timeout(60)]) :-
   shape(X, [3, 2]), shape(W, [2, 2]),
   Y @= maximum(X @ W, 0) @ W,
   vals(6, 0.8, Xv), vals(4, 1.7, Wv),
   vjp_matches(Y, [X-Xv, W-Wv], [X, W]),
   jvp_matches([Y], [X-Xv, W-Wv], [X, W]).
% The exact GELU, by erf, between two layers.
test(gelu_by_erf, [timeout(60)]) :-
   shape(X, [3, 2]), shape(W, [2, 2]),
   H @= X @ W,
   Y @= (0.5 * H * (1 + erf(H / sqrt(2)))) @ W,
   vals(6, 0.8, Xv), vals(4, 1.7, Wv),
   vjp_matches(Y, [X-Xv, W-Wv], [X, W]),
   jvp_matches([Y], [X-Xv, W-Wv], [X, W]).
test(slice_and_broadcast_of_the_overlay, [timeout(60)]) :-
   shape(X, [4, 3]), shape(B, [3]),
   Y @= sum(exp(X[1:_, _]) * B, [axis(0)]) / mean(X),
   vals(12, 0.45, Xv), vals(3, 1.3, Bv),
   vjp_matches(Y, [X-Xv, B-Bv], [X, B]).

% A tie is split between the elements that reach the maximum, and the element a fold starts
% from gets its share once.
test(max_splits_a_tie, [timeout(60), true(Gv == [0.0, 0.5, 0.5])]) :-
   shape(X, [3]),
   M @= max(X),
   grad(M, [X], [G]),
   eval(G, [X-[1.0, 3.0, 3.0]], Gv).
test(max_from_its_first_element, [timeout(60), true(Gv == [1.0, 0.0, 0.0])]) :-
   shape(X, [3]),
   M @= max(X),
   grad(M, [X], [G]),
   eval(G, [X-[5.0, 1.0, 2.0]], Gv).

test(several_outputs_add_up, [timeout(60), true(Gv == [5.0, 7.0])]) :-
   shape(X, [2]),
   A @= 2 * X, B @= 3 * X,
   vjp([A, B], [X], [Abar, Bbar], [G]),
   eval(G, [X-[1.0, 1.0], Abar-[1.0, 2.0], Bbar-[1.0, 1.0]], Gv).
% A name asked for is on a path to the output, else an error that says why not: no output
% depends on it, or every path is blocked, by a realized name, a stop_gradient, or a name
% that is not a float. A derivative never crosses a realized name. The ball of a throw is
% a copy: the names in the error are copies, known by their attributes.
test(a_name_the_output_does_not_read_is_refused, [timeout(60), error(domain_error(depended_on, _))]) :-
   shape(X, [2]), shape(Z, [2]),
   L @= sum(X * X),
   grad(L, [Z], _).
test(a_name_behind_a_realized_name_is_refused, [timeout(60)]) :-
   shape(X, [2]),
   H @= X * 2,
   L @= sum(H * H),
   realize([H], [X-[1.0, 2.0]], [device(pocl)]),
   catch(grad(L, [X], _), error(domain_error(reachable_through(Bs), N), _), true),
   shape(N, [2]), Bs = [B], core:realized(B),
   grad(L, [H], [G]),
   eval(G, [], Gv), Gv == [4.0, 8.0].
test(a_name_behind_a_stop_gradient_is_refused, [timeout(60)]) :-
   shape(X, [2]),
   H @= X * 2,
   stop_gradient(H),
   L @= sum(H * H),
   catch(grad(L, [X], _), error(domain_error(reachable_through(Bs), N), _), true),
   shape(N, [2]), Bs = [B], get_attr(B, stop_gradient, _).
test(a_name_behind_an_int_is_refused, [timeout(60)]) :-
   shape(X, [2]), shape(K, [2]), kind(K, int),
   over([I:2], [K[I] := where(X[I] > 0, 1, 0)]),
   L @= sum(K),
   catch(grad(L, [X], _), error(domain_error(reachable_through(Bs), N), _), true),
   shape(N, [2]), Bs = [B], kind(B, int).
% A float on a path whose partials are all zero, read in a comparison inside an equation,
% has its gradient, zero; the overlay makes the comparison a bool name, and a path through
% it alone is blocked.
test(a_name_read_in_a_comparison_alone_has_a_zero_gradient, [timeout(60), true(Gv == [0.0, 0.0])]) :-
   shape(X, [2]), shape(L, []),
   over([], [L := 0.0]),
   over([I:2], [L := L + where(X[I] > 0, 1.0, 0.0)]),
   grad(L, [X], [G]),
   eval(G, [X-[1.0, -1.0]], Gv).
test(a_name_behind_a_bool_name_is_refused, [timeout(60)]) :-
   shape(X, [2]),
   L @= sum(where(X > 0, 1.0, 0.0)),
   catch(grad(L, [X], _), error(domain_error(reachable_through(Bs), N), _), true),
   shape(N, [2]), Bs = [B], kind(B, bool).
test(forward_mode_refuses_an_unreached_input, [timeout(60), error(domain_error(depended_on, _))]) :-
   shape(X, [2]), shape(Z, [2]),
   Y @= exp(X),
   jvp([Y], [Z], 1, _, _).
test(gradient_in_a_written_name, [timeout(60)]) :-
   shape(X, [2]),
   H @= exp(X),
   L @= sum(H * H),
   grad(L, [H], [G]),
   eval(G, [X-[0.0, 1.0]], Gv),
   E is 2*exp(1.0),
   near(Gv, [2.0, E]).
test(loss_must_be_rank_0, [timeout(10), error(domain_error(rank(0), _))]) :-
   shape(X, [2]),
   Y @= 2 * X,
   grad(Y, [X], _).
% Reverse mode needs the values a box overwrote: a Cholesky factor updated in place is refused.
test(in_place_cholesky_is_not_available, [timeout(60), error(domain_error(available, _))]) :-
   cholesky(A, L, 4),
   vjp([L], [A], _, _).
test(int_name_is_not_differentiated_in, [timeout(10), error(domain_error(kind, _))]) :-
   embedding(_, Idx, _, Y),
   vjp([Y], [Idx], _, _).

% The adjoint of an elementwise chain is a chain of pure names: the gradient of a sum of
% squares of an exponential is one kernel, as its forward is.
test(elementwise_adjoints_fuse, [timeout(60), true(N == 1)]) :-
   shape(X, [64]),
   L @= sum(exp(X) * exp(X)),
   grad(L, [X], [G]),
   kernels(G, [], Ks),
   length(Ks, N).

:- end_tests(grad_reverse).

% jvp_matches(+Outs, +Data, +Ins): the forward mode of Outs along two random directions
% agrees with the differences: dOut[d] = sum over k of dOut/dIn[k] * T[d, k].
jvp_matches(Outs, Data, Ins) :-
   jvp(Outs, Ins, 2, Tangents, OutTs),
   foldl(tangent_data(Data), Ins, Tangents, TData, 1, _),
   append(TData, Data, JData),
   maplist(tangent_matches(Data, JData, Ins, TData), Outs, OutTs).

tangent_data(Data, In, T, T-Vs, Seed, Seed1) :-
   data_of(In, Data, Xs), length(Xs, L), N is 2*L,
   vals(N, Seed, Vs), Seed1 is Seed + 0.37.

tangent_matches(Data, JData, Ins, TData, Out, OutT) :-
   eval(OutT, JData, Got),
   eval(Out, Data, Ys), length(Ys, NY),
   maplist(directional(Out, Data), Ins, TData, Parts),
   N2 is 2*NY, length(Zero, N2), maplist(=(0.0), Zero),
   foldl([P, A0, A]>>maplist([X, Y, Z]>>(Z is X + Y), P, A0, A), Parts, Zero, Want),
   near(Got, Want).

% directional(+Out, +Data, +In, +T-Vs, -D): the two directional derivatives of Out along the
% rows of Vs, concatenated, by central differences column by column.
directional(Out, Data, In, _-Vs, D) :-
   data_of(In, Data, Xs), length(Xs, L), numlist(1, L, Ks),
   maplist(column(Out, Data, In), Ks, Cols),
   length(V0, L), append(V0, V1, Vs),
   maplist(combine(Cols), [V0, V1], Ds),
   append(Ds, D).

combine(Cols, V, D) :-
   Cols = [C0 | _], length(C0, NY), length(Zero, NY), maplist(=(0.0), Zero),
   foldl([C, W, A0, A]>>maplist({W}/[X, Y, Z]>>(Z is Y + W*X), C, A0, A), Cols, V, Zero, D).

% A batch of constant-velocity tracks observed by range and height: the EKF's transition
% and observation of each state, F[b] = dY[b]/dX[b] and H[b] = dZ[b]/dX[b].
cv_batch(X, Y, Z) :-
   shape(X, [3, 4]), shape(Y, [3, 4]), shape(Z, [3, 2]),
   Xs = [X[B, 0], X[B, 1], X[B, 2], X[B, 3]],
   cv_range_model(Xs, [Y0, Y1, Y2, Y3], [Z0, Z1]),
   over([B:3], [Y[B, 0] := Y0, Y[B, 1] := Y1, Y[B, 2] := Y2, Y[B, 3] := Y3,
                Z[B, 0] := Z0, Z[B, 1] := Z1]).

% The Cholesky factor of A, overwritten column by column.
cholesky(A, L, N) :-
   shape(A, [N, N]), shape(L, [N, N]), shape(C, [N]),
   over([I:N, J:N], [L[I, J] := where(J =< I, A[I, J], 0)]),
   over([K:N], [over([I:N], [C[I] := where(I =:= K, sqrt(L[K, K]), where(K < I, L[I, K] / sqrt(L[K, K]), 0))]),
                over([I:N], [L[I, K] := where(K =< I, C[I], L[I, K])]),
                over([I:N, J:N], [L[I, J] := where(K < J, where(J =< I, L[I, J] - C[I] * C[J], L[I, J]), L[I, J])])]).

% A symmetric positive definite matrix of N by N, row-major.
spd_values(N, Vs) :-
   findall(V, ( between(1, N, I), between(1, N, J),
                ( I =:= J -> V is N + 1.0 + 0.1*I ; V is 1.0 / (I + J) ) ), Vs).

% A product folded in place: each step reads the value the one before left.
running_product(X, P) :-
   shape(X, [4]),
   over([], [P := 1.0]),
   over([I:4], [P := P * X[I]]).

:- begin_tests(grad_forward).

% A program that overwrites its values has a dual box: forward mode differentiates it, and
% the program itself is left as it was.
test(cholesky_in_place, [timeout(120)]) :-
   cholesky(A, L, 4), spd_values(4, Av),
   program(L, Before), length(Before, NB),
   jvp_matches([L], [A-Av], [A]),
   program(L, After), length(After, NA),
   NA == NB.
test(product_folded_in_place, [timeout(60)]) :-
   running_product(X, P), vals(4, 0.9, Xv),
   jvp_matches([P], [X-Xv], [X]).
test(reader_of_a_factor, [timeout(120)]) :-
   cholesky(A, L, 3), spd_values(3, Av),
   over([], [S := 0]),
   over([I:3, J:3], [S := S + L[I, J] * L[I, J] * A[J, I]]),
   jvp_matches([S], [A-Av], [A]).

test(matmul, [timeout(60)]) :-
   matmul(A, B, C), vals(12, 1.1, Av), vals(8, 1.3, Bv),
   jvp_matches([C], [A-Av, B-Bv], [A, B]).
test(softmax_through_a_max_fold, [timeout(60)]) :-
   softmax(X, Y), vals(10, 0.9, Xv),
   jvp_matches([Y], [X-Xv], [X]).
test(softmax_of_the_overlay, [timeout(60)]) :-
   api_softmax(X, Y), vals(10, 0.9, Xv),
   jvp_matches([Y], [X-Xv], [X]).
test(recurrence, [timeout(60)]) :-
   recurrence(X, C), vals(12, 0.5, Xv),
   jvp_matches([C], [X-Xv], [X]).
test(layer_norm, [timeout(60)]) :-
   layer_norm(X, G, Y), vals(12, 0.4, Xv), vals(4, 2.1, Gv),
   jvp_matches([Y], [X-Xv, G-Gv], [X, G]).
test(gather, [timeout(60)]) :-
   embedding(E, Idx, W, Y), vals(15, 0.6, Ev), vals(4, 1.7, Wv),
   jvp_matches([Y], [E-Ev, Idx-[1, 4, 1, 0], W-Wv], [E, W]).
test(slabs_and_an_overwritten_write, [timeout(60)]) :-
   slabs(X, Z, Y), vals(3, 0.8, Xv), vals(3, 1.9, Zv),
   jvp_matches([Y], [X-Xv, Z-Zv], [X, Z]).
test(max_splits_a_tie, [timeout(60), true(Tv == [1.5])]) :-
   shape(X, [3]),
   M @= max(X),
   jvp([M], [X], 1, [DX], [DM]),
   eval(DM, [X-[1.0, 3.0, 3.0], DX-[7.0, 1.0, 2.0]], Tv).
test(ekf_jacobians_of_a_batch, [timeout(60)]) :-
   cv_batch(X, Y, Z),
   jvp([Y, Z], [X], 4, [DX], [F, H]),
   over([D:4, B:3, J:4], [DX[D, B, J] := where(J =:= D, 1.0, 0.0)]),
   Xv = [1.0, 2.0, 0.5, -0.5, 3.0, -4.0, 1.0, 1.0, 0.1, 0.2, 0.0, 2.0],
   eval(F, [X-Xv], Fv), eval(H, [X-Xv], Hv),
   % F[d, b, i] = dY[b, i]/dX[b, d]: the identity and 0.5 on the velocities.
   findall(V, ( between(0, 3, D), between(0, 2, _), between(0, 3, I),
                ( I =:= D -> V = 1.0 ; D =:= I + 2 -> V = 0.5 ; V = 0.0 ) ), Fw),
   near(Fv, Fw),
   % H[d, b, :] = (x, y)/r on the range and (0, 1) on the height, along x and y only.
   findall(V, ( between(0, 3, D), between(0, 2, B), Bx is 4*B, By is Bx + 1,
                nth0(Bx, Xv, Px), nth0(By, Xv, Py), R is sqrt(Px*Px + Py*Py),
                ( D =:= 0 -> member(V, [Px/R, 0.0]) ; D =:= 1 -> member(V, [Py/R, 1.0]) ; member(V, [0.0, 0.0]) ) ), Hw0),
   maplist([E, V]>>(V is E), Hw0, Hw),
   near(Hv, Hw).

% jacobian/4 over a batch: J[b, i, j] = dZ[b, i]/dX[b, j].
test(jacobian_of_a_batch, [timeout(60)]) :-
   cv_batch(X, _, Z),
   jacobian(Z, X, J, [batch(1)]),
   shape(J, S), S == [3, 2, 4],
   Xv = [1.0, 2.0, 0.5, -0.5, 3.0, -4.0, 1.0, 1.0, 0.1, 0.2, 0.0, 2.0],
   eval(J, [X-Xv], Jv),
   findall(V, ( between(0, 2, B), Bx is 4*B, By is Bx + 1,
                nth0(Bx, Xv, Px), nth0(By, Xv, Py), R is sqrt(Px*Px + Py*Py),
                member(V0, [Px/R, Py/R, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0]), V is V0 ), Jw),
   near(Jv, Jw).
test(jacobian_of_a_matrix_function, [timeout(60)]) :-
   shape(X, [2, 2]),
   Y @= X @ X,
   jacobian(Y, X, J, []),
   shape(J, S), S == [2, 2, 2, 2],
   Xv = [1.0, 2.0, 3.0, 4.0],
   eval(J, [X-Xv], Jv),
   numlist(1, 4, Ks),
   maplist(column(Y, [X-Xv], X), Ks, Cols),
   % Cols[k][o] = dY[o]/dX[k]; J is row-major in (o, k).
   findall(V, ( between(0, 3, O), member(Col, Cols), nth0(O, Col, V) ), Jw),
   near(Jv, Jw).

:- end_tests(grad_forward).

% A two-layer MLP with a GELU and a squared-error loss.
mlp_loss(X, T, W1, B1, W2, B2, L, S, D, H) :-
   shape(X, [S, D]), shape(T, [S, D]), shape(W1, [D, H]), shape(B1, [H]), shape(W2, [H, D]), shape(B2, [D]),
   over([I:S, J:H], [C1[I, J] := 0]),
   over([I:S, J:H, K:D], [C1[I, J] := C1[I, J] + X[I, K] * W1[K, J]]),
   over([I:S, J:H], [A[I, J] := (C1[I, J] + B1[J]) * (1 / (1 + exp(-1.702 * (C1[I, J] + B1[J]))))]),
   over([I:S, J:D], [C2[I, J] := 0]),
   over([I:S, J:D, K:H], [C2[I, J] := C2[I, J] + A[I, K] * W2[K, J]]),
   over([I:S, J:D], [Y[I, J] := C2[I, J] + B2[J]]),
   over([], [L := 0]),
   over([I:S, J:D], [L := L + (Y[I, J] - T[I, J]) * (Y[I, J] - T[I, J])]).

mlp_data(S, D, H, X, T, W1, B1, W2, B2, Data) :-
   SD is S*D, DH is D*H,
   vals(SD, 0.11, Xv), vals(SD, 0.13, Tv), vals(DH, 0.017, W1v), vals(H, 0.19, B1v), vals(DH, 0.023, W2v), vals(D, 0.29, B2v),
   Data = [X-Xv, T-Tv, W1-W1v, B1-B1v, W2-W2v, B2-B2v].

% A device's float result against the reference's.
near_device(Xs, Ys) :-
   maplist([X, Y]>>(abs(X - Y) < 1.0e-3 * (1 + abs(Y))), Xs, Ys).

:- begin_tests(grad_device).

test(mlp_gradients_agree_with_differences, [timeout(120)]) :-
   mlp_loss(X, T, W1, B1, W2, B2, L, 3, 2, 4),
   mlp_data(3, 2, 4, X, T, W1, B1, W2, B2, Data),
   vjp_matches(L, Data, [W1, B1, W2, B2]).
% The backward of the MLP is as many kernels as one written by hand: with the forward's two
% matmuls, each with its epilogue, the matmul of the hidden adjoint with the GELU's
% derivative as its epilogue, and the matmul of the gradient.
test(mlp_backward_adds_two_kernels, [timeout(60), true(N == 4)]) :-
   mlp_loss(_, _, W1, B1, W2, B2, L, 64, 32, 128),
   grad(L, [W1, B1, W2, B2], [G1 | _]),
   kernels(G1, [], Ks),
   length(Ks, N).
test(mlp_loss_gradients, [timeout(300), forall(test_device(D, _))]) :-
   mlp_loss(X, T, W1, B1, W2, B2, L, 64, 32, 128),
   grad(L, [W1, B1, W2, B2], Grads),
   mlp_data(64, 32, 128, X, T, W1, B1, W2, B2, Data),
   forall(member(G, Grads),
          ( eval(G, Data, Ref), run(G, Data, V, [device(D)]), near_device(V, Ref) )).
% One step of gradient descent is a program like any other: the new weights.
test(sgd_step, [timeout(300), forall(test_device(D, _))]) :-
   mlp_loss(X, T, W1, B1, W2, B2, L, 64, 32, 128),
   grad(L, [W1, B1, W2, B2], [G1 | _]),
   over([K:32, J:128], [W1n[K, J] := W1[K, J] - 0.01 * G1[K, J]]),
   mlp_data(64, 32, 128, X, T, W1, B1, W2, B2, Data),
   eval(W1n, Data, Ref), run(W1n, Data, V, [device(D)]), near_device(V, Ref).
test(ekf_jacobians, [timeout(120), forall(test_device(Dv, _))]) :-
   cv_batch(X, Y, Z),
   jvp([Y, Z], [X], 4, [DX], [F, H]),
   over([D:4, B:3, J:4], [DX[D, B, J] := where(J =:= D, 1.0, 0.0)]),
   vals(12, 0.3, Xv),
   forall(member(Out, [F, H]),
          ( eval(Out, [X-Xv], Ref), run(Out, [X-Xv], V, [device(Dv)]), near_device(V, Ref) )).
% A dual box on a device: the tangent of a Cholesky factor overwritten in place.
test(cholesky_tangent_on_a_device, [timeout(300), forall(test_device(D, _))]) :-
   cholesky(A, L, 8), spd_values(8, Av),
   jvp([L], [A], 3, [DA], [DL]),
   vals(192, 0.7, DAv),
   eval(DL, [A-Av, DA-DAv], Ref), run(DL, [A-Av, DA-DAv], V, [device(D)]),
   near_device(V, Ref).
test(max_gradient_on_a_device, [timeout(120), forall(test_device(D, _))]) :-
   api_softmax(X, Y),
   L @= sum(Y * Y),
   grad(L, [X], [G]),
   vals(10, 0.9, Xv),
   eval(G, [X-Xv], Ref), run(G, [X-Xv], V, [device(D)]), near_device(V, Ref).
test(erf_gradient_on_a_device, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [10]),
   L @= sum(0.5 * X * (1 + erf(X / sqrt(2)))),
   grad(L, [X], [G]),
   vals(10, 0.9, Xv0), maplist([V0, V]>>(V is 3 * V0), Xv0, Xv),
   eval(G, [X-Xv], Ref), run(G, [X-Xv], V, [device(D)]), near_device(V, Ref).

:- end_tests(grad_device).

% The data of a training run: a batch of 5, 4 features, 8 hidden units, 2 outputs.
train_values(Xv, Tv, [W1v, B1v, W2v, B2v]) :-
   vals(20, 0.11, Xv), vals(10, 0.13, Tv),
   vals(32, 0.17, W1v), vals(8, 0.19, B1v), vals(16, 0.23, W2v), vals(2, 0.29, B2v).

weight_shapes([[4, 8], [8], [8, 2], [2]]).

:- begin_tests(grad_train).

% The overlay's derivatives: the gradient of one name, of several by one backward, a
% Jacobian, and a name no derivative flows through.
test(overlay_grad, [timeout(60), true(Gv == [2.0, 4.0, 6.0])]) :-
   shape(X, [3]),
   G @= grad(sum(X * X), X),
   eval(G, [X-[1.0, 2.0, 3.0]], Gv).
test(overlay_grads, [timeout(60), true(Ga-Gb == [3.0, 4.0]-[1.0, 2.0])]) :-
   shape(A, [2]), shape(B, [2]),
   [GA, GB] @= grads(sum(A * B), [A, B]),
   eval(GA, [A-[1.0, 2.0], B-[3.0, 4.0]], Ga),
   eval(GB, [A-[1.0, 2.0], B-[3.0, 4.0]], Gb).
test(overlay_jacobian, [timeout(60), true(Jv == [2.0, 0.0, 0.0, 4.0])]) :-
   shape(X, [2]),
   J @= jacobian(X * X, X),
   eval(J, [X-[1.0, 2.0]], Jv).
test(overlay_stop_gradient, [timeout(60), true(Gv == [3.0, 4.0])]) :-
   shape(X, [2]),
   G @= grad(sum(X * stop_gradient(X + 2)), X),
   eval(G, [X-[1.0, 2.0]], Gv).

% One step of the handle is the step of the reference: the loss, and each weight less the
% rate times its gradient, the gradients those of the same program by eval/3.
test(a_step_is_the_reference_step, [timeout(300), forall(test_device(D, _))]) :-
   B::integer(1, 64),
   step(D, dims(B, 4, 8, 2), 0.1, Step, [X, T], Ws),
   train_values(Xv, Tv, Wvs),
   weight_shapes(Shapes),
   tensor([5, 4], Xv, Xt), tensor([5, 2], Tv, Tt),
   maplist(tensor, Shapes, Wvs, Hosts),
   maplist(on_device(D), Hosts, Devs),
   pairs_keys_values(Weights0, Ws, Devs),
   train(Step, [X-Xt, T-Tt], Weights0, 1, [Loss], Weights),
   pairs_values(Weights, News),
   maplist([N, V]>>run(N, [], V, []), News, Got),
   shape(Xr, [5, 4]), shape(Tr, [5, 2]),
   maplist([S, W]>>shape(W, S), Shapes, Wr),
   mlp(Xr, Wr, Yr),
   Lr @= mean((Yr - Tr) * (Yr - Tr)),
   Gr @= grads(Lr, Wr),
   pairs_keys_values(WData, Wr, Wvs),
   Data = [Xr-Xv, Tr-Tv | WData],
   eval(Lr, Data, [LossRef]),
   near_device([Loss], [LossRef]),
   maplist({Data}/[G, Wv, Want]>>( eval(G, Data, Gv), maplist([W0, G0, W1]>>(W1 is W0 - 0.1*G0), Wv, Gv, Want) ),
           Gr, Wvs, Wants),
   maplist(near_device, Got, Wants).

test(training_lowers_the_loss, [timeout(300), forall(test_device(D, _))]) :-
   B::integer(1, 64),
   step(D, dims(B, 4, 8, 2), 0.1, Step, [X, T], Ws),
   train_values(Xv, Tv, Wvs),
   weight_shapes(Shapes),
   tensor([5, 4], Xv, Xt), tensor([5, 2], Tv, Tt),
   maplist(tensor, Shapes, Wvs, Hosts),
   maplist(on_device(D), Hosts, Devs),
   pairs_keys_values(Weights0, Ws, Devs),
   train(Step, [X-Xt, T-Tt], Weights0, 30, Losses, _),
   Losses = [First | _], last(Losses, Last),
   Last < 0.5 * First,
   Step = step(Exe, _), release(Exe).

:- end_tests(grad_train).

% Rules: a name differentiated by a goal of its own instead of through its boxes.

% doubled(+Y, +Ybar, -Xbars): a backward that is not the derivative, to see the rule taken:
% twice the adjoint of an exponential.
doubled(Y, Ybar, [Xbar]) :-
   shape(Y, [N]), shape(Xbar, [N]),
   over([I:N], [Xbar[I] := 2 * Ybar[I] * Y[I]]).

% tripled(+Y, +ND, +DXs, +DY): a forward that is not the derivative: three times the
% tangent of an exponential.
tripled(Y, ND, [DX], DY) :-
   shape(Y, [N]),
   over([D:ND, I:N], [DY[D, I] := 3 * DX[D, I] * Y[I]]).

:- begin_tests(grad_rules).

test(vjp_rule_replaces_the_boxes, [timeout(60)]) :-
   shape(X, [2]),
   Y @= exp(X),
   derivative(Y, [X], [vjp(doubled(Y))]),
   G @= grad(sum(Y), X),
   eval(G, [X-[0.0, 1.0]], Gv),
   E is 2*exp(1.0),
   near(Gv, [2.0, E]).
test(jvp_rule_replaces_the_boxes, [timeout(60)]) :-
   shape(X, [2]),
   Y @= exp(X),
   derivative(Y, [X], [jvp(tripled(Y))]),
   jvp([Y], [X], 1, [DX], [DY]),
   eval(DY, [X-[0.0, 1.0], DX-[1.0, 1.0]], Tv),
   E is 3*exp(1.0),
   near(Tv, [3.0, E]).
% The mode without a rule goes through the boxes.
test(mode_without_a_rule_differentiates_the_boxes, [timeout(60)]) :-
   shape(X, [2]),
   Y @= exp(X),
   derivative(Y, [X], [vjp(doubled(Y))]),
   jvp([Y], [X], 1, [DX], [DY]),
   eval(DY, [X-[0.0, 1.0], DX-[1.0, 1.0]], Tv),
   E is exp(1.0),
   near(Tv, [1.0, E]).
% A name computed for the ruled one alone has no adjoint: the rule is the only path.
test(names_under_a_rule_are_not_active, [timeout(60)]) :-
   shape(X, [2]),
   H @= X * X,
   Y @= exp(H),
   derivative(Y, [X], [vjp(doubled(Y))]),
   G @= grad(sum(Y), X),
   eval(G, [X-[0.0, 1.0]], Gv),
   E is 2*exp(1.0),
   near(Gv, [2.0, E]).
test(rule_survives_a_copy, [timeout(60)]) :-
   shape(X, [2]),
   Y @= exp(X),
   derivative(Y, [X], [vjp(doubled(Y))]),
   copy_term(X-Y, X1-Y1),
   G @= grad(sum(Y1), X1),
   eval(G, [X1-[0.0, 1.0]], Gv),
   E is 2*exp(1.0),
   near(Gv, [2.0, E]).
test(rule_of_an_input_is_refused, [timeout(10), error(type_error(written_name, _))]) :-
   shape(X, [2]),
   derivative(X, [], [vjp(true)]).

% The backward of a Cholesky factorization overwritten in place, by its rule: against the
% differences, and through the log-determinant, whose gradient is the inverse's diagonal
% and twice its lower triangle.
test(cholesky_backward_by_its_rule, [timeout(120)]) :-
   differentiable_cholesky(A, L, 4), spd_values(4, Av),
   vjp_matches(L, [A-Av], [A]).
test(log_determinant_through_cholesky, [timeout(300), forall(test_device(D, _))]) :-
   differentiable_cholesky(A, L, 8), spd_values(8, Av),
   over([], [S := 0]),
   over([I:8], [S := S + 2.0 * log(L[I, I])]),
   grad(S, [A], [G]),
   eval(G, [A-Av], Ref),
   fd_vjp(S, [A-Av], A, [1.0], Fd),
   near(Ref, Fd),
   run(G, [A-Av], V, [device(D)]),
   near_device(V, Ref).

:- end_tests(grad_rules).

% The types of tangents. A chain of the float format F on the device D: H elementwise, Y a
% fold, both of X, and Z of W alone.
typed_chain(F, D, X, W, H, Y, Z) :-
   shape(X, [3]), type(X, F), device(X, D),
   shape(W, [3]), type(W, F), device(W, D),
   over([I:3], [H[I] := X[I] * W[I]]),
   over([], [Y := 0.0]),
   over([I:3], [Y := Y + exp(H[I])]),
   over([I:3], [Z[I] := W[I] * 2]).

% formats(+Outs, +Names, -Formats): the formats of Names as the program of Outs resolves
% them, undone.
formats(Outs, Names, Formats) :-
   findall(Fs, ( compile:programs(Outs, Boxes), compile:label_program(Outs, Boxes), maplist(type, Names, Fs) ),
           [Formats]).

a_device(D) :-
   once(test_device(D, _)).

float_format(float16).
float_format(float32).
float_format(float64).

linear_tangent(D, F, Vs) :-
   shape(X, [1]), type(X, F), device(X, D),
   over([I:1], [Y[I] := X[I] * 3]),
   jvp([Y], [X], 1, [DX], [DY]),
   run(DY, [DX-[0.1]], Vs, []).

% scaled(+Y, +ND, +DXs, +DY): the forward of Y := X * K by its rule; the tangent of K, a
% name that is not active, is zeroes.
scaled(Y, ND, [DX, DK], DY) :-
   shape(Y, [N]),
   over([D:ND, I:N], [DY[D, I] := 2 * DX[D, I] + DK[D]]).

:- begin_tests(grad_types).

% The tangent of the input, those written by an equation and by a fold, and the zeroes of a
% name that does not depend on the input.
test(tangents_are_of_the_type_of_the_primal, [timeout(60), forall(float_format(F)), true(Fs == [F, F, F, F])]) :-
   a_device(D),
   typed_chain(F, D, X, _, H, Y, Z),
   jvp([H, Y, Z], [X], 2, [DX], [DH, DY, DZ]),
   formats([DH, DY, DZ], [DX, DH, DY, DZ], Fs).
% The tangent program of a linear one mentions neither the input nor the output.
test(tangent_of_a_linear_program, [timeout(60), forall(float_format(F)), true(Fs == [F, F])]) :-
   a_device(D),
   shape(X, [3]), type(X, F), device(X, D),
   over([I:3], [Y[I] := X[I] * 3]),
   jvp([Y], [X], 1, [DX], [DY]),
   formats([DY], [DX, DY], Fs).
test(tangent_given_for_a_written_name, [timeout(60), forall(float_format(F)), true(Fs == [F, F])]) :-
   a_device(D),
   typed_chain(F, D, _, _, H, Y, _),
   jvp([Y], [H], 1, [DH], [DY]),
   formats([DY], [DH, DY], Fs).
test(tangents_of_two_types, [timeout(60), true(Fs == [float16, float32, float32])]) :-
   shape(X, [3]), type(X, float16), shape(W, [3]), type(W, float32),
   over([I:3], [H[I] := X[I] * W[I]]),
   jvp([H], [X, W], 1, [DX, DW], [DH]),
   formats([DH], [DX, DW, DH], Fs).
test(tangent_of_an_untyped_input_is_its_default, [timeout(60), true(Fs == [float32, float32])]) :-
   shape(X, [3]),
   over([I:3], [H[I] := X[I] * X[I]]),
   jvp([H], [X], 1, [DX], [DH]),
   formats([DH], [DX, DH], Fs).
test(tangent_makes_its_input_a_float, [timeout(60), true(K == float)]) :-
   shape(X, [3]),
   over([I:3], [H[I] := X[I] * X[I]]),
   jvp([H], [X], 1, _, _),
   kind(X, K).
% An int has no tangent of its type: the zeroes of one are floats of the default type.
test(zero_tangent_of_an_int, [timeout(60), true(Fs == [float64, float32])]) :-
   a_device(D),
   shape(X, [3]), type(X, float64), device(X, D),
   shape(N, [3]), type(N, int16), device(N, D),
   over([I:3], [H[I] := X[I] * 2]),
   over([I:3], [C[I] := N[I] + 1]),
   jvp([H, C], [X], 1, _, [DH, DC]),
   formats([DH, DC], [DH, DC], Fs).
test(tangent_by_a_rule, [timeout(60), forall(float_format(F)), true(Fs == [F, F])]) :-
   a_device(D),
   shape(X, [3]), type(X, F), device(X, D),
   shape(K, []), type(K, F), device(K, D),
   over([I:3], [Y[I] := X[I] * K]),
   derivative(Y, [X, K], [jvp(scaled(Y))]),
   jvp([Y], [X], 1, [DX], [DY]),
   formats([DY], [DX, DY], Fs).
test(jacobian_is_of_the_type_of_the_primal, [timeout(60), forall(float_format(F)), true(Fs == [F, F])]) :-
   a_device(D),
   typed_chain(F, D, X, _, H, Y, _),
   jacobian(H, X, J, []),
   jacobian(Y, H, Jh, []),
   formats([J, Jh], [J, Jh], Fs).

% On a device: a float64 tangent keeps what a float32 one would round, and overflow.
test(float64_tangent_on_a_device, [timeout(120), forall(test_device(D, _)), true(Vs == [0.6000000000000001, 4.0e300])]) :-
   shape(X, [2]), type(X, float64), device(X, D),
   over([I:2], [Y[I] := X[I] * X[I]]),
   jvp([Y], [X], 1, [DX], [DY]),
   run(DY, [X-[3.0, 2.0], DX-[0.1, 1.0e300]], Vs, []).
test(float16_tangent_on_a_device, [timeout(120), forall(test_device(D, _)), true(Vs == [0.599609375])]) :-
   shape(X, [1]), type(X, float16), device(X, D),
   over([I:1], [Y[I] := X[I] * X[I]]),
   jvp([Y], [X], 1, [DX], [DY]),
   run(DY, [X-[3.0], DX-[0.1]], Vs, []).
% One tangent program, which does not mention its input, for inputs of two types: a handle
% each.
test(a_handle_per_type_of_the_input, [timeout(120), forall(test_device(D, _)), true(Vs == [[0.2998046875], [0.30000000000000004]])]) :-
   maplist(linear_tangent(D), [float16, float64], Vs).

:- end_tests(grad_types).

% The digits are not in the repository: examples/mnist.py writes them, or mnist/1 downloads
% them once; the unit runs where they are, and never downloads them.
mnist_file :-
   example_file_present('mnist.safetensors').

:- begin_tests(grad_mnist, [condition(mnist_file)]).

% Two hundred steps of gradient descent on the digits: the classifier is right four times
% out of five at least on the test set, from one in ten.
test(two_hundred_steps, [timeout(300), forall(test_device(D, _))]) :-
   with_output_to(string(Out), mnist([device(D), steps(200), report(200)])),
   split_string(Out, "\n", "", Lines),
   once(( member(Line, Lines), sub_string(Line, 0, _, _, "epoch 1: accuracy ") )),
   split_string(Line, " ,", "", [_, _, _, Acc | _]),
   number_string(A, Acc),
   A > 0.8.

:- end_tests(grad_mnist).
