:- module(detector,
          [ detector_model/2,      % +Device, -Model
            detector_model/3,      % +Device, -Model, +Options
            detector_pages/2,      % -Pages, -References
            detector_pages/3,      % -Pages, -References, +Options
            page_image/3,          % +File, -Image, +Options
            kept_patches/4,        % +Model, +Image, -Gy, -Gx
            detector/7,            % +Model, +Kind, -Image, -Gy, -Gx, -Bias, -Outs
            detector_outputs/5,    % +Model, +Image, +Gy, +Gx, -Outs
            detect/4,              % +Model, +Image, -Detections, +Options
            check_torch/1          % +Options
          ]).
:- use_module(library(apply)).
:- use_module(library(lists)).
:- use_module(library(option)).
:- use_module(library(pairs)).
:- use_module(library(json), [atom_json_term/3]).
:- use_module(library(array)).
:- use_module(library(array/api)).
:- use_module(library(array/safetensors)).
:- use_module(example_data).
:- use_module(library(array/buffer), [buffer_to_data/4]).
:- use_module(library(clpBNR)).

/** <module> Inference of the music_deep symbol and line detector

The OMRDetector of ~/prog/music_deep, a ViT-nano on patches of 64 x 64 pixels of a whole
page of music, and its two dense heads, symbols as boxes and lines as segments, each patch
proposing five of each with a score per class. The weights are those of experiment 029,
written by detector.py from the checkpoint as a safetensors file; the page is an int name of
its pixels, 0..255, a grey image [H, W] or one of three channels [H, W, 3], the two kinds of
page, grey and rgb, each with its own pair of programs:

  1. kept_patches/4: the variance of every patch of the page, padded to a multiple of 64 by
     its last row and column, as torch's replicate padding does; a patch is kept when its
     variance over its 64*64*3 elements, the grey pixel repeated in the three channels,
     divided by 0.25, exceeds 0.001. The kept patches are a list, made on host: their
     number is the extent N of the second program, which shapes cannot compute.
  2. detector/7: the network on the N kept patches, its positions Gy[N] and Gx[N], the row
     and column of each patch, and the bias of each as a key, its only inputs with the
     page. The page goes to the device once and both programs read it there. The patches
     are padded to a multiple of 64 with keys of bias -1e30, which no query attends to:
     the program declares its rows as 64*K, whole tiles at every K, see detector_outputs/5.

The network, as music_deep's vit.py and detector.py write it:

  - patch embedding: LayerNorm(12288), Linear(12288, 192), LayerNorm(192), on the patch
    flattened as (row, column, channel), which an rgb page runs as written. The three
    channels of a grey page are the same value, so the layer norm of the 12288 elements is
    that of the 4096 pixels, the mean and the variance the same, and the gain of the first
    norm and the three channels fold into the linear weights once, on the device:
    [192, 4096] weights and a bias, see detector_model/3; the model keeps the full weights
    beside them;
  - 12 pre-norm transformer layers of 3 heads of 64: queries and keys rotated by PoPE, the
    magnitude softplus(q) at the phase of the patch's position, row frequencies in the
    first half, column ones in the second, a key of 128; attention as torch's
    scaled_dot_product_attention, scaled by 1/sqrt(128), the heads concatenated and
    projected out; a GELU MLP of 768; a last norm;
  - the heads: Linear, GELU, LayerNorm, Linear, each patch giving 5 shapes of the classes'
    logits, 4 numbers of geometry and 4 x 33 bins, whose softmax weighs the D-FINE
    function into a residual of each edge. A symbol is a box, x1 y1 x2 y2, around the patch
    center moved by the offset, of the size exp(clamp(s, -10, 10)), each edge moved by its
    residual times the size; a line, two endpoints from the patch center, sign(r) *
    (exp(|r|) - 1) each, moved by its residual times |base| + 1. Patch units, as torch's.

GELU is exact, as torch's: 0.5 x (1 + erf(x / sqrt 2)), by the erf of the library.

Each program is built once, its extents symbolic, the page's H and W and the K tiles of 64
kept patches, and compiled at its first run to a handle that serves every page after.

    detector_model(+Device, -Model, +Options)
        the weights of the file weights(File), detector_weights.safetensors of
        example_file/2 by default (beside this file, else downloaded), realized on Device, the embedding folded for grey pages, the
        hyper-parameters and class names of its metadata, and the two programs of each
        kind of page, built once, a dict: every page runs the same names, so that the
        handle a first run compiles serves every run after. A kind no page is of is never
        compiled. detector_model/2 is that of no option.
    detector_pages(-Pages, -References, +Options)
        the pages of the file pages(File), detector_pages.safetensors of example_file/2
        by default, int names on host, and for each what torch computed for it, a dict of the
        kept indices, the logits, boxes and keypoints. detector_pages/2 is that of no option.
    page_image(+File, -Image, +Options)
        a page from a safetensors file of images, with key(K), its key, `pages.0` by
        default.
    kept_patches(+Model, +Image, -Gy, -Gx)
        the rows and columns of the patches the variance drop keeps, lists of ints.
    detector(+Model, +Kind, -Image, -Gy, -Gx, -Bias, -Outs)
        the program of the pages of Kind, grey, Image [H, W], or rgb, Image [H, W, C], an
        int input, Gy, Gx [N] int inputs, N = 64*K, Bias [N] a float
        input added to the attention scores of each key, Outs a dict of names on host:
        sym_logits [N, 5, 83], sym_boxes [N, 5, 4], line_logits [N, 5, 8],
        line_keypoints [N, 5, 4], and sym_scores, sym_labels, line_scores, line_labels
        [N, 5], the sigmoid of the greatest logit and its class.
    detector_outputs(+Model, +Image, +Gy, +Gx, -Outs)
        the outputs of detector/6 for the page Image, realized on the model's device, at
        the kept patches Gy, Gx, padded to a multiple of 64 rows whose bias is -1e30: a
        dict of realized names on host, and kept: N, the rows of the patches.
    detect(+Model, +Image, -Detections, +Options)
        the detections of a page, symbol(Class, Score, X1, Y1, X2, Y2) and
        line(Class, Score, X1, Y1, X2, Y2) in pixels, clamped to the page as music_deep's
        inference does, best first: min_score(S), 0.5 by default, and max_symbols(K),
        max_lines(K), all by default.
    check_torch(+Options)
        every page of the pages file through both programs on device(D), pocl by default,
        against torch: the kept patches, and the greatest difference of each output; with
        detections(true), the detections of each page above the score too; weights(File)
        and pages(File) as above.

    ?- detector_model(nvidia, M), detector_pages([P | _], _),
       detect(M, P, Ds, [min_score(0.5)]), length(Ds, N).
*/

                 /*******************************
                 *            WEIGHTS           *
                 *******************************/

