File size: 24,427 Bytes
68888be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// Unit tests of the building blocks. No test framework: a failing check prints
// its line and the process exits with code 1.
//
//   hk_unit_tests            run everything
//   hk_unit_tests io planes  run the named groups
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <numeric>
#include <string>
#include <unordered_map>
#include <vector>

#include "cli/args.h"
#include "common/base.h"
#include "common/json.h"
#include "common/numeric.h"
#include "common/threads.h"
#include "format/planes.h"
#include "gpu/device_arena.h"
#include "gpu/selftest.h"
#include "io/file_io.h"
#include "io/os_info.h"
#include "loop/day_loop.h"
#include "loop/draft_loop.h"
#include "tokenizer/tokenizer.h"

using namespace hk;

static int g_checks = 0, g_failed = 0;

#define EXPECT(cond)                                                   \
    do {                                                               \
        ++g_checks;                                                    \
        if (!(cond)) {                                                 \
            ++g_failed;                                                \
            printf("    FAILED %s:%d: %s\n", __FILE__, __LINE__, #cond); \
        }                                                              \
    } while (0)

// ---- json -------------------------------------------------------------------------

static void test_json() {
    Json j = Json::parse(R"({"a": 1, "big": 9007199254740993, "neg": -5, "f": 1.5e3, "s": "x\ny\u00e9\ud83d\ude00", "n": null,
                             "t": true, "arr": [1, [2, 3], {"k": "v"}], "empty": {}, "e2": []})");
    EXPECT(j.at("a").as_int() == 1);
    EXPECT(j.at("big").as_int() == 9007199254740993ll);   // past 2^53: must not go through a double
    EXPECT(j.at("neg").as_int() == -5);
    EXPECT(j.at("f").as_num() == 1500.0);
    EXPECT(j.at("s").as_str() == "x\ny\xc3\xa9\xf0\x9f\x98\x80");
    EXPECT(j.get_int("n", 7) == 7);                        // null counts as absent
    EXPECT(j.get_int("missing", 9) == 9);
    EXPECT(j.at("t").as_bool());
    EXPECT(j.at("arr").size() == 3 && j.at("arr")[1][1].as_int() == 3 && j.at("arr")[2].at("k").as_str() == "v");
    Json back = Json::parse(j.dump());
    EXPECT(back.dump() == j.dump());
    EXPECT(Json::parse(j.dump(2)).dump() == j.dump());
    EXPECT(back.at("big").as_int() == 9007199254740993ll);
    bool threw = false;
    try {
        Json::parse("{\"a\": }");
    } catch (const Error&) {
        threw = true;
    }
    EXPECT(threw);
    Json o = Json::object();
    o.set("k", 1);
    o.set("k", 2);
    EXPECT(o.size() == 1 && o.at("k").as_int() == 2);
}

// ---- number formats -----------------------------------------------------------------

static void test_numeric() {
    for (float v : {0.0f, 1.0f, -1.0f, 0.5f, 3.140625f, -1024.0f, 1e-20f, 6.5e30f}) {
        EXPECT(bf16_to_f32(f32_to_bf16(v)) == v || std::fabs(bf16_to_f32(f32_to_bf16(v)) - v) <= std::fabs(v) / 128.0f);
        if (std::fabs(v) < 60000.0f && (v == 0.0f || std::fabs(v) > 1e-4f)) EXPECT(std::fabs(f16_to_f32(f32_to_f16(v)) - v) <= std::fabs(v) / 1024.0f);
    }
    EXPECT(bf16_to_f32(0x3F80) == 1.0f && bf16_to_f32(0xC000) == -2.0f);
    EXPECT(f16_to_f32(0x3C00) == 1.0f && f16_to_f32(0xC000) == -2.0f && f16_to_f32(0x0001) > 0.0f);
    EXPECT(e8m0_to_f32(127) == 1.0f && e8m0_to_f32(128) == 2.0f && e8m0_to_f32(126) == 0.5f && e8m0_to_f32(0) == 0.0f);
    uint8_t b[8];
    store_le64(b, 0x0102030405060708ull);
    EXPECT(b[0] == 8 && b[7] == 1 && load_le64(b) == 0x0102030405060708ull && load_le32(b) == 0x05060708u && load_le16(b) == 0x0708);
}

// ---- bit planes -----------------------------------------------------------------------

