:- module(safetensors_tests, []).

:- use_module(library(array/safetensors)).
:- use_module(library(array/buffer)).
:- use_module(library(array)).

% numpy.safetensors was written by the reference implementation, safetensors 0.8.0:
%
%   save_file({"enc.layers.0.w": np.arange(6, dtype=np.float32).reshape(2, 3),
%              "enc.layers.1.w": np.array([1.5, -2.5], dtype=np.float64),
%              "enc.ids": np.array([3, 1, 2], dtype=np.int32),
%              "mask": np.array([True, False]),
%              "half": np.array([0.5, 2.0], dtype=np.float16),
%              "empty": np.zeros((0, 4), dtype=np.float32)},
%             "numpy.safetensors", metadata={"source": "numpy"})
%
% torch.safetensors by safetensors 0.6.2 and torch 2.4.1:
%
%   x = torch.tensor([0.1, -2.0, 448.0, 1000.0, 0.001953125, 1.0625])
%   save_file({"brain": x.to(torch.bfloat16),
%              "eight": x.to(torch.float8_e4m3fn).reshape(2, 3)},
%             "torch.safetensors", metadata={"source": "torch"})

:- begin_tests(safetensors).

% tensor(+Kind, +Shape, +Values, -Name): a name of Kind realized on host with Values, stored
% as its kind is: float32 for a float, int32 for an int, bool for a bool.
tensor(Kind, Shape, Values, Name) :-
   foldl([E, P0, P]>>(P is P0*E), Shape, 1, N),
   compound_name_arguments(Data, data, Values),
   kind_storage(Kind, Type),
   buffer_from_data(Buffer, Type, N, Data),
   shape(Name, Shape),
   kind(Name, Kind),
   value(Name, Buffer).

kind_storage(float, float32).
kind_storage(int, int32).
kind_storage(bool, bool).

values(Name, Kind-Shape-Values) :-
   value(Name, Buffer),
   kind(Name, Kind),
   type(Name, Type),
   shape(Name, Shape),
   foldl([E, P0, P]>>(P is P0*E), Shape, 1, N),
   buffer_to_data(Buffer, Type, N, Data),
   compound_name_arguments(Data, data, Values).

with_file(File, Goal) :-
   setup_call_cleanup(tmp_file(safetensors, File), Goal, delete_file(File)).

raw_file(File, Json, Data) :-
   string_codes(Json, Header),
   length(Header, N),
   setup_call_cleanup(open(File, write, S, [type(binary)]),
                      ( forall(between(0, 7, I), ( B is (N >> (8*I)) /\ 0xff, put_byte(S, B) )),
                        maplist(put_byte(S), Header), maplist(put_byte(S), Data) ),
                      close(S)).

test(round_trip, [timeout(30)]) :-
   tensor(float, [2, 3], [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], W),
   tensor(int, [2], [7, -8], B),
   tensor(int, [0], [], E),
   tensor(float, [1], [0.25], Q),
   with_file(File, ( safetensors_write(File, _{fc1: _{weight: W, bias: B}, layers: [_{q: E}, _{q: Q}]}, _{format: pt}),
                     safetensors_read(File, T, M) )),
   M.format == "pt",
   values(T.fc1.weight, float-[2, 3]-[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]),
   values(T.fc1.bias, int-[2]-[7, -8]),
   T.layers = [L0, L1],
   values(L0.q, int-[0]-[]),
   values(L1.q, float-[1]-[0.25]).

test(empty_tree_no_metadata, [timeout(30)]) :-
   with_file(File, ( safetensors_write(File, _{}, _{}), safetensors_read(File, T, M),
                     size_file(File, 16) )),
   dict_pairs(T, _, []),
   dict_pairs(M, _, []).

