File size: 6,332 Bytes
6a8ca2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
// jev-backbone: the Jeveration backbone pass (jeveration/backbone.py: backbone_forward) on a GGUF model.
//
// One request = one forward pass of the reference code, done in two llama.cpp passes:
//   pass 1 (causal)     the prefix (prompt tokens, and image embeddings for dense / image-to-image) -> KV cache + recurrent state
//   pass 2 (non-causal) the decision tokens / spatial queries                                       -> final hidden states
// In pass 2 these tokens see the whole cached prefix and each other in both directions in the full-attention layers,
// which is the mask of backbone_forward. The linear-attention layers are causal in both passes.
// Image tokens share their t position; llama.cpp then masks them causally in raster (y, x) order, as the reference does.
//
// Protocol (stdin/stdout, little-endian, persistent process):
//   startup -> int32 n_embd
//   request <- int32 n1, int32 n2,
//              (n1 + n2) x int32[4] entries {token, t, y, x}   token = -1: an embedding entry
//              float32 embd[n_embd] for every embedding entry, in entry order
//   reply   -> int32 status (0 = ok), float32 hidden[n2 * n_embd] (the pass-2 entries, in order)
// Logs go to stderr.
//
// usage: jev-backbone MODEL.gguf [n_threads] [n_ubatch]   (n_ubatch >= the number of pass-2 entries)

#include "llama.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>

struct entry { int32_t tok, t, y, x; };

static bool read_all(void * dst, size_t n) { return fread(dst, 1, n, stdin) == n; }
static void write_all(const void * src, size_t n) { fwrite(src, 1, n, stdout); }

// add entries [i0, i1) to the batch; embd points at the embedding of the first embedding entry in the range
static int fill(llama_batch_ext * b, const std::vector<entry> & es, int i0, int i1, const float *& embd, int n_embd, bool out) {
    for (int i = i0; i < i1; ++i) {
        const entry & e = es[i];
        int idx;
        if (e.tok >= 0) {
            idx = llama_batch_ext_add_token(b, 0, e.tok);
            if (idx < 0 || !llama_batch_ext_set_pos(b, idx, &e.t)) return -1;
        } else {
            idx = llama_batch_ext_add_embd(b, 0, llama_embd{ embd, 1, (size_t) n_embd });
            embd += n_embd;
            const llama_pos pos[4] = { e.t, e.y, e.x, 0 };
            if (idx < 0 || !llama_batch_ext_set_pos(b, idx, pos)) return -1;
        }
        llama_batch_ext_set_output_embd(b, idx, out);
    }
    return 0;
}

static int run(llama_context * ctx, int n_embd, int n_batch, const std::vector<entry> & es, int n1, const std::vector<float> & embd,
               std::vector<float> & out) {
    llama_memory_clear(llama_get_memory(ctx), true);
    const int n2 = (int) es.size() - n1;
    const float * e = embd.data();
    llama_batch_ext * b = llama_batch_ext_init(ctx);

    // pass 1: prefix, causal, in chunks of n_batch
    llama_set_causal_attn(ctx, true);
    for (int i0 = 0; i0 < n1; i0 += n_batch) {
        llama_batch_ext_clear(b);
        const int i1 = i0 + n_batch < n1 ? i0 + n_batch : n1;
        if (fill(b, es, i0, i1, e, n_embd, false) != 0) { fprintf(stderr, "bad prefix entry\n"); llama_batch_ext_free(b); return 1; }
        const int rc = llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, b);
        if (rc != 0) { fprintf(stderr, "prefix pass failed: %d\n", rc); llama_batch_ext_free(b); return 2; }
    }

    // pass 2: decision tokens / queries, non-causal, one batch
    llama_batch_ext_clear(b);
    llama_set_causal_attn(ctx, false);
    if (fill(b, es, n1, n1 + n2, e, n_embd, true) != 0) { fprintf(stderr, "bad decision entry\n"); llama_batch_ext_free(b); return 3; }
    const int rc = llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, b);
    llama_batch_ext_free(b);
    if (rc != 0) { fprintf(stderr, "decision pass failed: %d\n", rc); return 4; }

    out.resize((size_t) n2 * n_embd);
    for (int i = 0; i < n2; ++i) {
        const float * h = llama_get_embeddings_ith(ctx, i);
        if (!h) { fprintf(stderr, "no embedding for %d\n", i); return 5; }
        memcpy(out.data() + (size_t) i * n_embd, h, sizeof(float) * n_embd);
    }
    return 0;
}

int main(int argc, char ** argv) {
    if (argc < 2) { fprintf(stderr, "usage: %s MODEL.gguf [n_threads] [n_ubatch]\n", argv[0]); return 1; }
    const int n_threads = argc > 2 ? atoi(argv[2]) : 4;
    const int n_ubatch = argc > 3 ? atoi(argv[3]) : 256;

    llama_backend_init();
    llama_model_params mp = llama_model_default_params();
    mp.load_mode = LLAMA_LOAD_MODE_NONE;   // read once into RAM: with mmap, repacked tensors also stay resident as file pages
    llama_model * model = llama_model_load_from_file(argv[1], mp);
    if (!model) { fprintf(stderr, "cannot load %s\n", argv[1]); return 1; }

    llama_context_params cp = llama_context_default_params();
    cp.n_ctx = 1536;            // dense: ~500-token prefix + 432 queries; text-to-image: ~150 + 128
    cp.n_batch = n_ubatch;
    cp.n_ubatch = n_ubatch;     // the non-causal pass must fit in one ubatch
    cp.n_seq_max = 1;
    cp.embeddings = true;
    cp.pooling_type = LLAMA_POOLING_TYPE_NONE;
    cp.n_threads = cp.n_threads_batch = n_threads;
    llama_context * ctx = llama_init_from_model(model, cp);
    if (!ctx) { fprintf(stderr, "cannot create context\n"); return 1; }

    const int32_t n_embd = llama_model_n_embd(model);
    write_all(&n_embd, sizeof n_embd);
    fflush(stdout);

    std::vector<entry> es;
    std::vector<float> embd, out;
    for (;;) {
        int32_t hdr[2];
        if (!read_all(hdr, sizeof hdr)) break;           // EOF: done
        const int n1 = hdr[0], n2 = hdr[1];
        es.resize(n1 + n2);
        if (!read_all(es.data(), sizeof(entry) * es.size())) break;
        size_t n_e = 0;
        for (const auto & x : es) n_e += x.tok < 0;
        embd.resize(n_e * n_embd);
        if (!read_all(embd.data(), sizeof(float) * embd.size())) break;
        int32_t status = n2 > n_ubatch ? 6 : run(ctx, n_embd, n_ubatch, es, n1, embd, out);
        if (status == 6) fprintf(stderr, "%d decision entries > n_ubatch %d\n", n2, n_ubatch);
        write_all(&status, sizeof status);
        if (status == 0) write_all(out.data(), sizeof(float) * out.size());
        fflush(stdout);
    }

    llama_free(ctx);
    llama_model_free(model);
    llama_backend_free();
    return 0;
}