static void test_planes() {
    Rng rng(42);
    const int rows = 6, cols = 96;
    std::vector<uint8_t> packed((size_t)rows * cols / 2), scales((size_t)rows * cols / 32);
    for (auto& x : packed) x = (uint8_t)rng.below(256);
    for (auto& x : scales) x = (uint8_t)(120 + rng.below(12));
    const size_t pb = (size_t)rows * cols / 8;
    std::vector<uint8_t> p0(pb), p1(pb), p2(pb), p3(pb), again(packed.size());
    mxfp4_nibbles_to_planes(packed.data(), rows, cols, p0.data(), p1.data(), p2.data(), p3.data());
    mxfp4_planes_to_nibbles(p0.data(), p1.data(), p2.data(), p3.data(), rows, cols, again.data());
    EXPECT(again == packed);   // the bit-plane rewrite loses nothing

    // Decoding the planes gives the MXFP4 values: sign * {0, .5, 1, 1.5, 2, 3, 4, 6} * 2^(e - 127).
    PlanesDesc d;
    d.rows = rows;
    d.cols = cols;
    planes_set_mxfp4(d);
    PlanesView v;
    v.scales = scales.data();
    v.planes[0] = p0.data();
    v.planes[1] = p1.data();
    v.planes[2] = p2.data();
    v.planes[3] = p3.data();
    std::vector<float> row((size_t)cols);
    bool same = true;
    for (int r = 0; r < rows; ++r) {
        planes_decode_row(d, v, r, row.data());
        for (int c = 0; c < cols; ++c) {
            const uint8_t byte = packed[((size_t)r * cols + c) / 2];
            const uint8_t nib = (c & 1) ? (byte >> 4) : (byte & 15);
            const float want = ((nib & 8) ? -1.0f : 1.0f) * kE2M1[nib & 7] * e8m0_to_f32(scales[(size_t)r * (cols / 32) + c / 32]);
            same = same && row[(size_t)c] == want;
        }
    }
    EXPECT(same);

    // fewer planes: the error grows as planes are dropped, and the signs alone still carry the direction
    double hist[8] = {};
    mxfp4_accumulate_hist(packed.data(), scales.data(), rows, cols, hist);
    std::vector<float> full((size_t)cols), part((size_t)cols);
    double err_prev = 0;
    for (int np = 3; np >= 1; --np) {
        PlanesDesc t = d;
        t.nplanes = np;
        mxfp4_truncated_lut(hist, np, t.lut);
        double err = 0, dot = 0;
        for (int r = 0; r < rows; ++r) {
            planes_decode_row(d, v, r, full.data());
            planes_decode_row(t, v, r, part.data());
            for (int c = 0; c < cols; ++c) {
                err += (double)(full[(size_t)c] - part[(size_t)c]) * (full[(size_t)c] - part[(size_t)c]);
                dot += (double)full[(size_t)c] * part[(size_t)c];
            }
        }
        EXPECT(err >= err_prev && dot > 0);
        err_prev = err;
    }

    // Float -> MXFP4 -> float is exact for values MXFP4 can represent.
    std::vector<float> w((size_t)cols);
    for (int c = 0; c < cols; ++c) w[(size_t)c] = ((c % 3) ? 1.0f : -1.0f) * kE2M1[(size_t)rng.below(8)] * 0.25f;
    std::vector<uint8_t> qs((size_t)cols / 32), qp((size_t)cols / 2), q0((size_t)cols / 8), q1(q0), q2(q0), q3(q0);
    mxfp4_quantize_row(w.data(), cols, qs.data(), qp.data());
    mxfp4_nibbles_to_planes(qp.data(), 1, cols, q0.data(), q1.data(), q2.data(), q3.data());
    PlanesDesc d1 = d;
    d1.rows = 1;
    PlanesView v1;
    v1.scales = qs.data();
    v1.planes[0] = q0.data();
    v1.planes[1] = q1.data();
    v1.planes[2] = q2.data();
    v1.planes[3] = q3.data();
    planes_decode_row(d1, v1, 0, row.data());
    bool exact = true;
    for (int c = 0; c < cols; ++c) exact = exact && row[(size_t)c] == w[(size_t)c];
    EXPECT(exact);

}

// ---- file reading ------------------------------------------------------------------------