% detector_model(+Device, -Model, +Options): the weights realized on Device; the patch
% embedding's first norm and its linear layer folded into Embed, a dict of weight [D, P*P] and
% bias [D], for the grey pages; the programs of each kind of page, grey and rgb:
% programs(variance(Image, Var), program(Image, Gy, Gx, Bias, Outs)), of kept_patches/4 and of
% detector/7.
detector_model(Device, Model) :-
   detector_model(Device, Model, []).

detector_model(Device, Model, Options) :-
   data_option(weights(File), Options, 'detector_weights.safetensors'),
   safetensors_read(File, Host, Meta),
   on_device(Device, Host, Net, Names, []),
   realize(Names, [], [device(Device)]),
   config(Meta, Config),
   embedding(Net, Config, Embed),
   realize([Embed.weight, Embed.bias], [], [device(Device)]),
   Model0 = Config.put(_{net: Net, embed: Embed, device: Device}),
   maplist(programs(Model0), [grey, rgb], [Grey, Rgb]),
   Model = Model0.put(programs, _{grey: Grey, rgb: Rgb}).

programs(Model, Kind, programs(variance(VarImage, VarH), program(Image, Gy, Gx, Bias, Outs))) :-
   patch_variance(Model, Kind, VarImage, Var),
   copy(Var, VarH, host),
   detector(Model, Kind, Image, Gy, Gx, Bias, Outs).

config(Meta, Config) :-
   maplist(meta_number(Meta),
           [patch_size, channels, heads, dim_head, num_shapes, base_anchor_size, var_threshold],
           [P, C, Heads, Dh, Shapes, Anchor, Threshold]),
   maplist(meta_json(Meta), [symbol_classes, line_classes], [Symbols, Lines]),
   Config = _{patch: P, channels: C, heads: Heads, dim_head: Dh, shapes: Shapes,
              anchor: Anchor, threshold: Threshold, symbols: Symbols, lines: Lines}.