% The header ends at a multiple of 8, and the tensors follow in the standard order of their
% paths whatever the order the tree was built in.
test(layout_is_canonical, [timeout(30)]) :-
   tensor(float, [3], [1.0, 2.0, 3.0], A),
   tensor(int, [1], [5], B),
   dict_pairs(T1, t, [b-B, a-A]),
   dict_pairs(T2, _, [a-A, b-B]),
   with_file(F1, with_file(F2, ( safetensors_write(F1, T1, _{}), safetensors_write(F2, T2, _{}),
                                 read_file_to_codes(F1, C1, [type(binary)]),
                                 read_file_to_codes(F2, C2, [type(binary)]) ))),
   C1 == C2,
   C1 = [N0, N1, N2, N3, N4, N5, N6, N7 | _],
   foldl([X, I-N, I1-N1x]>>(N1x is N \/ (X << (8*I)), I1 is I + 1), [N0, N1, N2, N3, N4, N5, N6, N7], 0-0, _-Len),
   (8 + Len) mod 8 =:= 0,
   length(C1, Size), Size =:= 8 + Len + 12 + 4.

% A level whose keys are 0, ..., N-1 reads back as a list; a non-canonical integer stays an atom.
test(integer_keys, [timeout(30)]) :-
   tensor(int, [1], [0], X),
   with_file(File, ( safetensors_write(File, _{d: _{0: X, 1: X}, g: _{0: X, 2: X}, s: _{'01': X}}, _{}),
                     safetensors_read(File, T, _) )),
   T.d = [_, _],
   is_dict(T.g), dict_keys(T.g, [0, 2]),
   is_dict(T.s), dict_keys(T.s, ['01']).

dict_keys(D, Ks) :-
   dict_pairs(D, _, Ps),
   pairs_keys(Ps, Ks).

test(reference_file, [timeout(30)]) :-
   module_property(safetensors_tests, file(Here)),
   file_directory_name(Here, Dir),
   directory_file_path(Dir, 'numpy.safetensors', File),
   safetensors_read(File, T, M),
   M.source == "numpy",
   T.enc.layers = [L0, L1],
   values(L0.w, float-[2, 3]-[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]),
   values(L1.w, float-[2]-[1.5, -2.5]),                % float64, kept
   type(L1.w, float64),
   values(T.enc.ids, int-[3]-[3, 1, 2]),
   values(T.mask, bool-[2]-[1, 0]),
   values(T.half, float-[2]-[0.5, 2.0]),                % float16, kept
   type(T.half, float16),
   type(T.mask, bool),
   values(T.empty, float-[0, 4]-[]).

test(torch_file, [timeout(30)]) :-
   % bfloat16 and float8_e4m3, kept: the float8_e4m3fn of torch, where 1000 is not a number
   module_property(safetensors_tests, file(Here)),
   file_directory_name(Here, Dir),
   directory_file_path(Dir, 'torch.safetensors', File),
   safetensors_read(File, T, M),
   M.source == "torch",
   type(T.brain, bfloat16),
   values(T.brain, float-[6]-[0.10009765625, -2.0, 448.0, 1000.0, 0.001953125, 1.0625]),
   type(T.eight, float8_e4m3),
   values(T.eight, float-[2, 3]-[0.1015625, -2.0, 448.0, NaN, 0.001953125, 1.0]),
   NaN =\= NaN.

test(coded_floats_round_trip, [timeout(30), true(Bits == [bfloat16-[0x3dcd, 0xc000, 0x43e0], float8_e4m3-[0x1d, 0xc0, 0x7e, 0x7f]])]) :-
   % written and read back, the elements are the same bits, a not a number too
   NaN is nan,
   coded(bfloat16, [0.1, -2.0, 448.0], B),
   coded(float8_e4m3, [0.1, -2.0, 448.0, NaN], E),
   with_file(File, ( safetensors_write(File, _{brain: B, eight: E}, _{}),
                     safetensors_read(File, T, _) )),
   maplist(format_bits, [T.brain-uint16, T.eight-uint8], Bits).

% coded(+Format, +Values, -Name): a name of Format realized on host with Values.
coded(Format, Values, Name) :-
   length(Values, N),
   compound_name_arguments(Data, data, Values),
   buffer_from_data(Buffer, Format, N, Data),
   shape(Name, [N]),
   type(Name, Format),
   value(Name, Buffer).

% format_bits(+Name-Ints, -Format-Bits): the format of Name and its elements read as Ints.
format_bits(Name-Ints, Format-Bits) :-
   type(Name, Format),
   shape(Name, [N]),
   value(Name, Buffer),
   buffer_to_data(Buffer, Ints, N, Data),
   compound_name_arguments(Data, _, Bits).