static void test_io() {
    namespace fs = std::filesystem;
    const std::string path = (fs::temp_directory_path() / ("hk_io_test_" + std::to_string((unsigned long long)now_sec()) + ".bin")).u8string();
    const int64_t size = 3 * 1024 * 1024 + 1234;   // not a multiple of the 4 KB block
    std::vector<uint8_t> data((size_t)size);
    Rng rng(7);
    for (auto& x : data) x = (uint8_t)rng.next();
    {
        std::ofstream f(fs::u8path(path), std::ios::binary);
        f.write((const char*)data.data(), (std::streamsize)data.size());
    }
    for (const char* engine : {"auto", "threads", "uring", "iocp"}) {
        for (bool direct : {true, false}) {
            IoOptions o;
            o.engine = engine;
            o.direct = direct;
            std::unique_ptr<IoEngine> io;
            try {
                io = IoEngine::create(o);
            } catch (const Error&) {
                continue;   // this engine does not exist on this OS
            }
            int f = io->open(path);
            EXPECT(io->file_size(f) == size);
            // Unaligned ranges, including the last partial block.
            bool ok = true;
            for (int i = 0; i < 40; ++i) {
                int64_t off = (int64_t)rng.below((uint64_t)size - 1);
                int64_t len = 1 + (int64_t)rng.below((uint64_t)std::min<int64_t>(size - off, 300000));
                if (i == 0) {
                    off = size - 5000;
                    len = 5000;
                }
                std::vector<uint8_t> got((size_t)len);
                io->read_range(f, off, len, got.data());
                ok = ok && memcmp(got.data(), data.data() + off, (size_t)len) == 0;
            }
            EXPECT(ok);
            // Many aligned reads in flight, completions in any order.
            const int n = 48;
            const int64_t blk = 8 * kIoAlign;
            std::vector<AlignedBuf> bufs((size_t)n);
            int submitted = 0, done = 0;
            bool match = true;
            IoCompletion comp[16];
            while (done < n) {
                while (submitted < n && io->in_flight() < 16) {
                    bufs[(size_t)submitted].resize(blk);
                    IoRequest r;
                    r.file = f;
                    r.offset = align_down((int64_t)rng.below((uint64_t)(size - blk)));
                    r.len = blk;
                    r.dst = bufs[(size_t)submitted].data();
                    r.tag = ((uint64_t)r.offset << 8) | (uint64_t)submitted;
                    io->submit(r);
                    ++submitted;
                }
                int k = io->wait(comp, 16, 1);
                for (int i = 0; i < k; ++i) {
                    const int idx = (int)(comp[i].tag & 255);
                    const int64_t off = (int64_t)(comp[i].tag >> 8);
                    match = match && comp[i].error == 0 && comp[i].bytes == blk &&
                            memcmp(bufs[(size_t)idx].data(), data.data() + off, (size_t)blk) == 0;
                    ++done;
                }
            }
            EXPECT(match);
            printf("    %-7s -> engine %-7s %s\n", engine, io->name(), io->is_direct(f) ? "direct" : "buffered");
        }
    }
    std::error_code ec;
    fs::remove(fs::u8path(path), ec);

    // what the system says is free: known on Linux and Windows, and never more than there is
    const int64_t ram_total = system_ram_bytes(), ram_free = system_ram_free_bytes();
#if defined(__linux__) || defined(_WIN32)
    EXPECT(ram_total > 0 && ram_free > 0 && ram_free <= ram_total);
#else
    EXPECT(ram_free == -1 || (ram_free > 0 && ram_free <= ram_total));
#endif
    printf("    RAM: %s, of which free %s\n", human_bytes((double)ram_total).c_str(), human_bytes((double)ram_free).c_str());

    // the RAM peak goes up when memory is taken and used, and does not come down when it is given back
    const int64_t peak0 = process_ram_peak_bytes();
    EXPECT(peak0 > 0);
    const size_t take = (size_t)96 << 20;
    {
        std::vector<uint8_t> big(take);
        for (size_t i = 0; i < big.size(); i += 1024) big[i] = (uint8_t)(i >> 10);
        size_t sum = 0;
        for (size_t i = 0; i < big.size(); i += 4096) sum += big[i];
        EXPECT(sum > 0);
    }
    const int64_t peak1 = process_ram_peak_bytes();
    EXPECT(peak1 >= peak0 + (int64_t)(take / 2) && peak1 <= peak0 + (int64_t)(2 * take));
    printf("    this process held at most %s, then %s after using %s more\n", human_bytes((double)peak0).c_str(),
           human_bytes((double)peak1).c_str(), human_bytes((double)take).c_str());
}

// ---- threads ------------------------------------------------------------------------------------