meta_number(Meta, Key, V) :-
   get_dict(Key, Meta, S),
   number_string(V, S).

meta_json(Meta, Key, V) :-
   get_dict(Key, Meta, S),
   atom_json_term(S, V, [value_string_as(atom)]).

% embedding(+Net, +Config, -Embed): LayerNorm(P*P*C) then Linear on a patch whose C channels
% are one grey value: the gain of the norm summed with the weights over the channels, and
% its bias through the weights into the bias of the layer.
embedding(Net, Config, _{weight: Wg, bias: Bg}) :-
   [Norm, Linear, _] = Net.backbone.patch_embed,
   P2 is Config.patch^2,
   C = Config.channels,
   shape(Linear.weight, [D, _]),
   Wg @= sum(reshape(Linear.weight, [D, P2, C]) * reshape(Norm.weight, [P2, C]), [axis(-1)]),
   Bg @= Linear.bias + sum(Linear.weight * Norm.bias, [axis(-1)]).

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

% data_option(+Option, +Options, +Default): the file of Option in Options, else the example
% file Default.
data_option(Option, Options, _), option(Option, Options) => true.
data_option(Option, _, Default) =>
   arg(1, Option, File),
   example_file(Default, File).

                 /*******************************
                 *             PAGES            *
                 *******************************/

% detector_pages(-Pages, -References, +Options): the pages of the pages file and, for each,
% torch's outputs.
detector_pages(Pages, References) :-
   detector_pages(Pages, References, []).

detector_pages(Pages, References, Options) :-
   data_option(pages(File), Options, 'detector_pages.safetensors'),
   safetensors_read(File, Tree, _),
   Pages = Tree.pages,
   length(Pages, K),
   numlist(1, K, Ks),
   maplist(reference(Tree), Ks, References).

reference(Tree, K1, Ref) :-
   K is K1 - 1,
   foldl(reference_entry(Tree, K), [kept, sym_logits, sym_boxes, line_logits, line_keypoints], _{}, Ref).

reference_entry(Tree, K, Key, R0, R) :-
   get_dict(Key, Tree, List),
   nth0(K, List, V),
   put_dict(Key, R0, V, R).

page_image(File, Image, Options) :-
   option(key(Key), Options, 'pages.0'),
   atomic_list_concat(Path, '.', Key),
   maplist(segment, Path, Segments),
   safetensors_read(File, Tree, _),
   foldl(subtree, Segments, Tree, Image).

segment(S, T), atom_number(S, N), integer(N) => T = N.
segment(S, T) => T = S.

subtree(K, T0, T), integer(K) => nth0(K, T0, T).
subtree(K, T0, T) => get_dict(K, T0, T).

                 /*******************************
                 *          PATCH DROP          *
                 *******************************/

% patch_variance(+Model, +Kind, -Image, -Var): Var[Gh, Gw] the variance of each patch of the
% page Image of Kind, padded by its last row and column to Gh*P rows and Gw*P columns, as
% torch's var over the patch's P*P*C elements, a grey value in each channel, divided by 0.25.
patch_variance(Model, Kind, Image, Var) :-
   P = Model.patch, C = Model.channels, Elements is P*P*C,
   page(Kind, C, Image, H, W),
   grid(H, P, Gh), grid(W, P, Gw),
   patch_element(Kind, Model, Image, H-W, Y-X, K, E, Element),
   over([Y:Gh, X:Gw, K:E], [Px[Y, X, K] := Element]),
   Scale is Elements / (Elements - 1) / 0.25,
   Var @= var(Px, [axis(-1)]) * Scale.

% page(+Kind, +C, -Image, -H, -W): Image an input of bytes, uint8 as an image file holds
% them, a page of Kind of H rows and W columns, of C channels when rgb.
page(Kind, C, Image, H, W) :-
   H::integer(1, 32768), W::integer(1, 32768),
   page_shape(Kind, C, H, W, Shape),
   shape(Image, Shape),
   type(Image, uint8).

page_shape(grey, _, H, W, Shape) => Shape = [H, W].
page_shape(rgb, C, H, W, Shape) => Shape = [H, W, C].

% page_kind(+Image, -Kind): the kind of the page Image, by its rank.
page_kind(Image, Kind) :-
   shape(Image, Shape),
   length(Shape, Rank),
   rank_kind(Rank, Kind).

rank_kind(2, Kind) => Kind = grey.
rank_kind(3, Kind) => Kind = rgb.