test(write_dotted_segment, [timeout(30), error(domain_error(safetensors_segment, 'a.b'))]) :-
   tensor(int, [1], [0], X),
   with_file(File, safetensors_write(File, _{'a.b': X}, _{})).

test(write_metadata_key, [timeout(30), error(domain_error(safetensors_segment, '__metadata__'))]) :-
   tensor(int, [1], [0], X),
   with_file(File, safetensors_write(File, _{'__metadata__': X}, _{})).

test(write_same_path_twice, [timeout(30), error(domain_error(distinct_safetensors_keys, '0'))]) :-
   tensor(int, [1], [0], X),
   with_file(File, safetensors_write(File, _{0: X, '0': X}, _{})).

test(write_unrealized_name, [timeout(30), error(existence_error(value, [l, w]))]) :-
   shape(W, [2]),
   with_file(File, safetensors_write(File, _{l: _{w: W}}, _{})).

test(write_tensor_term, [timeout(30), error(type_error(safetensors_tree, tensor(float, [1], _)))]) :-
   buffer_alloc(B, float32, 1, true),
   with_file(File, safetensors_write(File, _{w: tensor(float, [1], B)}, _{})).

test(write_name_at_root, [timeout(30), error(type_error(safetensors_tree, _))]) :-
   tensor(int, [1], [0], X),
   with_file(File, safetensors_write(File, X, _{})).

test(write_not_a_tree, [timeout(30), error(type_error(safetensors_tree, 3))]) :-
   with_file(File, safetensors_write(File, _{w: 3}, _{})).

% The leaves read are input names: their kind is their dtype's, their shape the file's.
test(read_names, [timeout(30)]) :-
   tensor(float, [2, 2], [1.0, 2.0, 3.0, 4.0], W),
   tensor(int, [1], [9], I),
   tensor(bool, [1], [1], M),
   with_file(File, ( safetensors_write(File, _{w: W, i: I, m: M}, _{}), safetensors_read(File, T, _) )),
   kind(T.w, float), kind(T.i, int), kind(T.m, bool),
   shape(T.w, [2, 2]), \+ shape(T.w, [4, 1]),
   values(T.i, int-[1]-[9]).

% What a name declares and its bytes do not tell travels in the metadata, and is declared again
% on the name read, before its value, which is checked against it.
test(declarations_round_trip, [timeout(30)]) :-
   tensor(int, [3], [2, 0, 1], P), elements(P, 0-9), permutation(P),
   shape(M, [2]), kind(M, bool), buffer_from_data(Mb, int32, 2, data(1, 0)), value(M, Mb),
   tensor(int, [2], [5, 6], I),
   with_file(File, ( safetensors_write(File, _{p: P, m: M, i: I}, _{note: hi}),
                     safetensors_read(File, T, Meta) )),
   dict_pairs(Meta, _, [note-"hi"]),
   elements(T.p, Rp), Rp == 0-9,
   get_attr(T.p, perm, true),
   kind(T.m, bool),
   elements(T.i, Ri), Ri == 5-6,
   \+ get_attr(T.i, elements, _).

test(declarations_in_the_metadata, [timeout(30)]) :-
   tensor(int, [1], [3], P), elements(P, 0-9),
   with_file(File, ( safetensors_write(File, _{p: P}, _{}),
                     read_file_to_codes(File, Codes, [type(binary)]) )),
   string_codes(Text, Codes),
   once(sub_string(Text, _, _, _, "\"array.elements.p\":\"[0, 9]\"")).

test(user_key_under_array, [timeout(30), error(domain_error(safetensors_metadata_key, 'array.x'))]) :-
   tensor(int, [1], [0], X),
   with_file(File, safetensors_write(File, _{x: X}, _{'array.x': "y"})).

test(read_unknown_declaration, [timeout(30), error(syntax_error(safetensors(metadata_key('array.shape.w'))))]) :-
   with_file(File, ( raw_file(File, "{\"__metadata__\":{\"array.shape.w\":\"x\"},\c
                                     \"w\":{\"dtype\":\"U8\",\"shape\":[1],\"data_offsets\":[0,1]}}", [1]),
                     safetensors_read(File, _, _) )).