static void test_threads() {
    std::vector<int> hits(10007, 0);
    parallel_for((int64_t)hits.size(), 64, [&](int64_t b, int64_t e) {
        for (int64_t i = b; i < e; ++i) ++hits[(size_t)i];
    });
    EXPECT(std::accumulate(hits.begin(), hits.end(), 0) == (int)hits.size() && *std::min_element(hits.begin(), hits.end()) == 1);
    // Nested calls must not deadlock.
    std::vector<int> inner(64 * 64, 0);
    parallel_for(64, 1, [&](int64_t b, int64_t e) {
        for (int64_t i = b; i < e; ++i)
            parallel_for(64, 8, [&](int64_t b2, int64_t e2) {
                for (int64_t j = b2; j < e2; ++j) ++inner[(size_t)(i * 64 + j)];
            });
    });
    EXPECT(std::accumulate(inner.begin(), inner.end(), 0) == 64 * 64);
    // An exception in a worker reaches the caller.
    bool threw = false;
    try {
        parallel_for(1000, 1, [&](int64_t b, int64_t) {
            if (b == 500) HK_FAIL("boom");
        });
    } catch (const Error&) {
        threw = true;
    }
    EXPECT(threw);
    parallel_for(0, 1, [&](int64_t, int64_t) { EXPECT(false); });
}

// ---- pre-tokenizer ----------------------------------------------------------------------------------

static std::vector<std::string> pieces(const std::string& s) {
    std::vector<std::string> out;
    size_t i = 0;
    while (i < s.size()) {
        size_t n = pretok_next((const uint8_t*)s.data() + i, s.size() - i);
        out.push_back(s.substr(i, n));
        i += n;
    }
    return out;
}

static void test_pretok() {
    using V = std::vector<std::string>;
    EXPECT(pieces("Hello world") == (V{"Hello", " world"}));
    EXPECT(pieces("I'm here, DON'T") == (V{"I'm", " here", ",", " DON'T"}));
    EXPECT(pieces("12345") == (V{"123", "45"}));                     // digits go three at a time
    EXPECT(pieces("parseJSON") == (V{"parse", "JSON"}));             // a case change starts a new piece
    EXPECT(pieces("\xe4\xbd\xa0\xe5\xa5\xbdworld") == (V{"\xe4\xbd\xa0\xe5\xa5\xbd", "world"}));   // Han runs stand alone
    EXPECT(pieces("a  b") == (V{"a", " ", " b"}));                   // the last space before a word goes with the word
    EXPECT(pieces("x\n\ny") == (V{"x", "\n\n", "y"}));
    EXPECT(pieces("end.  ") == (V{"end", ".", "  "}));
    EXPECT(pieces("caf\xc3\xa9 \xc3\x89t\xc3\xa9") == (V{"caf\xc3\xa9", " \xc3\x89t\xc3\xa9"}));
    std::string all;
    for (const std::string& p : pieces("mixed 123 \xf0\x9f\x98\x80 text\r\n\tok")) all += p;
    EXPECT(all == "mixed 123 \xf0\x9f\x98\x80 text\r\n\tok");        // pieces always cover the text exactly
    // Invalid UTF-8 must not hang or drop bytes.
    const std::string junk = "ok \xff\xfe\x80 fine \xe4\xbd";
    all.clear();
    for (const std::string& p : pieces(junk)) all += p;
    EXPECT(all == junk);

    Utf8Stream u;
    std::string out = u.push("\xe4\xbd");   // first two bytes of a three-byte character
    EXPECT(out.empty());
    out = u.push("\xa0!");
    EXPECT(out == "\xe4\xbd\xa0!");
    EXPECT(u.push("\xf0\x9f").empty() && u.flush() == "\xf0\x9f");
}

// ---- draft length ----------------------------------------------------------------------------------------

static void test_draft_len() {
    // how many drafted tokens to have checked, from the drafter's confidence and the cost of a position
    EXPECT(best_check_len({}, 0, 0.085) == 0);
    EXPECT(best_check_len(std::vector<float>(7, 0.9f), 7, 0.085) == 7);       // sure of itself, positions cheap: all of them
    EXPECT(best_check_len(std::vector<float>(7, 0.9f), 4, 0.085) == 4);       // never more than the limit
    EXPECT(best_check_len(std::vector<float>(7, 0.3f), 7, 0.5) == 0);         // unsure, positions dear: none
    EXPECT(best_check_len({0.95f, 0.95f, 0.1f, 0.9f, 0.9f}, 5, 0.085) == 2);  // stops before the token it doubts
    EXPECT(best_check_len({}, 3, 0.085) == 3);                                // no confidence head: 0.8 each is assumed
}

