:- module(types_tests, []).

:- use_module(library(array)).
:- use_module(library(array/api)).
:- use_module(library(array/buffer)).
:- use_module(library(clpBNR)).
:- use_module(library(array/compile), [kernels/3, device_options/2, eval/3]).
:- use_module(test_devices, [test_device/2]).

% The formats of names on the devices: a name stored narrow is computed in the format of its
% kind, a box widening it on the way in and one narrowing it on the way out, see
% compile:widened/4. Each program runs on every device and against the reference, exact for
% the ints, to the precision of the format for the floats.

% host_name(+Format, +Shape, +Values, -Name): a name on host realized with Values in Format.
host_name(Format, Shape, Values, Name) :-
   foldl([E, P0, P]>>(P is P0*E), Shape, 1, N),
   compound_name_arguments(Data, data, Values),
   buffer_from_data(Buffer, Format, N, Data),
   shape(Name, Shape),
   type(Name, Format),
   device(Name, host),
   value(Name, Buffer).

% elements(+Name, -Format, -Values): the format and the elements of a realized name, on host
% or read back from its device.
name_elements(Name, Format, Values) :-
   type(Name, Format),
   device(Name, D),
   on_host(D, Name, Host),
   value(Host, Buffer),
   shape(Host, Shape),
   foldl([E, P0, P]>>(P is P0*E), Shape, 1, N),
   buffer_to_data(Buffer, Format, N, Data),
   compound_name_arguments(Data, _, Values).

on_host(host, Name, Host) => Host = Name.
on_host(_, Name, Host) =>
   copy(Name, Host, host),
   realize([Host], [], []).

% placed(+D, +Name): Name lives on the device D.
placed(D, Name) :-
   device(Name, D).

% on_device(+D, +Name, -Dev): Dev holds the elements of the host name Name on the device D.
on_device(D, Name, Dev) :-
   copy(Name, Dev, D).

near(Tolerance, A, B) :-
   abs(A - B) =< Tolerance * max(1, abs(B)).

% scatter(+D, +Format, +Op, +Ws, -Atomics, -Vs, -Expected): the 16 bins Vs of the fold by Op,
% from 0, a product from 1, of the 4096 sources Ws of Format, the source K into the bin
% 7*K mod 16, on the device D; Atomics the atomic names of its plan there, and Expected the
% bins folded here.
scatter(D, Format, Op, Ws, Atomics, Vs, Expected) :-
   numlist(1, 4096, Ks), maplist(bin, Ks, Is),
   start(Op, V0),
   host_name(int32, [4096], Is, Idx0), host_name(Format, [4096], Ws, W0),
   on_device(D, Idx0, Idx), on_device(D, W0, W),
   shape(H, [16]), type(H, Format),
   over([I:16], [H[I] := V0]),
   V =.. [Op, H[Idx[K]], W[K]],
   over([K:4096], [H[Idx[K]] := V]),
   test_device(D, Device), device_options(Device, Options),
   kernels(H, Options, Plan),
   findall(Op1, ( member(Kernel, Plan), is_dict(Kernel), get_dict(atomics, Kernel, As), member(_-Op1, As) ), Atomics),
   realize([H], [], []),
   name_elements(H, Format, Vs),
   numlist(0, 15, Bins),
   pairs_keys_values(Pairs, Is, Ws),
   maplist(folded_bin(Op, V0, Pairs), Bins, Expected).

bin(K, I) :- I is 7*K mod 16.

start(*, V0) => V0 = 1.
start(_, V0) => V0 = 0.

folded_bin(Op, V0, Pairs, Bin, V) :-
   foldl(fold_pair(Op, Bin), Pairs, V0, V).

fold_pair(Op, Bin, Bin-W, V0, V) => Goal =.. [Op, V0, W], V is Goal.
fold_pair(_, _, _, V0, V) => V = V0.

% sources(+Expr, -Ws): the 4096 sources, each the value of Expr at K, its number from 1.
sources(K-Expr, Ws) :-
   numlist(1, 4096, Ks),
   maplist(source_at(K-Expr), Ks, Ws).

source_at(Template, K, W) :-
   copy_term(Template, K-Expr),
   W is Expr.

% filled(+N, +V, -L): L is N times V.
filled(N, V, L) :-
   length(L, N),
   maplist(=(V), L).

% product(+D, -A, -B, -C): C is the product on the device D of the inputs A and B, float32
% matrices of 256 by 256: large enough for its kernel to stage its reads and take vectors.
product(D, A, B, C) :-
   N = 256,
   matrix(D, float32, A), matrix(D, float32, B), matrix(D, _, C),
   over([I:N, J:N], [C[I, J] := 0]),
   over([I:N, J:N, K:N], [C[I, J] := C[I, J] + A[I, K] * B[K, J]]).

% kernel_count(+Out, +Options, -K): K kernels in the plan of Out, under the device's Options.
kernel_count(Out, Options, K) :-
   kernels(Out, Options, Plan),
   include(is_dict, Plan, Kernels),
   length(Kernels, K).

% matrix(+D, ?Format, -X): X is a name of 256 by 256 on the device D, of Format when given.
matrix(D, Format, X) :-
   shape(X, [256, 256]),
   device(X, D),
   typed(Format, X).

typed(Format, _), var(Format) => true.
typed(Format, X) => type(X, Format).

% matrix_run(+D, +Out, +Data, -Values): the distinct elements of the matrix Out run on D from
% Data, Name-Value pairs, each matrix filled with its value.
matrix_run(D, Out, Data0, Values) :-
   maplist(matrix_data, Data0, Data),
   run(Out, Data, Vs, [device(D)]),
   sort(Vs, Values).

matrix_data(Name-V, Name-Vs) :-
   filled(65536, V, Vs).

:- begin_tests(types).