% patch_element(+Kind, +Model, +Image, +H-W, +Gy-Gx, +K, -E, -Element): Element the expression
% of the element K of the E of the patch at row Gy and column Gx of the page Image of H rows
% and W columns, in 0..1, clamped to the page: of a grey page one of its P*P pixels, of an rgb
% one, one of its P*P*C elements, as (row, column, channel).
patch_element(grey, Model, Image, H-W, Gy-Gx, K, E, Element) =>
   P = Model.patch, E is P*P,
   Element = Image[min(Gy*P + K // P, H - 1), min(Gx*P + K mod P, W - 1)] / 255.0.
patch_element(rgb, Model, Image, H-W, Gy-Gx, K, E, Element) =>
   P = Model.patch, C = Model.channels, Row is P*C, E is P*Row,
   Element = Image[min(Gy*P + K // Row, H - 1), min(Gx*P + K // C mod P, W - 1), K mod C] / 255.0.

% grid(+N, +P, -G): G patches of P cover N pixels, the last one padded: G = ceil(N / P).
grid(N, P, G) :-
   G::integer(1, 512),
   { G*P >= N, G*P =< N + P - 1 }.

% kept_patches(+Model, +Image, -Gy, -Gx): the rows and columns of the patches of the page
% whose variance exceeds the threshold, in row-major order, as torch keeps them.
kept_patches(Model, Image, Gy, Gx) :-
   page_kind(Image, Kind),
   programs(variance(In, VarH), _) = Model.programs.Kind,
   run(VarH, [In-Image], Values, [device(Model.device)]),
   shape(Image, [H, W | _]),
   Gw is (W + Model.patch - 1) // Model.patch,
   length(Values, Len),
   Len =:= Gw * ((H + Model.patch - 1) // Model.patch),
   T = Model.threshold,
   foldl(kept(T, Gw), Values, Kept, 0, _),
   exclude(==(none), Kept, Positions),
   pairs_keys_values(Positions, Gy, Gx).

% kept(+T, +Gw, +V, -K, +I0, -I): K the row and column of the patch I0 of variance V above T,
% else none.
kept(T, Gw, V, K, I0, I) :-
   I is I0 + 1,
   keep(V, T, Gw, I0, K).

keep(V, T, Gw, I0, K), V > T => Y is I0 // Gw, X is I0 mod Gw, K = Y-X.
keep(_, _, _, _, K) => K = none.

                 /*******************************
                 *            NETWORK           *
                 *******************************/

% detector(+Model, +Kind, -Image, -Gy, -Gx, -Bias, -Outs): the network on the kept patches of
% the page Image of Kind, at rows Gy and columns Gx; Bias[N] added to the scores of each key,
% 0 for a patch, -1e30 for a row of padding, which no patch then attends to; Outs on host.
% N is 64*Tiles, a multiple as the program states it: the library then stages and vectorises
% over the rows at every count of tiles. A name an over/2 defines has its shape declared:
% over/2 keeps the product, but would give its other axes new extents, bounded below only,
% where the declared numbers keep the program's constraints few.
detector(Model, Kind, Image, Gy, Gx, Bias, Outs) :-
   page(Kind, Model.channels, Image, H, W),
   Tiles::integer(1, 256),
   N = 64*Tiles,
   position(Gy, N, H),
   position(Gx, N, W),
   shape(Bias, [N]),
   patch_element(Kind, Model, Image, H-W, Gy[I]-Gx[I], K, E, Element),
   shape(X0, [N, E]),
   over([I:N, K:E], [X0[I, K] := Element]),
   Net = Model.net,
   embedded(Kind, Model, X0, E0),
   nth0(2, Net.backbone.patch_embed, Norm2),
   layer_norm(Norm2, E0, X1),
   rotation(Model, Gy, Gx, Rot),
   foldl(layer(Model, keys(Rot, Bias)), Net.backbone.transformer.layers, X1, X2),
   layer_norm(Net.backbone.transformer.norm, X2, T),
   length(Model.symbols, Cs),
   length(Model.lines, Cl),
   head(Model, Net.symbol_head, Cs, T, Rs, RelS),
   head(Model, Net.line_head, Cl, T, Rl, RelL),
   K5 = Model.shapes, A = Model.anchor,
   maplist({N, K5}/[G]>>shape(G, [N, K5, 4]), [Box, Base, Kp]),
   over([I:N, S:K5, J:4],
        [Box[I, S, J] := where(J mod 2 =:= 0, Rs[I, S, Cs] + Gx[I], Rs[I, S, Cs + 1] + Gy[I]) + 0.5
                         + where(J < 2, -1.0, 1.0) * A * exp(max(-10.0, min(10.0, Rs[I, S, Cs + 2 + J mod 2])))
                           * (0.5 + RelS[I, S, J])]),
   over([I:N, S:K5, J:4],
        [Base[I, S, J] := A * where(Rl[I, S, Cl + J] >= 0,
                                    exp(min(10.0, Rl[I, S, Cl + J])) - 1,
                                    1 - exp(min(10.0, -Rl[I, S, Cl + J])))]),
   over([I:N, S:K5, J:4],
        [Kp[I, S, J] := Base[I, S, J] + RelL[I, S, J] * (abs(Base[I, S, J]) + A)
                        + where(J mod 2 =:= 0, Gx[I], Gy[I]) + 0.5]),
   SymLogits @= Rs[_, _, 0:Cs],
   LineLogits @= Rl[_, _, 0:Cl],
   scores(SymLogits, SymScores, SymLabels),
   scores(LineLogits, LineScores, LineLabels),
   Device = _{sym_logits: SymLogits, sym_boxes: Box, line_logits: LineLogits, line_keypoints: Kp,
              sym_scores: SymScores, sym_labels: SymLabels,
              line_scores: LineScores, line_labels: LineLabels},
   dict_pairs(Device, Tag, Pairs),
   maplist([K-V, K-Vh]>>copy(V, Vh, host), Pairs, HostPairs),
   dict_pairs(Outs, Tag, HostPairs).

% embedded(+Kind, +Model, +X0, -E0): the first norm and the linear layer of the patch embedding
% on the patches X0: of a grey page, [N, P*P], by the folded weights; of an rgb one,
% [N, P*P*C], as the network writes them.
embedded(grey, Model, X0, E0) =>
   Embed = Model.embed,
   normalized(X0, X0n),
   E0 @= X0n @ matrix_transpose(Embed.weight) + Embed.bias.
embedded(rgb, Model, X0, E0) =>
   [Norm, Linear, _] = Model.net.backbone.patch_embed,
   layer_norm(Norm, X0, X0n),
   linear(Linear, X0n, E0).

% position(-G, +N, +Extent): G[N] an int input, a row or column of the patches of the page.
position(G, N, Extent) :-
   shape(G, [N]),
   kind(G, int),
   elements(G, 0-Extent).

scores(Logits, Scores, Labels) :-
   Scores @= 1 / (1 + exp(-max(Logits, [axis(-1)]))),
   Labels @= argmax(Logits, [axis(-1)]).

% normalized(+X, -Y): the rows of X less their mean, over their deviation, eps 1e-5.
normalized(X, Y) :-
   Rows = [axis(-1), keepdims(true)],
   Y @= (X - mean(X, Rows)) / sqrt(var(X, Rows) + 1.0e-5).

layer_norm(Norm, X, Y) :-
   normalized(X, Xn),
   Y @= Xn * Norm.weight + Norm.bias.

linear(Linear, X, Y) :-
   Y @= X @ matrix_transpose(Linear.weight) + Linear.bias.

% gelu(+X, -Y): Y = 0.5 X (1 + erf(X / sqrt 2)).
gelu(X, Y) :-
   Y @= 0.5 * X * (1 + erf(X / sqrt(2))).

% rotation(+Model, +Gy, +Gx, -Rot): Rot[N, 2*Dh], cos and sin of the phase of each patch at each
% frequency, interleaved: the phase of the first Dh/2 frequencies its row times them, of the
% others its column.
rotation(Model, Gy, Gx, Rot) :-
   Dh = Model.dim_head, Half is Dh // 2, R is 2*Dh,
   shape(Gy, [N]),
   numlist(1, Half, Is),
   maplist(frequency(Half), Is, Fs),
   Inv @= asarray(Fs),
   shape(Ph, [N, Dh]), shape(Rot, [N, R]),
   over([I:N, D:Dh], [Ph[I, D] := where(D < Half, Gy[I] * Inv[D mod Half], Gx[I] * Inv[D mod Half])]),
   over([I:N, E:R], [Rot[I, E] := where(E mod 2 =:= 0, cos(Ph[I, E // 2]), sin(Ph[I, E // 2]))]).

frequency(Half, I, F) :-
   F is 1 / 10000.0 ** ((I - 1) / Half).

% layer(+Model, +Keys, +Layer, +X, -Y): a pre-norm transformer layer, attention then MLP; Keys
% is keys(Rot, Bias), the rotations of the patches and the bias of their scores as keys.
layer(Model, Keys, [Attn, FF], X, Y) :-
   attention(Model, Keys, Attn, X, X1),
   get_dict(net, FF, Net),
   get_dict(0, Net, Norm), get_dict(1, Net, L1), get_dict(4, Net, L2),
   layer_norm(Norm, X1, X1n),
   linear(L1, X1n, H0),
   gelu(H0, H1),
   linear(L2, H1, H2),
   Y @= H2 + X1.

% attention(+Model, +Keys, +Attn, +X, -Y): the attention of the layer, its heads concatenated
% and projected out, as torch does.
attention(Model, Keys, Attn, X, Y) :-
   layer_norm(Attn.norm, X, Xn),
   Qkv @= Xn @ matrix_transpose(Attn.to_qkv.weight),
   numlist(1, Model.heads, Hs),
   maplist(head_attention(Model, Keys, Qkv), Hs, Os),
   [Out] = Attn.to_out,
   O @= concat(Os, [axis(1)]),
   linear(Out, O, P),
   Y @= P + X.

% head_attention(+Model, +Keys, +Qkv, +H1, -O): the attention of the head H1 (from 1), its
% queries and keys rotated, its scores [N, N] the one square name of the layer.
head_attention(Model, keys(Rot, Bias), Qkv, H1, O) :-
   Dh = Model.dim_head, R is 2*Dh, Inner is Model.heads * Dh,
   Oq is (H1 - 1)*Dh, Ok is Inner + Oq, Ov is 2*Inner + Oq, Ov1 is Ov + Dh,
   Scale is 1 / sqrt(R),
   shape(Qkv, [N, _]),
   pope(Qkv, Rot, Oq, N, R, Q),
   pope(Qkv, Rot, Ok, N, R, K),
   S @= Q @ matrix_transpose(K) * Scale + Bias,
   Rows = [axis(-1), keepdims(true)],
   Ex @= exp(S - max(S, Rows)),
   O @= (Ex @ Qkv[_, Ov:Ov1]) / sum(Ex, Rows).

% pope(+Qkv, +Rot, +Off, +N, +R, -Q): the R/2 columns of Qkv from Off, their softplus, the
% magnitude, at the phases of Rot: Q[I, 2D] = |q| cos, Q[I, 2D+1] = |q| sin.
pope(Qkv, Rot, Off, N, R, Q) :-
   Vq = Qkv[I, Off + E // 2],
   shape(Q, [N, R]),
   over([I:N, E:R], [Q[I, E] := where(Vq > 20, Vq, log(1 + exp(Vq))) * Rot[I, E]]).

% head(+Model, +Head, +C, +T, -R, -Rel): the MLP of a head, R[N, K, C + 4 + 4*Bins] its
% predictions per shape, Rel[N, K, 4] the residual of each edge, the D-FINE function weighed
% by the softmax of its bins.
head(Model, Head, C, T, R, Rel) :-
   Mlp = Head.mlp,
   get_dict(0, Mlp, L0), get_dict(2, Mlp, Norm), get_dict(3, Mlp, L3),
   linear(L0, T, H0),
   gelu(H0, H1),
   layer_norm(Norm, H1, H2),
   linear(L3, H2, R0),
   W = Head.weighting_fn.w,
   shape(W, [Bins]),
   K = Model.shapes,
   Pps is C + 4 + 4*Bins,
   shape(T, [N, _]),
   R @= reshape(R0, [N, K, Pps]),
   C4 is C + 4,
   Edges @= reshape(R[_, _, C4:Pps], [N, K, 4, Bins]),
   Rows = [axis(-1), keepdims(true)],
   Ex @= exp(Edges - max(Edges, Rows)),
   Rel @= sum(Ex * W, [axis(-1)]) / sum(Ex, [axis(-1)]).

                 /*******************************
                 *           INFERENCE          *
                 *******************************/

% detector_outputs(+Model, +Image, +Gy, +Gx, -Results): the outputs of the network on the page,
% a dict of realized names on host, by one handle for all of them, compiled at the first call,
% and kept: N, the number of patches. The patches are padded to a multiple of 64 rows, at
% the position 0, 0, keys of no weight: the program's rows are 64*K, which the handle binds
% from the data, and the kernels of the library take their fast path, a reduction staged and
% vectorised, on whole tiles: one handle for every page, a page of 891 patches in 0.41 s on a
% Quadro M1200, where an extent N of no declared multiple ran in 2.25 s. The outputs hold the
% rows of padding after the N of the patches, see rows/4.
detector_outputs(Model, Image, Gy, Gx, Results) :-
   page_kind(Image, Kind),
   programs(_, program(In, Gyn, Gxn, Biasn, Outs)) = Model.programs.Kind,
   length(Gy, N),
   Np is (N + 63) // 64 * 64,
   Pad is Np - N,
   length(Zeros, Pad), maplist(=(0), Zeros),
   append(Gy, Zeros, Gyp), append(Gx, Zeros, Gxp),
   length(Ones, N), maplist(=(0.0), Ones),
   length(Off, Pad), maplist(=(-1.0e30), Off),
   append(Ones, Off, Bias),
   dict_pairs(Outs, Tag, Pairs),
   pairs_keys_values(Pairs, Keys, Names),
   run_all(Names, [In-Image, Gyn-Gyp, Gxn-Gxp, Biasn-Bias], Values, [device(Model.device)]),
   pairs_keys_values(Results0, Keys, Values),
   dict_pairs(Results1, Tag, Results0),
   Results = Results1.put(kept, N).

% rows(+Outs, +Key, +Type, -Values): the elements of the output Key of the kept patches, the
% rows of padding left out.
rows(Outs, Key, Type, Values) :-
   get_dict(Key, Outs, Name),
   host_elements(Name, Type, All),
   shape(Name, [_ | Row]),
   foldl([E, P0, P]>>(P is P0*E), Row, 1, PerRow),
   Len is Outs.kept * PerRow,
   length(Values, Len),
   append(Values, _, All).

% detect(+Model, +Image, -Detections, +Options): the detections of the page Image, a name on
% host or on the model's device.
detect(Model, Image0, Detections, Options) :-
   on_model_device(Model, Image0, Image),
   kept_patches(Model, Image, Gy, Gx),
   detector_outputs(Model, Image, Gy, Gx, Outs),
   detections(Model, Image, Outs, Detections, Options).

% detections(+Model, +Image, +Outs, -Detections, +Options): the symbols then the lines of the
% outputs Outs of the page Image, each best first.
detections(Model, Image, Outs, Detections, Options) :-
   option(min_score(Min), Options, 0.5),
   shape(Image, [H, W | _]),
   Page = page(Model.patch, Min, H, W),
   detections(symbol, Model.symbols, Outs, [sym_scores, sym_labels, sym_boxes], Page, Syms),
   detections(line, Model.lines, Outs, [line_scores, line_labels, line_keypoints], Page, Lines),
   best(Syms, max_symbols, Options, Syms1),
   best(Lines, max_lines, Options, Lines1),
   append(Syms1, Lines1, Detections).

% on_model_device(+Model, +Image0, -Image): the page realized on the model's device.
on_model_device(Model, Image0, Image) :-
   device(Image0, D),
   on_device(D, Model.device, Image0, Image).

on_device(D, Device, Image0, Image), D == Device => Image = Image0.
on_device(_, Device, Image0, Image) =>
   copy(Image0, Image, Device),
   realize([Image], [], [device(Device)]).

detections(What, Classes, Outs, [Scores, Labels, Geometry], Page, Ds) :-
   rows(Outs, Scores, float32, Ss),
   rows(Outs, Labels, int32, Ls),
   rows(Outs, Geometry, float32, Gs),
   rows4(Gs, Rows),
   foldl(detection(What, Classes, Page), Ss, Ls, Rows, Ds0, []),
   sort(1, @>=, Ds0, Ds1),
   pairs_values(Ds1, Ds).

% detection(+What, +Classes, +Page, +Score, +Label, +Geometry, -Ds0, ?Ds): a detection of
% Score at least the page's minimum, in pixels: a symbol's box clamped as music_deep's COCO
% boxes are, x1 and y1 within the page and the width and height within what remains, a line's
% two endpoints each within the page.
detection(_, _, page(_, Min, _, _), S, _, _, Ds0, Ds), S < Min => Ds0 = Ds.
detection(What, Classes, page(P, _, H, W), S, L, [X1, Y1, X2, Y2], Ds0, Ds) =>
   nth0(L, Classes, Class),
   clamp(X1*P, 0.0, W, Cx1), clamp(Y1*P, 0.0, H, Cy1),
   endpoint(What, X1*P-X2*P, Cx1, W, Cx2),
   endpoint(What, Y1*P-Y2*P, Cy1, H, Cy2),
   D =.. [What, Class, S, Cx1, Cy1, Cx2, Cy2],
   Ds0 = [S-D | Ds].

endpoint(symbol, A-B, C1, Hi, C2) => clamp(B - A, 0.0, Hi - C1, Extent), C2 is C1 + Extent.
endpoint(line, _-B, _, Hi, C2) => clamp(B, 0.0, Hi, C2).

clamp(V, Lo, Hi, C) :-
   C is max(Lo, min(V, float(Hi))).

rows4([], Rows) => Rows = [].
rows4([A, B, C, D | T], Rows) => Rows = [[A, B, C, D] | Rows1], rows4(T, Rows1).

% best(+Ds, +Key, +Options, -Best): the first K of Ds with the option Key(K), else all of them.
best(Ds, Key, Options, Best) :-
   Opt =.. [Key, K],
   option(Opt, Options, all),
   take(K, Ds, Best).

take(all, Ds, Best) => Best = Ds.
take(K, Ds, Best) =>
   length(Ds, Len),
   Take is min(K, Len),
   length(Best, Take),
   append(Best, _, Ds).

% host_elements(+Name, +Type, -Values): the elements of a realized name on host, row-major.
host_elements(Name, Type, Values) :-
   value(Name, Buffer),
   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, _, Values).

                 /*******************************
                 *        AGAINST TORCH         *
                 *******************************/

% check_torch(+Options): every page of the pages file against torch's outputs.
check_torch(Options) :-
   option(device(Device), Options, pocl),
   detector_model(Device, Model, Options),
   detector_pages(Pages, Refs, Options),
   foldl(check_page(Model, Options), Pages, Refs, 0, _).

check_page(Model, Options, Page, Ref, K, K1) :-
   K1 is K + 1,
   shape(Page, [H, W | _]),
   page_kind(Page, Kind),
   format("page ~d: ~d x ~d, ~w~n", [K, H, W, Kind]),
   on_model_device(Model, Page, Image),
   timed(kept_patches(Model, Image, Gy, Gx), T0),
   host_elements(Ref.kept, int32, Kept),
   Gw is (W + Model.patch - 1) // Model.patch,
   maplist({Gw}/[Y, X, I]>>(I is Y*Gw + X), Gy, Gx, Mine),
   length(Mine, N), length(Kept, Nt),
   format("  kept ~d patches, torch ~d, ~3f s~n", [N, Nt, T0]),
   check_outputs(Mine, Kept, Model, Image, Gy, Gx, Ref, Options).

% check_outputs(+Mine, +Kept, ...): the outputs against torch's, when both keep the same patches.
check_outputs(Mine, Kept, _, _, _, _, _, _), Mine \== Kept =>
   format("  the kept patches differ from torch's, the outputs are not compared~n").
check_outputs(_, _, Model, Image, Gy, Gx, Ref, Options) =>
   timed(detector_outputs(Model, Image, Gy, Gx, Outs), T1),
   format("  network ~3f s (the first run of a process compiles)~n", [T1]),
   forall(member(Key, [sym_logits, sym_boxes, line_logits, line_keypoints]),
          compare_output(Ref, Outs, Key)),
   option(detections(Show), Options, false),
   show_detections(Show, Model, Image, Outs, Options).

show_detections(false, _, _, _, _) => true.
show_detections(true, Model, Image, Outs, Options) =>
   detections(Model, Image, Outs, Ds, Options),
   length(Ds, Nd),
   format("  ~d detections~n", [Nd]),
   forall(member(D, Ds), format("    ~p~n", [D])).

compare_output(Ref, Outs, Key) :-
   rows(Outs, Key, float32, Mine),
   host_elements(Ref.Key, float32, Torch),
   foldl([A, B, E0-M0, E-M]>>( E is max(E0, abs(A - B)), M is max(M0, abs(B)) ), Mine, Torch, 0-0, Err-Max),
   format("  ~w: max error ~e, max |torch| ~3f~n", [Key, Err, Max]).

timed(Goal, Wall) :-
   get_time(T0),
   call(Goal),
   get_time(T1),
   Wall is T1 - T0.