// ---- command line -------------------------------------------------------------------------------------------

static void test_args() {
    const char* argv[] = {"hkimi", "run", "store", "--draft-cost", "0.5", "--json", "--prompt=a b", "--max-new", "7", "extra"};
    Args a = Args::parse(10, (char**)argv, 2);
    EXPECT(a.pos.size() == 2 && a.pos[0] == "store" && a.pos[1] == "extra");
    EXPECT(a.real("draft-cost", 0) == 0.5 && a.flag("json") && a.str("prompt") == "a b" && a.num("max-new", 0) == 7 && !a.flag("nope"));
    bool threw = false;
    try {
        a.allow({"draft-cost", "json"});
    } catch (const Error&) {
        threw = true;
    }
    EXPECT(threw);
    EXPECT(parse_int_list("1, 2,3\n4") == (std::vector<int32_t>{1, 2, 3, 4}));
}

// ---- device memory arena -----------------------------------------------------------------------------------------------
// The "driver" here is malloc with a budget, so the paths taken on a nearly full device run too.

static void test_arena() {
    size_t held = 0, budget = (size_t)3 << 20;
    int raw_calls = 0;
    std::unordered_map<void*, size_t> raw;
    auto raw_alloc = [&](size_t n) -> void* {
        if (held + n > budget) return nullptr;
        void* p = std::malloc(n);
        raw[p] = n;
        held += n;
        ++raw_calls;
        return p;
    };
    auto raw_free = [&](void* p) {
        held -= raw.at(p);
        raw.erase(p);
        std::free(p);
    };
    DeviceArena::Sizes sz;
    sz.slab = (size_t)256 << 10;
    sz.direct = (size_t)64 << 10;
    sz.small = (size_t)4 << 10;
    sz.page = (size_t)4 << 10;
    {
        DeviceArena arena(raw_alloc, raw_free, sz);

        // Many medium buffers cost what they ask for, not a page each. Freed ones are reused in place.
        std::vector<void*> ps;
        for (int i = 0; i < 100; ++i) ps.push_back(arena.alloc(5000));
        EXPECT(arena.in_use() == 100 * 5120 && arena.reserved() == 2 * sz.slab && raw_calls == 2);
        void* third = ps[3];
        arena.free(ps[3]);
        EXPECT(arena.alloc(5000) == third && raw_calls == 2);
        arena.free(ps[10]);
        arena.free(ps[12]);
        arena.free(ps[11]);                                   // the three merge into one free piece
        EXPECT(arena.alloc(3 * 5120) == ps[10]);
        EXPECT(arena.consistent());
        ps[11] = ps[12] = nullptr;
        // A big request goes to the driver on its own and comes back to it when freed.
        void* big = arena.alloc(100000);
        EXPECT(big && raw_calls == 3 && arena.reserved() == 2 * sz.slab + 102400);
        arena.free(big);
        EXPECT(arena.reserved() == 2 * sz.slab && held == 2 * sz.slab);
        // Small requests go to slabs of their own, so that long-lived small buffers do not cut the
        // room of the big ones into holes.
        void* tiny = arena.alloc(100);
        EXPECT(tiny && raw_calls == 4 && arena.reserved() == 3 * sz.slab && arena.consistent());
        arena.free(tiny);
        for (void* q : ps) arena.free(q);
        EXPECT(arena.in_use() == 0 && arena.slabs() == 2);   // one empty slab of each kind is kept for the next request
        EXPECT(arena.trim() && arena.reserved() == 0 && held == 0);

        // Random traffic against the budget: no two live blocks may ever share a byte.
        struct Blk {
            unsigned char* p;
            size_t n;
            unsigned char tag;
        };
        std::vector<Blk> live;
        uint64_t rng = 12345;
        auto next = [&]() {
            rng = rng * 6364136223846793005ull + 1442695040888963407ull;
            return (uint32_t)(rng >> 33);
        };
        int refused = 0, corrupt = 0, inconsistent = 0;
        for (int step = 0; step < 30000; ++step) {
            if (live.empty() || next() % 100 < 55) {
                const size_t n = next() % 10 == 0 ? 60000 + next() % 120000 : 1 + next() % 20000;
                unsigned char* q = (unsigned char*)arena.alloc(n);
                if (!q) {
                    ++refused;   // the device is full: a refusal, never a corrupted book
                    continue;
                }
                const unsigned char tag = (unsigned char)(next() | 1);
                std::memset(q, tag, n);
                live.push_back({q, n, tag});
            } else {
                const size_t i = next() % live.size();
                const Blk b = live[i];
                for (size_t k = 0; k < b.n; ++k)
                    if (b.p[k] != b.tag) {
                        ++corrupt;
                        break;
                    }
                arena.free(b.p);
                live[i] = live.back();
                live.pop_back();
            }
            if (step % 499 == 0 && !arena.consistent()) ++inconsistent;
        }
        EXPECT(corrupt == 0 && inconsistent == 0);
        EXPECT(refused > 100);                                // the full-device paths were taken
        EXPECT(arena.consistent() && arena.reserved() == held && held <= budget);
        for (const Blk& b : live) arena.free(b.p);
        EXPECT(arena.in_use() == 0 && arena.blocks() == 0 && arena.slabs() <= 2);

        // with direct = 0 every request is a driver allocation of its own
        DeviceArena::Sizes plain = sz;
        plain.direct = 0;
        arena.trim();
        const int calls0 = raw_calls;
        DeviceArena each(raw_alloc, raw_free, plain);
        void* a = each.alloc(10);
        void* b = each.alloc(5000);
        EXPECT(a && b && raw_calls == calls0 + 2 && each.reserved() == 4096 + 8192);
        each.free(a);
        EXPECT(each.reserved() == 8192 && each.consistent());
        (void)b;   // left for the destructor

        // freed big buffers can be kept for the next one of the same size, up to a limit
        DeviceArena::Sizes keep = sz;
        keep.keep_direct = (size_t)250 << 10;
        DeviceArena kept(raw_alloc, raw_free, keep);
        const int calls1 = raw_calls;
        void* big2 = kept.alloc(100000);                        // on its own from the driver: 102400 bytes
        EXPECT(big2 && raw_calls == calls1 + 1);
        kept.free(big2);
        EXPECT(kept.reserved() == 102400 && kept.spare() == 102400 && kept.in_use() == 0 && kept.consistent());
        EXPECT(kept.alloc(100000) == big2 && raw_calls == calls1 + 1 && kept.spare() == 0);   // the same memory, no driver call
        void* other = kept.alloc(200000);                      // another size is another driver call: 200704 bytes
        EXPECT(other && other != big2 && raw_calls == calls1 + 2 && kept.reserved() == 102400 + 200704);
        kept.free(big2);
        kept.free(other);                                      // together they are over the limit: this one goes back
        EXPECT(kept.reserved() == 102400 && kept.spare() == 102400 && kept.blocks() == 0 && kept.consistent());
        EXPECT(kept.alloc(5000) && kept.spare() == 102400);    // small requests do not take the kept one
        EXPECT(kept.trim() && kept.spare() == 0 && kept.consistent());
    }
    EXPECT(held == 0 && raw.empty());   // the destructors gave everything back
}