test(read_declaration_of_no_tensor, [timeout(30), error(syntax_error(safetensors(metadata_key(v))))]) :-
   with_file(File, ( raw_file(File, "{\"__metadata__\":{\"array.permutation.v\":\"true\"},\c
                                     \"w\":{\"dtype\":\"I32\",\"shape\":[1],\"data_offsets\":[0,4]}}", [1, 0, 0, 0]),
                     safetensors_read(File, _, _) )).

test(read_values_out_of_declared_range, [timeout(30), error(domain_error(elements(0-1), _))]) :-
   with_file(File, ( raw_file(File, "{\"__metadata__\":{\"array.elements.w\":\"[0, 1]\"},\c
                                     \"w\":{\"dtype\":\"U8\",\"shape\":[2],\"data_offsets\":[0,2]}}", [1, 7]),
                     safetensors_read(File, _, _) )).

% Read, a dtype is kept: an int64 beyond an int32 is an int64 name on host.
test(read_int64_is_kept, [timeout(30), true(F-Vs == int64-[4294967296])]) :-
   with_file(File, ( raw_file(File, "{\"w\":{\"dtype\":\"I64\",\"shape\":[1],\"data_offsets\":[0,8]}}",
                              [0, 0, 0, 0, 1, 0, 0, 0]),
                     safetensors_read(File, T, _) )),
   type(T.w, F),
   value(T.w, B),
   buffer_to_data(B, int64, 1, Data),
   compound_name_arguments(Data, _, Vs).

% Only names on host are written: a value on a device is copied to host first.
test(write_device_name, [timeout(60), error(domain_error(host_name, [w]))]) :-
   tensor(float, [2], [1.0, 2.0], H),
   copy(H, W, pocl),
   realize([W], [], []),
   with_file(File, safetensors_write(File, _{w: W}, _{})).

test(read_truncated_data, [timeout(30), error(syntax_error(safetensors(truncated_data(w))))]) :-
   with_file(File, ( raw_file(File, "{\"w\":{\"dtype\":\"F32\",\"shape\":[2],\"data_offsets\":[0,8]}}", [0, 0, 0, 0]),
                     safetensors_read(File, _, _) )).

test(read_unindexed_data, [timeout(30), error(syntax_error(safetensors(unindexed_data)))]) :-
   with_file(File, ( raw_file(File, "{\"w\":{\"dtype\":\"U8\",\"shape\":[1],\"data_offsets\":[0,1]}}", [1, 2]),
                     safetensors_read(File, _, _) )).

test(read_gap, [timeout(30), error(syntax_error(safetensors(offsets(w))))]) :-
   with_file(File, ( raw_file(File, "{\"w\":{\"dtype\":\"U8\",\"shape\":[1],\"data_offsets\":[1,2]}}", [1, 2]),
                     safetensors_read(File, _, _) )).

test(read_wrong_size, [timeout(30), error(syntax_error(safetensors(entry(w))))]) :-
   with_file(File, ( raw_file(File, "{\"w\":{\"dtype\":\"F32\",\"shape\":[1],\"data_offsets\":[0,2]}}", [1, 2]),
                     safetensors_read(File, _, _) )).

test(read_unknown_dtype, [timeout(30), error(syntax_error(safetensors(entry(w))))]) :-
   with_file(File, ( raw_file(File, "{\"w\":{\"dtype\":\"F8_E5M2\",\"shape\":[2],\"data_offsets\":[0,2]}}", [1, 2]),
                     safetensors_read(File, _, _) )).

test(read_leaf_and_level, [timeout(30), error(syntax_error(safetensors(leaf_and_level)))]) :-
   with_file(File, ( raw_file(File, "{\"a\":{\"dtype\":\"U8\",\"shape\":[1],\"data_offsets\":[0,1]},\c
                                     \"a.b\":{\"dtype\":\"U8\",\"shape\":[1],\"data_offsets\":[1,2]}}", [1, 2]),
                     safetensors_read(File, _, _) )).

test(read_truncated_header, [timeout(30), error(syntax_error(safetensors(truncated_header)))]) :-
   with_file(File, ( setup_call_cleanup(open(File, write, S, [type(binary)]),
                                        maplist(put_byte(S), [100, 0, 0, 0, 0, 0, 0, 0, 0'{]),
                                        close(S)),
                     safetensors_read(File, _, _) )).

:- end_tests(safetensors).