test(uint8_times_literal_is_uint8, [timeout(120), forall(test_device(D, _)), true(F-Vs == uint8-[10, 200, 254])]) :-
   % a literal takes the type of what it is next to; the values are to fit, a contract
   host_name(uint8, [3], [5, 100, 127], X),
   on_device(D, X, Xd),
   over([I:3], [Y[I] := Xd[I] * 2]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(uint8_cast_wide_is_computed_wide, [timeout(120), forall(test_device(D, _)), true(F-Vs == int32-[10, 510, 256])]) :-
   host_name(uint8, [3], [5, 255, 128], X),
   on_device(D, X, Xd),
   over([I:3], [Y[I] := cast(Xd[I], int32) * 2]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(uint8_stays_uint8, [timeout(120), forall(test_device(D, _)), true(F-Vs == uint8-[6, 255, 129])]) :-
   % a uint8 and a literal are a uint8: stored as bytes, the device's too
   host_name(uint8, [3], [5, 254, 128], X),
   on_device(D, X, Xd),
   over([I:3], [Y[I] := Xd[I] + 1]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(int8_is_signed, [timeout(120), forall(test_device(D, _)), true(F-Vs == int8-[-128, 127, -1])]) :-
   host_name(int8, [3], [-128, 127, -1], X),
   on_device(D, X, Xd),
   over([I:3], [Y[I] := Xd[I]]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(int16_and_uint16, [timeout(120), forall(test_device(D, _)), true(F-Vs == int32-[32767, 32767, 1])]) :-
   % an int16 and a uint16 are an int32: 17 bits and a sign
   host_name(int16, [3], [-32768, 32767, 0], X),
   host_name(uint16, [3], [65535, 0, 1], U),
   on_device(D, X, Xd), on_device(D, U, Ud),
   over([I:3], [Y[I] := Xd[I] + Ud[I]]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(float16_in_float16_out, [timeout(120), forall(test_device(D, _)), true(F == float16)]) :-
   host_name(float16, [4], [0.5, -2.0, 1024.0, 0.1], X),
   on_device(D, X, Xd),
   over([I:4], [Y[I] := Xd[I] * 0.5 + 1]),
   realize([Y], [], []),
   name_elements(Y, F, Vs),
   maplist(near(1.0e-3), Vs, [1.25, 0.0, 513.0, 1.05]).

test(float16_rounds_where_stored, [timeout(120), forall(test_device(D, _)), true(Vs == [0.0999755859375])]) :-
   % 0.1 is not a float16: the name holds the nearest one, whatever computed it
   host_name(float32, [1], [0.1], X),
   on_device(D, X, Xd),
   over([I:1], [Y[I] := cast(Xd[I], float16)]),
   realize([Y], [], []),
   name_elements(Y, float16, Vs).

test(float16_overflows_to_infinity, [timeout(120), forall(test_device(D, _)), true(Infs == [1, -1])]) :-
   host_name(float32, [2], [1.0e6, -1.0e6], X),
   on_device(D, X, Xd),
   over([I:2], [Y[I] := cast(Xd[I], float16)]),
   realize([Y], [], []),
   name_elements(Y, float16, Vs),
   maplist([V, S]>>( V =:= inf -> S = 1 ; V =:= -inf -> S = -1 ; S = 0 ), Vs, Infs).

test(coded_float_in_and_out, [timeout(120), forall(( test_device(D, _), member(Format, [bfloat16, float8_e4m3]) )),
                             true(F-Vs == Format-[1.25, 0.0, 9.0, 3.0])]) :-
   % a bfloat16 and a float8_e4m3 are stored as their bits and computed as floats
   host_name(Format, [4], [0.5, -2.0, 16.0, 4.0], X),
   on_device(D, X, Xd),
   over([I:4], [Y[I] := Xd[I] * 0.5 + 1]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(bfloat16_rounds_where_stored, [timeout(120), forall(test_device(D, _)),
                                   true(Vs == [0.10009765625, 1.0, 1.0078125, 1.015625, -3.296875])]) :-
   % to the nearest, a tie to the even one, as torch.bfloat16 does: 1 + 2^-8 is 1
   V1 is 1 + 2** -8, V2 is 1 + 2** -8 + 2** -20, V3 is 1 + 3 * 2** -8,
   host_name(float32, [5], [0.1, V1, V2, V3, -3.3], X),
   on_device(D, X, Xd),
   over([I:5], [Y[I] := cast(Xd[I], bfloat16)]),
   realize([Y], [], []),
   name_elements(Y, bfloat16, Vs).

test(bfloat16_overflows_to_infinity, [timeout(120), forall(test_device(D, _)), true(Vs == [3.3895313892515355e38, Inf, NInf])]) :-
   Inf is inf, NInf is -inf,
   host_name(float32, [3], [3.39e38, 3.4e38, -3.4e38], X),
   on_device(D, X, Xd),
   over([I:3], [Y[I] := cast(Xd[I], bfloat16)]),
   realize([Y], [], []),
   name_elements(Y, bfloat16, Vs).

test(float8_e4m3_rounds_where_stored, [timeout(120), forall(test_device(D, _)),
                                      true(Vs == [0.1015625, 1.0, 1.125, 1.25, -3.25, 0.001953125, 0.0, 448.0])]) :-
   % to the nearest, a tie to the even one, as torch.float8_e4m3fn does; 2^-9 is the least
   V is 2.0** -10,
   host_name(float32, [8], [0.1, 1.0625, 1.0626, 1.1875, -3.3, 0.002, V, 464.0], X),
   on_device(D, X, Xd),
   over([I:8], [Y[I] := cast(Xd[I], float8_e4m3)]),
   realize([Y], [], []),
   name_elements(Y, float8_e4m3, Vs).

test(float8_e4m3_overflows_to_not_a_number, [timeout(120), forall(test_device(D, _)), true(NaNs == [0, 1, 1, 1])]) :-
   % it has no infinity: past 448 and half a step, a value is not a number
   host_name(float32, [4], [463.0, 465.0, -1000.0, 1.0e30], X),
   on_device(D, X, Xd),
   over([I:4], [Y[I] := cast(Xd[I], float8_e4m3)]),
   realize([Y], [], []),
   name_elements(Y, float8_e4m3, Vs),
   maplist([V, S]>>( V =\= V -> S = 1 ; S = 0 ), Vs, NaNs).

test(coded_float_and_float16, [timeout(120), forall(test_device(D, _)), true(F-Vs == float32-[1.5, 2.25])]) :-
   % a bfloat16 and a float16 have no order: their sum is a float32
   host_name(bfloat16, [2], [1.0, 2.0], X),
   host_name(float16, [2], [0.5, 0.25], H),
   on_device(D, X, Xd), on_device(D, H, Hd),
   over([I:2], [Y[I] := Xd[I] + Hd[I]]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(float16_and_uint8, [timeout(120), forall(test_device(D, _)), true(F == float16)]) :-
   % a float16 holds a uint8 exactly: the image of a page by float16 weights is a float16
   host_name(float16, [3], [0.5, 0.25, 2.0], W),
   host_name(uint8, [3], [255, 4, 100], X),
   on_device(D, W, Wd), on_device(D, X, Xd),
   over([I:3], [Y[I] := Wd[I] * Xd[I]]),
   realize([Y], [], []),
   name_elements(Y, F, Vs),
   Vs == [127.5, 1.0, 200.0].

test(uint8_over_literal_is_float32, [timeout(120), forall(test_device(D, _)), true(F == float32)]) :-
   host_name(uint8, [3], [255, 51, 0], X),
   on_device(D, X, Xd),
   over([I:3], [Y[I] := Xd[I] / 255.0]),
   realize([Y], [], []),
   name_elements(Y, F, Vs),
   maplist(near(1.0e-6), Vs, [1.0, 0.2, 0.0]).

test(comparison_is_stored_as_bool, [timeout(120), forall(test_device(D, _)), true(F-Vs == bool-[1, 0, 1])]) :-
   host_name(float32, [3], [-1.0, 2.0, -0.5], X),
   on_device(D, X, Xd),
   over([I:3], [Y[I] := Xd[I] < 0]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(bool_input, [timeout(120), forall(test_device(D, _)), true(F-Vs == float32-[1.5, 0.0, 1.5])]) :-
   host_name(bool, [3], [1, 0, 1], M),
   on_device(D, M, Md),
   over([I:3], [Y[I] := Md[I] * 1.5]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(count_of_bools, [timeout(120), forall(test_device(D, _)), true(F-Vs == int32-[2])]) :-
   host_name(bool, [3], [1, 0, 1], M),
   on_device(D, M, Md),
   over([], [C := 0]),
   over([I:3], [C := C + Md[I]]),
   realize([C], [], []),
   name_elements(C, F, Vs).

test(cast_to_uint8_saturates, [timeout(120), forall(test_device(D, _)), true(Vs == [0, 255, 3, 0, 255])]) :-
   % a float is truncated towards zero, then held to 0..255
   host_name(float32, [5], [-7.5, 300.2, 3.9, -0.5, 1.0e9], X),
   on_device(D, X, Xd),
   over([I:5], [Y[I] := cast(Xd[I], uint8)]),
   realize([Y], [], []),
   name_elements(Y, uint8, Vs).

test(cast_int_to_int8_saturates, [timeout(120), forall(test_device(D, _)), true(Vs == [-128, 127, 5])]) :-
   host_name(int32, [3], [-1000, 1000, 5], X),
   on_device(D, X, Xd),
   over([I:3], [Y[I] := cast(Xd[I], int8)]),
   realize([Y], [], []),
   name_elements(Y, int8, Vs).

test(cast_to_bool, [timeout(120), forall(test_device(D, _)), true(Vs == [1, 0, 1])]) :-
   host_name(float32, [3], [0.25, 0.0, -3.0], X),
   on_device(D, X, Xd),
   over([I:3], [Y[I] := cast(Xd[I], bool)]),
   realize([Y], [], []),
   name_elements(Y, bool, Vs).

test(cast_matches_the_reference, [timeout(120), forall(test_device(D, _)), true(Vs == Expected)]) :-
   shape(X, [5]), device(X, D),
   over([I:5], [Y[I] := cast(X[I] * 100, int16)]),
   Data = [X-[-400.0, 1.5, 327.67, 400.0, -0.004]],
   eval(Y, Data, Expected),
   run(Y, Data, Vs, []).

test(declared_output_is_widened, [timeout(120), forall(test_device(D, _)), true(F-Vs == float32-[5.0, 255.0])]) :-
   host_name(uint8, [2], [5, 255], X),
   on_device(D, X, Xd),
   type(Y, float32),
   over([I:2], [Y[I] := Xd[I]]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(int8_accumulator_stays_int8, [timeout(120), forall(test_device(D, _)), true(F-Vs == int8-[6])]) :-
   host_name(int8, [3], [1, 2, 3], X),
   on_device(D, X, Xd),
   over([], [S := 0]),
   over([I:3], [S := S + Xd[I]]),
   realize([S], [], []),
   name_elements(S, F, Vs).

test(sum_of_int8_is_int32, [timeout(120), forall(test_device(D, _)), true(F-Vs == int32-[381])]) :-
   % the sum of the api outgrows its ints: an int32
   host_name(int8, [3], [127, 127, 127], X),
   on_device(D, X, Xd),
   S @= sum(Xd),
   realize([S], [], []),
   name_elements(S, F, Vs).

test(sum_preferred, [timeout(120), forall(test_device(D, _)), true(F-Vs == int8-[6])]) :-
   host_name(int8, [3], [1, 2, 3], X),
   on_device(D, X, Xd),
   S @= sum(Xd, [preferred(int8)]),
   realize([S], [], []),
   name_elements(S, F, Vs).

test(sum_of_float16_stays, [timeout(120), forall(test_device(D, _)), true(F-Vs == float16-[3.5])]) :-
   host_name(float16, [3], [1.0, 2.0, 0.5], X),
   on_device(D, X, Xd),
   S @= sum(Xd),
   realize([S], [], []),
   name_elements(S, F, Vs).

test(mean_of_ints_is_float32, [timeout(120), forall(test_device(D, _)), true(F-Vs == float32-[2.5])]) :-
   host_name(int32, [4], [1, 2, 3, 4], X),
   on_device(D, X, Xd),
   M @= mean(Xd),
   realize([M], [], []),
   name_elements(M, F, Vs).

test(matmul_of_uint8_is_int32, [timeout(120), forall(test_device(D, _)), true(F-Vs == int32-[130050])]) :-
   host_name(uint8, [1, 2], [255, 255], A),
   host_name(uint8, [2, 1], [255, 255], B),
   on_device(D, A, Ad), on_device(D, B, Bd),
   C @= Ad @ Bd,
   realize([C], [], []),
   name_elements(C, F, Vs).

test(api_cast, [timeout(120), forall(test_device(D, _)), true(F-Vs == uint8-[0, 255, 7])]) :-
   host_name(float32, [3], [-3.0, 999.0, 7.9], X),
   on_device(D, X, Xd),
   Y @= astype(Xd, uint8),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(handle_argument_of_another_format, [timeout(120), forall(test_device(D, _)), error(domain_error(type(uint8), _))]) :-
   % a handle is of the formats of its slots: an int32 is no argument of a uint8 slot
   shape(X, [3]), type(X, uint8), device(X, D),
   over([I:3], [Y[I] := X[I] + 1]),
   compile(Y, [], Exe),
   host_name(int32, [3], [1, 2, 3], A),
   on_device(D, A, Ad),
   realize([Ad], [], []),
   run(Exe, [Ad], _).

test(handle_of_uint8, [timeout(120), forall(test_device(D, _)), true(Vs == [2, 3, 4])]) :-
   shape(X, [3]), type(X, uint8), device(X, D),
   over([I:3], [Y[I] := X[I] + 1]),
   compile(Y, [], Exe),
   host_name(uint8, [3], [1, 2, 3], A),
   on_device(D, A, Ad),
   realize([Ad], [], []),
   run(Exe, [Ad], R),
   name_elements(R, uint8, Vs).

test(data_of_a_declared_input, [timeout(120), forall(test_device(D, _)), true(Vs == [2.0, 4.0])]) :-
   % the data of a run is uploaded in the format its input declares
   shape(X, [2]), type(X, float16), device(X, D),
   over([I:2], [Y[I] := X[I] * 2]),
   run(Y, [X-[1.0, 2.0]], Vs, []).

test(in_place_float16, [timeout(120), forall(test_device(D, _)), true(F == float16)]) :-
   % a name run in place is of one format: its argument's and its result's
   type(S, float16), shape(S, [2]), device(S, D),
   shape(G, [2]), type(G, float16), device(G, D),
   over([I:2], [S[I] := S[I] - 0.5 * G[I]]),
   host_name(float16, [2], [1.0, 2.0], S0),
   host_name(float16, [2], [2.0, 2.0], G0),
   on_device(D, S0, Sd), on_device(D, G0, Gd),
   realize([Sd, Gd], [], []),
   run(S, [S-Sd, G-Gd], R, [result(name)]),
   name_elements(R, F, Vs),
   Vs == [0.0, 1.0].

test(data_of_a_coded_input, [timeout(120), forall(( test_device(D, _), member(Format, [bfloat16, float8_e4m3]) )),
                            true(Vs == [2.0, 4.0])]) :-
   shape(X, [2]), type(X, Format), device(X, D),
   over([I:2], [Y[I] := X[I] * 2]),
   run(Y, [X-[1.0, 2.0]], Vs, []).

test(in_place_coded_float, [timeout(120), forall(( test_device(D, _), member(Format, [bfloat16, float8_e4m3]) )),
                           true(F-Vs == Format-[0.0, 1.0])]) :-
   type(S, Format), shape(S, [2]), device(S, D),
   shape(G, [2]), type(G, Format), device(G, D),
   over([I:2], [S[I] := S[I] - 0.5 * G[I]]),
   host_name(Format, [2], [1.0, 2.0], S0),
   host_name(Format, [2], [2.0, 2.0], G0),
   on_device(D, S0, Sd), on_device(D, G0, Gd),
   realize([Sd, Gd], [], []),
   run(S, [S-Sd, G-Gd], R, [result(name)]),
   name_elements(R, F, Vs).

test(overflow_is_checked_under_the_flag, [timeout(120), forall(test_device(D, _)),
                                         setup(( flush_handles, set_prolog_flag(array_check_fit, true) )),
                                         cleanup(( set_prolog_flag(array_check_fit, false), flush_handles )),
                                         error(domain_error(format(uint8), 10-510))]) :-
   % 255 * 2 is no uint8: the contract of the type is broken, which the flag shows
   host_name(uint8, [2], [5, 255], X),
   on_device(D, X, Xd),
   over([I:2], [Y[I] := Xd[I] * 2]),
   realize([Y], [], []).

test(fit_passes_under_the_flag, [timeout(120), forall(test_device(D, _)),
                                setup(( flush_handles, set_prolog_flag(array_check_fit, true) )),
                                cleanup(( set_prolog_flag(array_check_fit, false), flush_handles )),
                                true(Vs == [10, 200])]) :-
   host_name(uint8, [2], [5, 100], X),
   on_device(D, X, Xd),
   over([I:2], [Y[I] := Xd[I] * 2]),
   realize([Y], [], []),
   name_elements(Y, uint8, Vs).

test(gradient_of_float16_is_float16, [timeout(120), forall(test_device(D, _)), true(F-Vs == float16-[0.5, 2.0, 4.0])]) :-
   host_name(float16, [3], [0.5, 2.0, 4.0], X),
   host_name(float16, [3], [1.0, 1.0, 1.0], W),
   on_device(D, X, Xd), on_device(D, W, Wd),
   L @= sum(Wd * Xd),
   G @= grad(L, Wd),
   realize([G], [], []),
   name_elements(G, F, Vs).

test(int32_into_float_is_a_float64, [timeout(120), forall(test_device(D, _)), true(F-Vs == float64-[0.5, 1073741823.5])]) :-
   % the float of an int32 holds it exactly: a float64, computed as a double
   host_name(int32, [2], [1, 2147483647], X),
   on_device(D, X, Xd),
   over([I:2], [Y[I] := Xd[I] * 0.5]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(float64_in_float64_out, [timeout(120), forall(test_device(D, _)), true(F-Vs == float64-[0.30000000000000004, 1.0e300])]) :-
   host_name(float64, [2], [0.1, 5.0e299], X),
   on_device(D, X, Xd),
   over([I:2], [Y[I] := Xd[I] * 2 + 0.1 * (1 - I)]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(float64_and_float32, [timeout(120), forall(test_device(D, _)), true(F == float64)]) :-
   host_name(float64, [2], [0.1, 0.2], X),
   host_name(float32, [2], [1.0, 2.0], W),
   on_device(D, X, Xd), on_device(D, W, Wd),
   over([I:2], [Y[I] := Xd[I] * Wd[I]]),
   realize([Y], [], []),
   name_elements(Y, F, Vs),
   Vs == [0.1, 0.4].

test(sum_of_float64, [timeout(120), forall(test_device(D, _)), true(F-Vs == float64-[1000000000000000.5])]) :-
   % exact in a double in whatever order it is summed, and far beyond a float32
   host_name(float64, [3], [1.0e15, 0.25, 0.25], X),
   on_device(D, X, Xd),
   S @= sum(Xd),
   realize([S], [], []),
   name_elements(S, F, Vs).

test(int64_arithmetic, [timeout(120), forall(test_device(D, _)), true(F-Vs == int64-[9000000000, -4611686018427387904])]) :-
   host_name(int64, [2], [4500000000, -2305843009213693952], X),
   on_device(D, X, Xd),
   over([I:2], [Y[I] := Xd[I] * 2]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(int64_max_fold, [timeout(120), forall(test_device(D, _)), true(F-Vs == int64-[9000000000])]) :-
   host_name(int64, [3], [5, 9000000000, -9000000000], X),
   on_device(D, X, Xd),
   M @= max(Xd),
   realize([M], [], []),
   name_elements(M, F, Vs).

test(uint32_is_computed_as_a_long, [timeout(120), forall(test_device(D, _)), true(F-Vs == uint32-[4294967295, 2147483648])]) :-
   % a uint32 beyond an int32: read, divided and stored without a sign
   host_name(uint32, [2], [4294967295, 4294967295], X),
   on_device(D, X, Xd),
   over([I:2], [Y[I] := Xd[I] // (1 + I) + I]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(uint32_and_int32_are_an_int64, [timeout(120), forall(test_device(D, _)), true(F-Vs == int64-[4294967294, -1])]) :-
   host_name(uint32, [2], [4294967295, 0], X),
   host_name(int32, [2], [-1, -1], N),
   on_device(D, X, Xd), on_device(D, N, Nd),
   over([I:2], [Y[I] := Xd[I] + Nd[I]]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(uint64_stays_uint64, [timeout(120), forall(test_device(D, _)), true(F-Vs == uint64-[18446744073709551615, 3])]) :-
   host_name(uint64, [2], [18446744073709551614, 2], X),
   on_device(D, X, Xd),
   over([I:2], [Y[I] := Xd[I] + 1]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(cast_to_int64_saturates, [timeout(120), forall(test_device(D, _)), true(Vs == [9223372036854775807, -5])]) :-
   host_name(float64, [2], [1.0e30, -5.9], X),
   on_device(D, X, Xd),
   over([I:2], [Y[I] := cast(Xd[I], int64)]),
   realize([Y], [], []),
   name_elements(Y, int64, Vs).

test(cast_float64_to_float32, [timeout(120), forall(test_device(D, _)), true(F-Vs == float32-[0.10000000149011612])]) :-
   host_name(float64, [1], [0.1], X),
   on_device(D, X, Xd),
   over([I:1], [Y[I] := cast(Xd[I], float32)]),
   realize([Y], [], []),
   name_elements(Y, F, Vs).

test(mean_of_float64, [timeout(120), forall(test_device(D, _)), true(F-Vs == float64-[0.15000000000000002])]) :-
   host_name(float64, [2], [0.1, 0.2], X),
   on_device(D, X, Xd),
   M @= mean(Xd),
   realize([M], [], []),
   name_elements(M, F, Vs).

% bits/1 is the bits of a float as the device computes it, an int32 for a float32 or a
% narrower float and an int64 for a float64, whatever else its kernel computes; the
% reference agrees.

test(bits_of_float32_next_to_a_float64, [timeout(120), forall(test_device(D, _)),
                                          true(F-Ref-Vs == int32-Bits-Bits)]) :-
   Bits = [1065353216, -1073741824, 1056964608, 1036831949],
   shape(X, [4]), type(X, float32), shape(H, [4]), type(H, float64), shape(B, [4]),
   maplist(placed(D), [X, H, B]),
   over([I:4], [B[I] := bits(X[I]) + (H[I] > 1)]),
   Data = [X-[1.0, -2.0, 0.5, 0.1], H-[0.0, 0.0, 0.0, 0.0]],
   eval(B, Data, Ref), run(B, Data, Vs, [device(D)]),
   type(B, F).

test(bits_of_float64, [timeout(120), forall(test_device(D, _)), true(F-Ref-Vs == int64-Bits-Bits)]) :-
   Bits = [4607182418800017408, -4611686018427387904, 4602678819172646912, 4591870180066957722],
   shape(X, [4]), type(X, float64), shape(B, [4]),
   maplist(placed(D), [X, B]),
   over([I:4], [B[I] := bits(X[I])]),
   Data = [X-[1.0, -2.0, 0.5, 0.1]],
   eval(B, Data, Ref), run(B, Data, Vs, [device(D)]),
   type(B, F).

test(bits_of_float16, [timeout(120), forall(test_device(D, _)), true(F-Ref-Vs == int32-Bits-Bits)]) :-
   % the float32 the float16 is computed in
   Bits = [1065353216, -1073741824, 1056964608],
   shape(X, [3]), type(X, float16), shape(B, [3]),
   maplist(placed(D), [X, B]),
   over([I:3], [B[I] := bits(X[I])]),
   Data = [X-[1.0, -2.0, 0.5]],
   eval(B, Data, Ref), run(B, Data, Vs, [device(D)]),
   type(B, F).

% A scatter of many sources runs them in parallel, folding a place atomically: a name of 64
% bits by the 64-bit atomics of the device, a double by a compare-and-swap of its bits. The
% bins equal those folded one source at a time: each of 256 sources, sums and products
% exact in the format in whatever order, and wrong in 32 bits.

test(scatter_add_int64, [timeout(120), forall(test_device(D, _)), true(As-Vs == [+]-Expected)]) :-
   sources(K-(4294967296 + K), Ws),
   scatter(D, int64, +, Ws, As, Vs, Expected).

test(scatter_add_uint64, [timeout(120), forall(test_device(D, _)), true(As-Vs == [+]-Expected)]) :-
   % each bin beyond a signed long
   sources(K-(36028797018963968 + K), Ws),
   scatter(D, uint64, +, Ws, As, Vs, Expected).

test(scatter_add_uint32, [timeout(120), forall(test_device(D, _)), true(As-Vs == [+]-Expected)]) :-
   % each bin beyond an int32: folded as a long, stored as a uint32
   sources(K-(8388608 + K), Ws),
   scatter(D, uint32, +, Ws, As, Vs, Expected).

test(scatter_add_float64, [timeout(120), forall(test_device(D, _)), true(As-Vs == [+]-Expected)]) :-
   sources(K-(1099511627776.5 + K), Ws),
   scatter(D, float64, +, Ws, As, Vs, Expected).

test(scatter_max_int64, [timeout(120), forall(test_device(D, _)), true(As-Vs == [max]-Expected)]) :-
   sources(K-(4294967296 * (K mod 1000 - 100) + K), Ws),
   scatter(D, int64, max, Ws, As, Vs, Expected).

test(scatter_min_int64, [timeout(120), forall(test_device(D, _)), true(As-Vs == [min]-Expected)]) :-
   sources(K-(4294967296 * (K mod 1000 - 900) + K), Ws),
   scatter(D, int64, min, Ws, As, Vs, Expected).

test(scatter_max_uint64_is_unsigned, [timeout(120), forall(test_device(D, _)), true(As-Vs == [max]-Expected)]) :-
   % a source in three beyond a signed long, where it would compare as negative
   sources(K-(9223372036854775808 * (K mod 3 // 2) + K), Ws),
   scatter(D, uint64, max, Ws, As, Vs, Expected).

test(scatter_max_float64, [timeout(120), forall(test_device(D, _)), true(As-Vs == [max]-Expected)]) :-
   sources(K-(1099511627776.5 * (K mod 1000 - 100) + K), Ws),
   scatter(D, float64, max, Ws, As, Vs, Expected).

test(scatter_min_float64, [timeout(120), forall(test_device(D, _)), true(As-Vs == [min]-Expected)]) :-
   sources(K-(1099511627776.5 * (K mod 1000 - 900) + K), Ws),
   scatter(D, float64, min, Ws, As, Vs, Expected).

test(scatter_product_int64, [timeout(120), forall(test_device(D, _)), true(As-Vs == [*]-Expected)]) :-
   % 2 to the 40 in each bin
   sources(K-(1 + (K + 639) // 4096), Ws),
   scatter(D, int64, *, Ws, As, Vs, Expected).

test(scatter_product_float64, [timeout(120), forall(test_device(D, _)), true(As-Vs == [*]-Expected)]) :-
   % 1.5 to the 32 in each bin: 51 bits
   sources(K-(1.0 + 0.5 * ((K + 511) // 4096)), Ws),
   scatter(D, float64, *, Ws, As, Vs, Expected).

test(scatter_stays_a_loop_without_the_atomics, [timeout(120), forall(test_device(D, _)),
      setup(asserta(compile:known_extensions(D, []), Ref)), cleanup(erase(Ref)),
      true(As-Vs == []-Expected)]) :-
   % a device without the 64-bit atomics: the sources are one loop, the bins the same
   sources(K-(4294967296 + K), Ws),
   scatter(D, int64, +, Ws, As, Vs, Expected).

% A name of no device takes the device of the run's option before its type is resolved: the
% formats that exist are that device's.
test(float64_on_the_device_of_the_run, [timeout(120), forall(test_device(D, _)), true(Vs == [0.2, 1.0e300])]) :-
   shape(X, [2]),
   type(X, float64),
   over([I:2], [Y[I] := X[I] * 2]),
   run(Y, [X-[0.1, 5.0e299]], Vs, [device(D)]).

test(int64_fold_on_the_device_of_the_run, [timeout(120), forall(test_device(D, _)), true(Vs == [9000000000])]) :-
   shape(X, [3]),
   type(X, int64),
   over([], [H := 0]),
   over([I:3], [H := max(H, X[I])]),
   run(H, [X-[5, 9000000000, -9000000000]], Vs, [device(D)]).

test(int64_cast_realized_on_the_device_of_the_option, [timeout(120), forall(test_device(D, _)), true(F-Vs == int64-[9223372036854775807, -5])]) :-
   shape(X, [2]),
   kind(X, float),
   over([I:2], [Y[I] := cast(X[I], int64)]),
   realize([Y], [X-[1.0e30, -5.9]], [device(D)]),
   name_elements(Y, F, Vs).

% A program labelled with no device, by kernels/3 or eval/3, keeps its types: a device with
% doubles then runs it in the formats it would have had with the device known from the
% start, and one without them refuses it, see no_doubles/2.

% int_into_float(-X, -Y, -A): A is the product of an int X of no range and a float Y: a
% float64, which holds every int32 exactly.
int_into_float(X, Y, A) :-
   shape(X, [3]), kind(X, int), shape(Y, [3]),
   over([I:3], [A[I] := X[I]*Y[I]]).

int_into_float_data(X, Y, [X-[1000, 3, -5], Y-[1.0, 0.5, 2.0]]).

% no_doubles(+D, -Ref): the device D has no float64 from now on, as compile.pl knows its
% formats, until Ref is erased; no handle compiled for it before is kept.
no_doubles(D, Ref) :-
   flush_handles,
   compile:device_formats(D, Fs),
   exclude(==(float64), Fs, Fs1),
   asserta(compile:known_formats(D, Fs1), Ref).

with_doubles(Ref) :-
   erase(Ref),
   flush_handles.

test(labelled_with_no_device_runs_as_known, [timeout(120), forall(test_device(D, _)),
      true(F1-Vs1-F2-Vs2-Vs0 == float64-Vs-float64-Vs-Vs)]) :-
   Vs = [1000.0, 1.5, -10.0],
   int_into_float(X1, Y1, A1), int_into_float_data(X1, Y1, Data1),
   kernels(A1, [], _),
   eval(A1, Data1, Vs0),
   realize([A1], Data1, [device(D)]),
   name_elements(A1, F1, Vs1),
   int_into_float(X2, Y2, A2), int_into_float_data(X2, Y2, Data2),
   device(A2, D),
   realize([A2], Data2, []),
   name_elements(A2, F2, Vs2).

test(float64_labelled_with_no_device_runs, [timeout(120), forall(test_device(D, _)), true(F-Vs == float64-[0.2, 1.0e300])]) :-
   shape(X, [2]), type(X, float64),
   over([I:2], [Y[I] := X[I] * 2]),
   eval(Y, [X-[0.1, 5.0e299]], Vs),
   realize([Y], [X-[0.1, 5.0e299]], [device(D)]),
   name_elements(Y, F, Vs).

test(realized_after_labelling_keeps_its_format, [timeout(120), forall(test_device(D, _)), true(F-Vs == int16-[5, 7, -100])]) :-
   % its type resolved before the run, to no format's exactly: the run stores it in its format
   shape(X, [3]), type(X, int8), shape(Y, [3]), type(Y, uint8),
   over([I:3], [A[I] := X[I] + Y[I]]),
   kernels(A, [], _),
   realize([A], [X-[1, 2, -128], Y-[4, 5, 28]], [device(D)]),
   name_elements(A, F, Vs).

test(labelled_with_no_device_refused_without_doubles, [timeout(120), forall(test_device(D, _)),
      setup(no_doubles(D, Ref)), cleanup(with_doubles(Ref)), true(M == Expected)]) :-
   int_into_float(X, Y, A), int_into_float_data(X, Y, Data),
   kernels(A, [], _),
   format(atom(Expected), "it needs float64, a format the device ~w does not have", [D]),
   catch(run(A, Data, _, [device(D)]), error(domain_error(type, _), context(_, M)), true).

test(declared_float64_refused_without_doubles, [timeout(120), forall(test_device(D, _)),
      setup(no_doubles(D, Ref)), cleanup(with_doubles(Ref)), true(M == Expected)]) :-
   shape(X, [2]), type(X, float64),
   over([I:2], [Y[I] := X[I] * 2]),
   eval(Y, [X-[0.1, 5.0e299]], _),
   format(atom(Expected), "it needs float64, a format the device ~w does not have", [D]),
   catch(realize([Y], [X-[0.1, 5.0e299]], [device(D)]), error(domain_error(type, _), context(_, M)), true).

% With no device, eval/3 gives the exact results of 64-bit programs, and kernels/3 and the
% signature take them.

i64_fold(X, H) :-
   shape(X, [3]), type(X, int64),
   over([], [H := 0]),
   over([I:3], [H := max(H, X[I])]).

test(eval_of_64_bits_with_no_device, [timeout(60),
      true(Vs == [[0.2, 1.0e300], [9000000001, -8999999999, 9223372036854775807], [4294967295, 1, 8],
                  [9000000000], [9223372036854775807, -5]])]) :-
   shape(X1, [2]), type(X1, float64), over([I:2], [Y1[I] := X1[I] * 2]),
   shape(X2, [3]), type(X2, int64), over([I:3], [Y2[I] := X2[I] + 1]),
   shape(X3, [3]), type(X3, uint32), over([I:3], [Y3[I] := X3[I] + 1]),
   i64_fold(X4, H),
   shape(X5, [2]), kind(X5, float), over([I:2], [Y5[I] := cast(X5[I], int64)]),
   eval(Y1, [X1-[0.1, 5.0e299]], V1),
   eval(Y2, [X2-[9000000000, -9000000000, 9223372036854775806]], V2),
   eval(Y3, [X3-[4294967294, 0, 7]], V3),
   eval(H, [X4-[5, 9000000000, -9000000000]], V4),
   eval(Y5, [X5-[1.0e30, -5.9]], V5),
   Vs = [V1, V2, V3, V4, V5].

test(kernels_of_64_bits_with_no_device, [timeout(60), true(Fs == [float64, int64, uint32, int64, int64])]) :-
   shape(X1, [2]), type(X1, float64), over([I:2], [Y1[I] := X1[I] * 2]),
   shape(X2, [3]), type(X2, int64), over([I:3], [Y2[I] := X2[I] + 1]),
   shape(X3, [3]), type(X3, uint32), over([I:3], [Y3[I] := X3[I] + 1]),
   i64_fold(_, H),
   shape(X5, [2]), kind(X5, float), over([I:2], [Y5[I] := cast(X5[I], int64)]),
   Outs = [Y1, Y2, Y3, H, Y5],
   maplist([Y]>>kernels(Y, [], _), Outs),
   maplist(type, Outs, Fs).

test(signature_of_64_bits_with_no_device, [timeout(60), true(S1-K1-S0-K0 == [3]-int-[]-int)]) :-
   i64_fold(_, H),
   handle:signature(H, [slot(_, S1, K1, D1)], slot(_, S0, K0, D0), _),
   var(D1), D1 == D0.

test(int64_scatter_planned_with_no_device_is_atomic, [timeout(60), true(As == [+])]) :-
   % a device not known yet is taken to have the 64-bit atomics
   shape(Idx, [4096]), kind(Idx, int), elements(Idx, 0-15),
   shape(W, [4096]), type(W, int64),
   shape(H, [16]), type(H, int64),
   over([I:16], [H[I] := 0]),
   over([K:4096], [H[Idx[K]] := H[Idx[K]] + W[K]]),
   kernels(H, [], Plan),
   findall(Op, ( member(Kernel, Plan), is_dict(Kernel), get_dict(atomics, Kernel, Ats), member(_-Op, Ats) ), As).

test(sum_of_int64_is_split, [timeout(120), forall(test_device(D, _)), true(F-Vs == int64-[294912000000000])]) :-
   % long enough to be summed by chunks: the partial sums are int64 too
   filled(65536, 4500000000, Xs),
   host_name(int64, [65536], Xs, X),
   on_device(D, X, Xd),
   S @= sum(Xd),
   realize([S], [], []),
   name_elements(S, F, Vs).

test(sum_of_an_int64_matrix, [timeout(120), forall(test_device(D, _)), true(F-Vs == int64-[294912000000000])]) :-
   % two reduced axes: the sums of the rows are int64 too
   filled(65536, 4500000000, Xs),
   host_name(int64, [512, 128], Xs, X),
   on_device(D, X, Xd),
   S @= sum(Xd),
   realize([S], [], []),
   name_elements(S, F, Vs).

test(dot_of_float64_is_split, [timeout(120), forall(test_device(D, _)), true(F-Vs == float64-[1000000000016383.75])]) :-
   % exact in a double in whatever order it is summed, and lost in partial sums of float32
   filled(65535, 0.25, Rest), filled(65536, 1.0, Ones),
   host_name(float64, [65536], [1.0e15 | Rest], X),
   host_name(float64, [65536], Ones, O),
   on_device(D, X, Xd), on_device(D, O, Od),
   S @= sum(Xd * Od),
   realize([S], [], []),
   name_elements(S, F, Vs).

test(float64_after_a_float32_product, [timeout(120), forall(test_device(D, _)), true(Vs == [256.5])]) :-
   % the product is a kernel of float32 vectors: the float64 box after it is none of its
   product(D, A, B, C),
   matrix(D, float64, H), matrix(D, _, Z),
   over([I:256, J:256], [Z[I, J] := C[I, J] + H[I, J]]),
   matrix_run(D, Z, [A-1.0, B-1.0, H-0.5], Vs).

test(vectors_are_of_float32_alone, [timeout(120), forall(test_device(D, Dev))]) :-
   % the float64 box costs the product neither its vectors nor its staged reads
   product(D, _, _, C),
   matrix(D, float64, H), matrix(D, _, Z),
   over([I:256, J:256], [Z[I, J] := C[I, J] + H[I, J]]),
   compile:device_options(Dev, Options),
   compile:kernels(Z, Options, Plan),
   compile:flat_plan(Plan, Ks),
   forall(( member(K, Ks), get_dict(vector, K, W), W > 1 ),
          ( get_dict(names, K, Ns), forall(member(N, Ns), compile:ptype(N, float)) )),
   once(( member(K, Ks), get_dict(stage, K, Stage), Stage \== none, get_dict(vector, K, W), W > 1 )).

test(int32_after_a_float32_product, [timeout(120), forall(test_device(D, _)), true(Vs == [7])]) :-
   % the int32 box is written an element at a time, by no float vector
   product(D, A, B, C),
   matrix(D, _, Z),
   over([I:256, J:256], [Z[I, J] := where(C[I, J] > 100, 7, 3)]),
   matrix_run(D, Z, [A-1.0, B-1.0], Vs).

test(bool_after_a_float32_product, [timeout(120), forall(test_device(D, _)), true(Vs == [1])]) :-
   product(D, A, B, C),
   matrix(D, _, Z),
   over([I:256, J:256], [Z[I, J] := C[I, J] > 100]),
   matrix_run(D, Z, [A-1.0, B-1.0], Vs).

test(uint8_after_a_float32_product, [timeout(120), forall(test_device(D, _)), true(Vs == [259.0])]) :-
   % a narrow input is read where it is stored, by no float vector
   product(D, A, B, C),
   matrix(D, uint8, T), matrix(D, _, Z),
   over([I:256, J:256], [Z[I, J] := C[I, J] + T[I, J]]),
   matrix_run(D, Z, [A-1.0, B-1.0, T-3], Vs).

test(product_from_host_inputs, [timeout(120), forall(( test_device(D, _), member(F, [float32, float64]) )),
                                 true(K-Vs == K0-[256.5])]) :-
   % the copies of the inputs come before the boxes: they part none of the kernels of the
   % program the device's names make, a float32 epilogue in the product's kernel
   filled(65536, 1.0, Ones), filled(65536, 0.5, Halves),
   host_name(float32, [256, 256], Ones, A0), host_name(float32, [256, 256], Ones, B0),
   host_name(F, [256, 256], Halves, T0),
   on_device(D, A0, A), on_device(D, B0, B), on_device(D, T0, T),
   matrix(D, _, C), matrix(D, _, Z),
   over([I:256, J:256], [C[I, J] := 0]),
   over([I:256, J:256, L:256], [C[I, J] := C[I, J] + A[I, L] * B[L, J]]),
   over([I:256, J:256], [Z[I, J] := C[I, J] + T[I, J]]),
   product(D, _, _, C1), matrix(D, F, T1), matrix(D, _, Z1),
   over([I1:256, J1:256], [Z1[I1, J1] := C1[I1, J1] + T1[I1, J1]]),
   test_device(D, Device), device_options(Device, Options),
   kernel_count(Z, Options, K), kernel_count(Z1, Options, K0),
   realize([Z], [], []),
   name_elements(Z, _, Vs0),
   sort(Vs0, Vs).

test(float32_product_from_a_float64, [timeout(120), forall(test_device(D, _)), true(Vs == [256.5])]) :-
   % the initialisation of the sums reads a float64: it is none of the product's kernel
   N = 256,
   matrix(D, float32, A), matrix(D, float32, B), matrix(D, float64, H), matrix(D, _, C),
   over([I:N, J:N], [C[I, J] := cast(H[I, J], float32)]),
   over([I:N, J:N, K:N], [C[I, J] := C[I, J] + A[I, K] * B[K, J]]),
   matrix_run(D, C, [A-1.0, B-1.0, H-0.5], Vs).

test(float32_product_from_an_int32, [timeout(120), forall(test_device(D, _)), true(Vs == [259.0])]) :-
   N = 256,
   matrix(D, float32, A), matrix(D, float32, B), matrix(D, int32, T), elements(T, 0-100), matrix(D, _, C),
   over([I:N, J:N], [C[I, J] := T[I, J]]),
   over([I:N, J:N, K:N], [C[I, J] := C[I, J] + A[I, K] * B[K, J]]),
   matrix_run(D, C, [A-1.0, B-1.0, T-3], Vs).

test(float32_product_into_a_float64, [timeout(120), forall(test_device(D, _)), true(Vs == [25.600000381469727])]) :-
   % 256 times the float32 nearest 0.1, exact in the float64 sums
   product(D, A, B, C),
   type(C, float64),
   matrix_run(D, C, [A-1.0, B-0.1], Vs).

test(masked_float32_product_into_a_float64, [timeout(120), forall(test_device(D, _)), true(Vs == [25.600000381469727])]) :-
   % the tile a staged kernel sums under the guard in is of float64 too
   N = 256,
   matrix(D, float32, A), matrix(D, float32, B), matrix(D, float32, M), matrix(D, float64, C),
   over([I:N, J:N], [C[I, J] := 0]),
   over([I:N, J:N, K:N], [C[I, J] := where(M[I, J] > 0, C[I, J] + A[I, K] * B[K, J], C[I, J])]),
   matrix_run(D, C, [A-1.0, B-0.1, M-1.0], Vs).

% A kernel whose names are all float64 runs by vectors of doubles where the device has them,
% see compile:vector_width/3; one of float32 and float64 names an element at a time. The
% values differ from 1 by multiples of 2^-40, which a float32 loses: the results are exact.

test(float64_vectors_select, [timeout(120), forall(( test_device(D, _), member(N, [4096, 4099, 37]) )), true(Vs == Expected)]) :-
   % 4099 and 37 are no multiple of the lanes
   numlist(1, N, Ks), maplist(near_one, Ks, Xs),
   length(Xs, N), near_one(100, Z0), filled(N, Z0, Zs),
   host_name(float64, [N], Xs, X), host_name(float64, [N], Zs, Z),
   on_device(D, X, Xd), on_device(D, Z, Zd),
   over([I:N], [Y[I] := where(Xd[I] > Zd[I], (Xd[I] - 1.0) * 1099511627776.0, Zd[I] - Xd[I])]),
   realize([Y], [], []),
   name_elements(Y, float64, Vs),
   maplist(selected(Z0), Xs, Expected).

test(float64_vectors_fma_and_lane_index, [timeout(120), forall(( test_device(D, _), member(N, [4096, 37]) )), true(Vs == Expected)]) :-
   % X*S + X fused, S read as one element; the lane index compared and multiplied
   numlist(1, N, Ks), maplist(near_one, Ks, Xs),
   host_name(float64, [N], Xs, X), host_name(float64, [2], [3.0, 0.5], S),
   on_device(D, X, Xd), on_device(D, S, Sd),
   over([I:N], [Y[I] := where(I < 5, Xd[I] * Sd[0] + Xd[I], (Xd[I] - 1.0) * 1099511627776.0 - I)]),
   realize([Y], [], []),
   name_elements(Y, float64, Vs),
   N1 is N - 1, numlist(0, N1, Is),
   maplist(fma_or_lane, Is, Xs, Expected).

test(float64_column_sums_by_vectors, [timeout(120), forall(( test_device(D, _), member(C, [256, 250]) )), true(Vs-Ms == Expected-Halves)]) :-
   % the sums of the columns, accumulated by vectors along the row, and halved after them in
   % the same kernel: exact in a double in whatever order, and lost in a float32
   R = 300,
   column_data(R, C, Xs),
   host_name(float64, [R, C], Xs, X),
   on_device(D, X, Xd),
   over([J:C], [Sum[J] := 0]),
   over([I:R, J:C], [Sum[J] := Sum[J] + Xd[I, J]]),
   over([J:C], [M[J] := Sum[J] * 0.5]),
   realize([Sum, M], [], []),
   name_elements(Sum, float64, Vs), name_elements(M, float64, Ms),
   V is 1.0e15 + 0.25 * (R - 1), H is V * 0.5,
   filled(C, V, Expected), filled(C, H, Halves).

test(float64_column_sums_into_a_float32, [timeout(120), forall(test_device(D, _)), true(Vs == Expected)]) :-
   % a float32 epilogue in a kernel of double vectors is written an element at a time
   R = 300, C = 256,
   column_data(R, C, Xs),
   host_name(float64, [R, C], Xs, X),
   on_device(D, X, Xd),
   over([J:C], [Sum[J] := 0]),
   over([I:R, J:C], [Sum[J] := Sum[J] + Xd[I, J]]),
   type(F, float32),
   over([J:C], [F[J] := cast(Sum[J] - 1.0e15, float32)]),
   realize([F], [], []),
   name_elements(F, float32, Vs),
   V is 0.25 * (R - 1), filled(C, V, Expected).

test(float64_and_float32_stay_scalar, [timeout(120), forall(test_device(D, _)), true(Vs == Expected)]) :-
   N = 4096,
   numlist(1, N, Ks), maplist(near_one, Ks, Xs), filled(N, 2.0, Ws),
   host_name(float64, [N], Xs, X), host_name(float32, [N], Ws, W),
   on_device(D, X, Xd), on_device(D, W, Wd),
   over([I:N], [Y[I] := (Xd[I] * Wd[I] - 2.0) * 549755813888.0]),
   realize([Y], [], []),
   name_elements(Y, float64, Vs),
   maplist([K, E]>>(E is float(K)), Ks, Expected).

test(float64_vector_plans, [timeout(120), forall(test_device(D, Dev))]) :-
   % the lanes of a vector of doubles where the device has them, none in a kernel of both
   device_options(Dev, Options), option(double_vector(WD), Options),
   option(vector(WF), Options),
   N = 4096,
   shape(A, [N]), type(A, float64), device(A, D),
   shape(B, [N]), type(B, float64), device(B, D),
   shape(F, [N]), type(F, float32), device(F, D),
   over([I:N], [Y[I] := where(A[I] > B[I], A[I] * B[I] + A[I], B[I])]),
   over([I:N], [Z[I] := A[I] * F[I]]),
   over([I:N], [Y32[I] := F[I] * F[I]]),
   shape(X, [300, 256]), type(X, float64), device(X, D),
   over([J:256], [Sum[J] := 0]),
   over([I:300, J:256], [Sum[J] := Sum[J] + X[I, J]]),
   over([J:256], [M[J] := Sum[J] * 0.5]),
   plan_vectors(Y, Options, WY, SY),
   plan_vectors(Z, Options, WZ, _),
   plan_vectors(Y32, Options, W32, _),
   plan_vectors(M, Options, WM, _),
   assertion(WY == [WD]), assertion(WZ == [1]), assertion(W32 == [WF]), assertion(WM == [WD]),
   (  WD > 1
   -> format(atom(Ptr), "double~d *", [WD]), assertion(sub_atom(SY, _, _, _, Ptr))
   ;  assertion(\+ sub_atom(SY, _, _, _, "double2"))
   ).

% A value the engine types wider than its operands is computed at that width: a float32 with
% an int32 is a float64, its operands converted to double before the operation, which C
% would compute in float; values a float loses.

% mixed_run(+D, +Y, +Names, +Data, -F, -Ref, -Vs): the program of Y on the device D, with Names
% on it: the format of Y, the reference and the device's elements.
mixed_run(D, Y, Names, Data, F, Ref, Vs) :-
   maplist(placed(D), [Y | Names]),
   eval(Y, Data, Ref), run(Y, Data, Vs, [device(D)]),
   type(Y, F).

test(float32_and_int32_in_double, [timeout(120), forall(test_device(D, _)),
                                    true(F-Ref-Vs == float64-[25165826.5, 4.5]-[25165826.5, 4.5])]) :-
   shape(X, [2]), type(X, float32), shape(J, [2]), type(J, int32), shape(Y, [2]),
   over([I:2], [Y[I] := (X[I] + J[I]) * 2 - X[I] * J[I]]),
   mixed_run(D, Y, [X, J], [X-[0.5, 1.5], J-[16777217, 3]], F, Ref, Vs).

test(comparison_of_float32_and_int32, [timeout(120), forall(test_device(D, _)), true(F-Ref-Vs == bool-[1, 0]-[1, 0])]) :-
   % compared in double in a kernel of no double name
   shape(X, [2]), type(X, float32), shape(J, [2]), type(J, int32), shape(Y, [2]),
   over([I:2], [Y[I] := X[I] < J[I]]),
   mixed_run(D, Y, [X, J], [X-[16777216.0, 3.0], J-[16777217, 3]], F, Ref, Vs).

test(where_and_max_of_float32_and_int32, [timeout(120), forall(test_device(D, _)),
                                          true(Ref-Vs == [33554434.0, 3.5]-[33554434.0, 3.5])]) :-
   shape(X, [2]), type(X, float32), shape(J, [2]), type(J, int32), shape(Y, [2]),
   over([I:2], [Y[I] := max(X[I], J[I]) + where(X[I] > 0, X[I], J[I])]),
   mixed_run(D, Y, [X, J], [X-[-1.0, 0.5], J-[16777217, 3]], _, Ref, Vs).

test(fold_of_float32_by_int32, [timeout(120), forall(test_device(D, _)), true(F-Ref-Vs == float64-[8388611.5]-[8388611.5])]) :-
   % the products accumulated in a register of the reduction
   shape(X, [3]), type(X, float32), shape(J, [3]), type(J, int32), shape(S, []),
   over([], [S := 0]),
   over([I:3], [S := S + X[I] * J[I]]),
   mixed_run(D, S, [X, J], [X-[0.5, 1.0, 1.0], J-[16777217, 1, 2]], F, Ref, Vs).

test(uint32_and_float32_in_double, [timeout(120), forall(test_device(D, _)), true(F-Ref-Vs == float64-[4294967295.5]-[4294967295.5])]) :-
   shape(X, [1]), type(X, float32), shape(U, [1]), type(U, uint32), shape(Y, [1]),
   over([I:1], [Y[I] := X[I] + U[I]]),
   mixed_run(D, Y, [X, U], [X-[0.5], U-[4294967295]], F, Ref, Vs).

test(int_literal_of_25_bits_and_float32, [timeout(120), forall(test_device(D, _)), true(F-Ref-Vs == float64-[16777217.5]-[16777217.5])]) :-
   shape(X, [1]), type(X, float32), shape(Y, [1]),
   over([I:1], [Y[I] := X[I] + 16777217]),
   mixed_run(D, Y, [X], [X-[0.5]], F, Ref, Vs).

test(index_of_25_bits_and_float32, [timeout(120), forall(test_device(D, _)),
                                     true(Vs == [16777217.5])]) :-
   % the index of a reduction the compiler splits is an int of its parts; no reference, of
   % as many steps
   shape(X, [1]), type(X, float32), shape(S, [1]),
   over([R:1], [S[R] := 0]),
   over([R:1, K:16777218], [S[R] := max(S[R], X[R] + K)]),
   maplist(placed(D), [S, X]),
   run(S, [X-[0.5]], Vs, [device(D)]).

test(math_function_of_an_int, [timeout(120), forall(test_device(D, _)),
                                true(F-Ref-Vs-F16-Vs16 == float64-[4096.000122070311]-[4096.000122070311]-float32-[4.0])]) :-
   % of an int32 a float64, of an int16 a float32: the int converted to the float first
   shape(J, [1]), type(J, int32), shape(Y, [1]),
   over([I:1], [Y[I] := sqrt(J[I])]),
   mixed_run(D, Y, [J], [J-[16777217]], F, Ref, Vs),
   shape(J16, [1]), type(J16, int16), shape(Y16, [1]),
   over([I1:1], [Y16[I1] := sqrt(J16[I1])]),
   mixed_run(D, Y16, [J16], [J16-[16]], F16, _, Vs16).

test(bits_and_int_cast_of_a_float64_value, [timeout(120), forall(test_device(D, _)),
                                            true(F-Ref-Vs-Cs == int64-Bits-Bits-[16777217, 3])]) :-
   Bits = [4715268810259562496, 4614500768194494464],
   shape(X, [2]), type(X, float32), shape(J, [2]), type(J, int32), shape(Y, [2]), shape(Z, [2]), type(Z, int32),
   over([I:2], [Y[I] := bits(X[I] + J[I])]),
   Data = [X-[0.5, 0.25], J-[16777217, 3]],
   mixed_run(D, Y, [X, J], Data, F, Ref, Vs),
   over([I1:2], [Z[I1] := cast(X[I1] + J[I1], int32)]),
   mixed_run(D, Z, [], Data, _, _, Cs).

test(float32_product_stays_a_float_product, [timeout(120), forall(test_device(D, _)), true(F-Vs == float64-[-16785408.0])]) :-
   % the engine types the product a float32: rounded as one, though its sum is a float64
   shape(X, [1]), type(X, float32), shape(W, [1]), type(W, float32), shape(H, [1]), type(H, float64), shape(Y, [1]),
   over([I:1], [Y[I] := H[I] - X[I] * W[I]]),
   mixed_run(D, Y, [X, W, H], [X-[4097.0], W-[4097.0], H-[0.0]], F, _, Vs).

test(float32_and_narrow_int_in_float, [timeout(120), forall(test_device(D, Dev)), true(F-Vs-Doubles == float32-[100.5, 1.25]-0)]) :-
   % an int32 of a declared range and an index a float32 holds: no double in the source
   shape(X, [2]), type(X, float32), shape(J, [2]), type(J, int32), elements(J, 0-1000), shape(Y, [2]),
   over([I:2], [Y[I] := X[I] + J[I] + I]),
   mixed_run(D, Y, [X, J], [X-[0.5, 0.25], J-[100, 0]], F, _, Vs),
   device_options(Dev, Options),
   kernels(Y, Options, Plan), compile:source(Plan, Src),
   aggregate_all(count, sub_string(Src, _, _, _, "double"), Doubles).

test(max_of_int32_and_int64, [timeout(120), forall(test_device(D, _)), true(F-Ref-Vs == int64-[4294967296, 3]-[4294967296, 3])]) :-
   % max and min take two operands of one C type
   shape(J, [2]), type(J, int32), shape(L, [2]), type(L, int64), shape(Y, [2]),
   over([I:2], [Y[I] := max(J[I], L[I]) + min(L[I], J[I]) - min(L[I], J[I])]),
   mixed_run(D, Y, [J, L], [J-[-5, 3], L-[4294967296, -9]], F, Ref, Vs).

% A statement holding a value wider than the floats of its vectors runs an element at a time,
% where its operands are converted to double first, see compile:wide/3: an int literal of 25
% bits next to a float32, a selection or a maximum of one, an int of indices of 25 bits, in a
% kernel whose names are all float32; and an int of the lane numbers that no int holds. 4096
% elements are vectorised, 4099 no multiple of the lanes.

test(wide_comparisons_in_float32_vectors, [timeout(120), forall(( test_device(D, _), member(N, [4096, 4099]) )),
                                           true(Ref-Vs == Expected-Expected)]) :-
   shape(X, [N]), type(X, float32), shape(Y, [N]),
   over([I:N], [Y[I] := where(X[I] < 16777217, 1.0, 0.0) + where(X[I] + 16777217 > 33554432, 2.0, 0.0)
                       + where(max(X[I], 16777217) > X[I], 4.0, 0.0)
                       + where(where(X[I] > 0, X[I], 16777217) < 16777217.0, 8.0, 0.0)]),
   filled(N, 16777216.0, Xs), filled(N, 15.0, Expected),
   mixed_run(D, Y, [X], [X-Xs], _, Ref, Vs).

test(wide_index_in_float32_vectors, [timeout(120), forall(( test_device(D, _), member(N, [4096, 4099]) )),
                                     true(Vs-V1 == Ref-1.0)]) :-
   % 16777217 is no float32
   shape(Y, [N]),
   over([I:N], [Y[I] := where(I + 16777216 + 0.5 > 16777217, 1.0, 0.0)]),
   mixed_run(D, Y, [], [], _, Ref, Vs),
   nth0(1, Vs, V1).

test(axis_of_25_bits_in_float32_vectors, [timeout(120), forall(test_device(D, _)), true(Vs == Expected)]) :-
   % the last elements, read from the realized name
   N is 16777216 + 8,
   shape(Y, [N]), device(Y, D),
   over([I:N], [Y[I] := where(I + 0.5 > 16777216, 1.0, 0.0)]),
   realize([Y], [], []),
   over([J:8], [T[J] := Y[16777216 + J]]),
   realize([T], [], []),
   name_elements(T, float32, Vs),
   filled(8, 1.0, Expected).

test(long_int_of_lanes_in_float32_vectors, [timeout(120), forall(( test_device(D, _), member(N, [4096, 4099]) )),
                                            true(Vs == Ref)]) :-
   shape(X, [N]), type(X, float32), shape(Y, [N]),
   over([I:N], [Y[I] := where(I + 4294967296 > 4294967300, X[I], 0.0)]),
   filled(N, 2.5, Xs),
   mixed_run(D, Y, [X], [X-Xs], _, Ref, Vs).

test(float64_vectors_with_int_name_or_wide_literal, [timeout(120), forall(test_device(D, Dev)),
                                                     true(WJ-WL-VJ-VL == [1]-[WD]-RJ-RL)]) :-
   % an int32 name has the kernel run an element at a time; a literal of 33 bits is a double
   device_options(Dev, Options), option(double_vector(WD), Options),
   N = 4096,
   shape(X, [N]), type(X, float64), shape(J, [N]), type(J, int32), shape(YJ, [N]), shape(YL, [N]),
   maplist(placed(D), [X, J, YJ, YL]),
   over([I:N], [YJ[I] := X[I] + J[I]]),
   over([I:N], [YL[I] := where(X[I] < 4294967297, X[I] + 4294967296, 0.0)]),
   plan_vectors(YJ, Options, WJ, _), plan_vectors(YL, Options, WL, _),
   filled(N, 0.5, Xs), filled(N, 16777217, Js),
   mixed_run(D, YJ, [X, J], [X-Xs, J-Js], _, RJ, VJ),
   mixed_run(D, YL, [X], [X-Xs], _, RL, VL).

% The lane numbers of a vector of floats are ints, converted to floats where a float takes
% them: an operand of arithmetic, of a comparison, of a function or of a selection; compared
% with ints as ints.

test(lane_index_in_float32_vectors, [timeout(120), forall(( test_device(D, Dev), member(N, [4096, 4099, 37]) )), true(Vs == Ref)]) :-
   % vectorised at 4096
   shape(X, [N]), type(X, float32), shape(Y, [N]),
   maplist(placed(D), [X, Y]),
   over([I:N], [Y[I] := X[I] * (I + 1) + where(X[I] > I, I, 0.5) + I / 4 - min(X[I], -I)
                       + where(I < 5, 1.0, 0.0) + exp(I - I)]),
   device_options(Dev, Options), plan_vectors(Y, Options, _, Src),
   (  N == 4096
   -> assertion(sub_atom(Src, _, _, _, convert_float))
   ;  true
   ),
   filled(N, 2.5, Xs),
   mixed_run(D, Y, [X], [X-Xs], _, Ref, Vs).

:- end_tests(types).

% near_one(+K, -X): 1 plus K times 2^-40, exact in a double.
near_one(K, X) :-
   X is 1.0 + K * 2.0 ** -40.

% selected(+Z, +X, -Y): the expected selection of float64_vectors_select.
selected(Z, X, Y), X > Z => Y is (X - 1.0) * 1099511627776.0.
selected(Z, X, Y) => Y is Z - X.

% fma_or_lane(+I, +X, -Y): the expected value of float64_vectors_fma_and_lane_index.
fma_or_lane(I, X, Y), I < 5 => Y is X * 3.0 + X.
fma_or_lane(I, X, Y) => Y is (X - 1.0) * 1099511627776.0 - I.

% column_data(+R, +C, -Xs): R rows of C, the first 1e15, the others 0.25.
column_data(R, C, Xs) :-
   filled(C, 1.0e15, First),
   R1 is (R - 1) * C, filled(R1, 0.25, Rest),
   append(First, Rest, Xs).

% plan_vectors(+Out, +Options, -Ws, -Source): the vector widths of the kernels of Out under
% Options, and their source.
plan_vectors(Out, Options, Ws, Source) :-
   kernels(Out, Options, Plan),
   compile:flat_plan(Plan, Ks),
   findall(W, ( member(K, Ks), is_dict(K), get_dict(vector, K, W) ), Ws),
   compile:source(Plan, Src),
   atom_string(Source, Src).

% The clamp of a cast to an int, convert_<T>_sat, is printed where the value may leave the
% range of the format, and the conversion of C alone where what the kernel reads proves it
% within, see compile:cast_fits/3: the results are the same either way.

% clamps(+Out, -Types): the C types the source of the program of Out, of one kernel, clamps
% a cast to, convert_<T>_sat, in order, each once.
clamps(Out, Types) :-
   kernels(Out, [], [K]),
   source([K], Src),
   findall(T, clamp_in(Src, T), Ts),
   sort(Ts, Types).

clamp_in(Src, T) :-
   sub_string(Src, B, _, _, "convert_"),
   S is B + 8,
   member(T, [char, uchar, short, ushort, int, uint, long, ulong]),
   atom_concat(T, '_sat(', Rest),
   atom_length(Rest, L),
   sub_string(Src, S, L, _, Rest).

% bytes(-X, +N): X is an input of N uint8.
bytes(X, N) :-
   shape(X, [N]), type(X, uint8).

:- begin_tests(cast_fit).

test(uint8_read_fits_wider, [timeout(60), true(C == [])]) :-
   bytes(X, 300), shape(Y, [300]),
   over([I:300], [Y[I] := cast(X[I], int16) + cast(X[I], int32) + cast(X[I], uint16)]),
   clamps(Y, C).

test(uint8_read_may_leave_int8, [timeout(60), true(C == [char])]) :-
   bytes(X, 300), shape(Y, [300]),
   over([I:300], [Y[I] := cast(X[I], int8)]),
   clamps(Y, C).

test(mean_of_two_uint8_fits, [timeout(60), true(C == [])]) :-
   bytes(X, 300), bytes(Z, 300), shape(Y, [300]),
   over([I:300], [Y[I] := cast((X[I] + Z[I]) // 2, uint8)]),
   clamps(Y, C).

test(sum_of_two_uint8_is_clamped, [timeout(60), true(C == [uchar])]) :-
   % the type of the sum is a uint8, a contract: its value is computed wide, and may be 510
   bytes(X, 300), bytes(Z, 300), shape(Y, [300]),
   over([I:300], [Y[I] := cast(X[I] + Z[I], uint8)]),
   clamps(Y, C).

test(difference_of_uint8_fits_int16, [timeout(60), true(C == [])]) :-
   bytes(X, 300), bytes(Z, 300), shape(Y, [300]),
   over([I:300], [Y[I] := cast(X[I] - Z[I], int16)]),
   clamps(Y, C).

test(comparison_and_literals_fit, [timeout(60), true(C == [])]) :-
   bytes(X, 300), shape(Y, [300]),
   over([I:300], [Y[I] := cast(X[I] > 3, int8) + cast(where(X[I] > 7, 255, 0), uint8) + cast(-128, int8)]),
   clamps(Y, C).

test(literal_outside_is_clamped, [timeout(60), true(C == [uchar])]) :-
   bytes(X, 300), shape(Y, [300]),
   over([I:300], [Y[I] := X[I] + cast(256, uint8)]),
   clamps(Y, C).

test(max_min_and_mask_fit, [timeout(60), true(C == [])]) :-
   shape(X, [300]), type(X, int32), shape(Y, [300]),
   over([I:300], [Y[I] := cast(max(min(X[I], 255), 0), uint8) + cast(X[I] /\ 127, int8)
                          + cast(max(X[I], 0) mod 256, uint8)]),
   clamps(Y, C).

test(int32_read_is_clamped, [timeout(60), forall(test_device(D, _)), true(C == [uchar, uint])]) :-
   shape(X, [300]), type(X, int32), device(X, D),
   over([I:300], [Y[I] := cast(X[I], uint8) + cast(X[I], uint32)]),
   clamps(Y, C).

test(declared_range_fits, [timeout(60), true(C == [char])]) :-
   % 0..100 is a uint8, and 27 more an int8 still; 28 more is not
   shape(X, [300]), type(X, int32), elements(X, 0-100), shape(Y, [300]),
   over([I:300], [Y[I] := cast(X[I], uint8) + cast(X[I] + 27, int8) + cast(X[I] + 28, int8)]),
   clamps(Y, C).

test(range_in_an_extent_fits_at_its_bound, [timeout(60), true(C1-C2 == []-[uchar])]) :-
   N::integer(1, 256), shape(X, [N]), type(X, int32), elements(X, 0-(N-1)), shape(Y, [N]),
   over([I:N], [Y[I] := cast(X[I], uint8)]),
   clamps(Y, C1),
   M::integer(1, 257), shape(X2, [M]), type(X2, int32), elements(X2, 0-(M-1)), shape(Y2, [M]),
   over([J:M], [Y2[J] := cast(X2[J], uint8)]),
   clamps(Y2, C2).

test(index_fits_below_its_extent, [timeout(60), true(C1-C2 == []-[uchar])]) :-
   bytes(X, 256), shape(Y, [256]),
   over([I:256], [Y[I] := X[I] + cast(I, uint8)]),
   clamps(Y, C1),
   bytes(X2, 257), shape(Y2, [257]),
   over([J:257], [Y2[J] := X2[J] + cast(J, uint8)]),
   clamps(Y2, C2).

test(float_is_clamped, [timeout(60), true(C == [uchar])]) :-
   % a float is truncated, and not a number is 0, whatever bounds it
   bytes(X, 300), shape(F, [300]), kind(F, float), shape(Y, [300]),
   over([I:300], [Y[I] := cast(F[I], uint8) + cast(X[I] / 2, uint8)]),
   clamps(Y, C).

test(cast_of_a_float_bounds_what_reads_it, [timeout(60), true(C == [uchar])]) :-
   shape(F, [300]), kind(F, float), shape(Y, [300]),
   over([I:300], [Y[I] := cast(cast(F[I], uint8) + 1, int16)]),
   clamps(Y, C).

test(int32_fits_int64, [timeout(60), forall(test_device(D, _)), true(C == [])]) :-
   shape(X, [300]), type(X, int32), device(X, D),
   over([I:300], [Y[I] := cast(X[I], int64)]),
   clamps(Y, C).

test(operation_leaving_an_int_is_clamped, [timeout(60), forall(test_device(D, _)), true(C == [long])]) :-
   % the product of two int32 may wrap: nothing is said of it
   shape(X, [300]), type(X, int32), device(X, D),
   over([I:300], [Y[I] := cast(X[I] * X[I], int64)]),
   clamps(Y, C).

test(uint64_is_clamped, [timeout(60), forall(test_device(D, _)), true(C == [long])]) :-
   shape(X, [300]), type(X, uint64), elements(X, 0-10), device(X, D),
   over([I:300], [Y[I] := cast(X[I], int64)]),
   clamps(Y, C).

test(bool_input_fits, [timeout(60), true(C == [])]) :-
   shape(X, [300]), type(X, bool), shape(Y, [300]),
   over([I:300], [Y[I] := cast(X[I], uint8) * 255]),
   clamps(Y, C).

test(mean_of_uint8_at_the_edges, [timeout(120), forall(test_device(D, _)), true(Vs == [0, 255, 254, 127])]) :-
   host_name(uint8, [4], [0, 255, 255, 128], X), host_name(uint8, [4], [0, 255, 254, 127], Z),
   on_device(D, X, Xd), on_device(D, Z, Zd),
   over([I:4], [Y[I] := cast((Xd[I] + Zd[I]) // 2, uint8)]),
   realize([Y], [], []),
   name_elements(Y, uint8, Vs).

test(uint8_to_int8_at_the_edges, [timeout(120), forall(test_device(D, _)), true(Vs == [0, 127, 127, 127])]) :-
   host_name(uint8, [4], [0, 127, 128, 255], X),
   on_device(D, X, Xd),
   over([I:4], [Y[I] := cast(Xd[I], int8)]),
   realize([Y], [], []),
   name_elements(Y, int8, Vs).

test(difference_of_uint8_at_the_edges, [timeout(120), forall(test_device(D, _)), true(Vs == [-255, 255, 0, -1])]) :-
   host_name(uint8, [4], [0, 255, 255, 127], X), host_name(uint8, [4], [255, 0, 255, 128], Z),
   on_device(D, X, Xd), on_device(D, Z, Zd),
   over([I:4], [Y[I] := cast(Xd[I] - Zd[I], int16)]),
   realize([Y], [], []),
   name_elements(Y, int16, Vs).

test(realized_bounds_at_the_edges, [timeout(120), forall(test_device(D, _)), true(Vs == [-128, 127, 5, 127])]) :-
   % the elements of a realized name bound it: -128..127 is an int8, one more is not
   host_name(int32, [4], [-128, 127, 5, 127], X),
   on_device(D, X, Xd),
   realize([Xd], [], []),
   over([I:4], [Y[I] := cast(Xd[I], int8) + 0 * cast(Xd[I] + 1, int8)]),
   clamps(Y, [char]),
   realize([Y], [], []),
   name_elements(Y, int8, Vs).

test(declared_range_at_the_edges, [timeout(120), forall(test_device(D, _)), true(Vs == [0, 255, 7])]) :-
   shape(X, [3]), type(X, int32), elements(X, 0-255), device(X, D),
   over([I:3], [Y[I] := cast(X[I], uint8)]),
   run(Y, [X-[0, 255, 7]], Vs, []).

test(declared_range_is_checked, [timeout(120), forall(test_device(D, _)), error(domain_error(elements(0-255), _))]) :-
   % the range that drops the clamp is one every argument is held to
   shape(X, [3]), type(X, int32), elements(X, 0-255), device(X, D),
   over([I:3], [Y[I] := cast(X[I], uint8)]),
   run(Y, [X-[0, 256, 7]], _, []).

test(index_at_the_edges, [timeout(120), forall(test_device(D, _)), true(Vs == Expected)]) :-
   shape(Y, [256]), device(Y, D), type(Y, uint8),
   over([I:256], [Y[I] := cast(255 - I, uint8)]),
   clamps(Y, []),
   numlist(0, 255, Is), reverse(Is, Expected),
   run(Y, [], Vs, []).

test(int32_to_int64_at_the_edges, [timeout(120), forall(test_device(D, _)),
                                   true(Vs == [-2147483648, 2147483647, 255, 0])]) :-
   host_name(int32, [4], [-2147483648, 2147483647, 255, 0], X),
   on_device(D, X, Xd),
   over([I:4], [Y[I] := cast(Xd[I], int64)]),
   realize([Y], [], []),
   name_elements(Y, int64, Vs).

test(uint8_to_uint32_at_the_edges, [timeout(120), forall(test_device(D, _)), true(Vs == [0, 255, 4294967295])]) :-
   host_name(uint8, [3], [0, 255, 7], X), host_name(int64, [3], [0, 0, 4294967288], B),
   on_device(D, X, Xd), on_device(D, B, Bd),
   over([I:3], [Y[I] := cast(cast(Xd[I], uint32) + Bd[I], uint32)]),
   realize([Y], [], []),
   name_elements(Y, uint32, Vs).

test(clamped_and_fitting_agree_with_the_reference, [timeout(120), forall(test_device(D, _)), true(Vs == Expected)]) :-
   shape(X, [6]), type(X, uint8), device(X, D), shape(Z, [6]), type(Z, uint8), device(Z, D),
   over([I:6], [Y[I] := cast(X[I] + Z[I], uint8) + cast(X[I] - Z[I], int16) + cast((X[I] * Z[I]) >> 8, uint8)]),
   Data = [X-[0, 255, 255, 1, 128, 16], Z-[0, 255, 0, 255, 128, 16]],
   eval(Y, Data, Expected),
   run(Y, Data, Vs, []).

test(fitting_cast_under_the_flag, [timeout(120), forall(test_device(D, _)),
                                  setup(( flush_handles, set_prolog_flag(array_check_fit, true) )),
                                  cleanup(( set_prolog_flag(array_check_fit, false), flush_handles )),
                                  true(Vs == [0, 255, 127])]) :-
   host_name(uint8, [3], [0, 255, 128], X), host_name(uint8, [3], [0, 255, 127], Z),
   on_device(D, X, Xd), on_device(D, Z, Zd),
   over([I:3], [Y[I] := cast((Xd[I] + Zd[I]) // 2, uint8)]),
   realize([Y], [], []),
   name_elements(Y, uint8, Vs).

:- end_tests(cast_fit).