// ---- the CPU backend against itself (every op runs, shapes agree) ---------------------------------------------------

static void test_backend() {
    std::unique_ptr<Backend> a = make_cpu_backend(), b = make_cpu_backend();
    SelftestReport r = backend_selftest(*a, *b, 5, /*quick=*/true);
    EXPECT(r.passed == (int)r.cases.size() && !r.cases.empty());
    EXPECT(a->mem_used() == 0 && b->mem_used() == 0);   // nothing leaked
}

int main(int argc, char** argv) {
    struct Group {
        const char* name;
        void (*fn)();
    };
    const Group groups[] = {{"json", test_json},       {"numeric", test_numeric}, {"planes", test_planes}, {"io", test_io},
                            {"threads", test_threads}, {"pretok", test_pretok},   {"draft", test_draft_len}, {"args", test_args},
                            {"arena", test_arena},     {"backend", test_backend}};
    for (const Group& g : groups) {
        bool wanted = argc < 2;
        for (int i = 1; i < argc; ++i) wanted = wanted || !strcmp(argv[i], g.name);
        if (!wanted) continue;
        const int before = g_failed;
        printf("%s\n", g.name);
        try {
            g.fn();
        } catch (const std::exception& e) {
            ++g_failed;
            printf("    EXCEPTION: %s\n", e.what());
        }
        if (g_failed == before) printf("    ok\n");
    }
    printf("%d checks, %d failed\n", g_checks, g_failed);
    return g_failed ? 1 : 0;
}