okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-memlock-split 4aa298595 into f-own-int (round 14: the split engine locks its host-read tables as far as the machine allows, never a failed start)067879249

main
10.8 KiB237 linesraw
1// src/memlock.hpp: the split engine locks its host-read tables as far as the machine lets it and never fails because of it. No GPU. Cases:
2//   1 plan     budget handed out in order: the first part first, page-sized pieces, cut by the memory-lock limit and by the free RAM
3//   2 fake     an mlock that always succeeds / always fails / fails past a total: no exception, the numbers add up, the tables are untouched, the line is right
4//   3 real     the real mlock under a lowered RLIMIT_MEMLOCK in a child process (the lock may fail or succeed; either way the lock call returns and the bytes are intact)
5//   4 raise    a soft limit below the need and a hard limit above it is raised (child process)
6#include "../src/memlock.hpp"
7
8#include <sys/mman.h>
9#include <sys/wait.h>
10#include <unistd.h>
11
12#include <atomic>
13#include <cstdio>
14#include <cstdlib>
15
16using namespace fnx;
17
18namespace {
19
20int fails = 0;
21#define CHECK(c)                                                                                  \
22    do {                                                                                          \
23        if (!(c)) {                                                                               \
24            std::printf("FAIL line %d: %s\n", __LINE__, #c);                                      \
25            ++fails;                                                                              \
26        }                                                                                         \
27    } while (0)
28
29constexpr size_t MiB = 1u << 20;
30
31uint8_t* map_pages(size_t n, uint8_t seed) {
32    void* p = mmap(nullptr, n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
33    if (p == MAP_FAILED) std::abort();
34    auto* b = (uint8_t*) p;
35    for (size_t i = 0; i < n; ++i) b[i] = (uint8_t) (seed + i * 7);
36    return b;
37}
38uint64_t sum(const uint8_t* b, size_t n) {
39    uint64_t s = 0;
40    for (size_t i = 0; i < n; ++i) s = s * 31 + b[i];
41    return s;
42}
43
44std::atomic<uint64_t> g_locked{0}, g_calls{0}, g_cap{UINT64_MAX};
45int fake_ok(const void*, size_t) { ++g_calls; return 0; }
46int fake_fail(const void*, size_t) { ++g_calls; errno = ENOMEM; return -1; }
47int fake_cap(const void*, size_t n) {   // like the kernel: a call that would pass the allowance fails whole
48    ++g_calls;
49    uint64_t cur = g_locked.load();
50    for (;;) {
51        if (cur + n > g_cap.load()) { errno = ENOMEM; return -1; }
52        if (g_locked.compare_exchange_weak(cur, cur + n)) return 0;
53    }
54}
55
56std::vector<LockPart> two_parts(uint8_t* a, size_t na, uint8_t* b, size_t nb) {
57    LockPart x, y;
58    x.name = "token_embd.weight"; x.data = a; x.nbytes = na;
59    y.name = "per_layer_token_embd.weight"; y.data = b; y.nbytes = nb;
60    return {x, y};
61}
62
63void test_plan() {
64    uint8_t* a = map_pages(2 * MiB, 1);
65    uint8_t* b = map_pages(8 * MiB, 2);
66    auto parts = two_parts(a, 2 * MiB, b, 8 * MiB);
67    std::vector<uint64_t> t;
68    LockEnv e;   // nothing limits
69    CHECK(plan_lock(parts, e, t) == 10 * MiB && t[0] == 2 * MiB && t[1] == 8 * MiB);
70    e.limit = 1 * MiB;   // the limit cuts inside the first part: the second gets nothing
71    CHECK(plan_lock(parts, e, t) == 1 * MiB && t[0] == 1 * MiB && t[1] == 0);
72    e.limit = 5 * MiB;   // the first whole, the second its start
73    CHECK(plan_lock(parts, e, t) == 5 * MiB && t[0] == 2 * MiB && t[1] == 3 * MiB);
74    e.limit = 0;
75    CHECK(plan_lock(parts, e, t) == 0);
76    e = LockEnv{};
77    e.avail = 12 * MiB; e.reserve = 9 * MiB;   // the free RAM leaves 3 MiB
78    bool ram = false;
79    CHECK(plan_lock(parts, e, t, &ram) == 3 * MiB && ram);
80    e.avail = 4 * MiB;   // below the reserve: nothing
81    CHECK(plan_lock(parts, e, t, &ram) == 0 && ram);
82    munmap(a, 2 * MiB); munmap(b, 8 * MiB);
83}
84
85void test_fake() {
86    uint8_t* a = map_pages(2 * MiB + 100, 3);   // not a whole number of pages: the piece edges must still work
87    uint8_t* b = map_pages(8 * MiB + 17, 4);
88    const uint64_t sa = sum(a, 2 * MiB + 100), sb = sum(b, 8 * MiB + 17);
89    // everything locks: no line
90    {
91        auto parts = two_parts(a, 2 * MiB + 100, b, 8 * MiB + 17);
92        g_calls = 0;
93        LockOutcome o = lock_parts(parts, LockEnv{}, fake_ok);
94        CHECK(o.locked == o.want && o.want == 10 * MiB + 117);
95        CHECK(parts[0].locked == parts[0].nbytes && parts[1].locked == parts[1].nbytes);
96        CHECK(lock_line(parts, o).empty());
97        CHECK(g_calls > 0);
98    }
99    // the limit lets the first part and a bit of the second: partial, the line says "only partly" and names the limit
100    {
101        auto parts = two_parts(a, 2 * MiB + 100, b, 8 * MiB + 17);
102        LockEnv e;
103        e.limit = 4 * MiB;
104        LockOutcome o = lock_parts(parts, e, fake_ok);
105        CHECK(parts[0].locked == parts[0].nbytes);
106        CHECK(parts[1].locked > 0 && parts[1].locked < parts[1].nbytes);
107        CHECK(o.locked <= 4 * MiB + 4096);
108        const std::string l = lock_line(parts, o);
109        CHECK(l.find(" of its ") != std::string::npos && l.find("locked in RAM") != std::string::npos && l.find("at most 4 MiB") != std::string::npos);
110        CHECK(l.find("runs as usual") != std::string::npos);
111    }
112    // nothing may be locked: mlock is not even called, the tables are read in, the line says "not locked"
113    {
114        auto parts = two_parts(a, 2 * MiB + 100, b, 8 * MiB + 17);
115        LockEnv e;
116        e.limit = 0;
117        g_calls = 0;
118        LockOutcome o = lock_parts(parts, e, fake_ok);
119        CHECK(o.locked == 0 && g_calls == 0);
120        const std::string l = lock_line(parts, o);
121        CHECK(l.find("not locked in RAM") != std::string::npos);
122    }
123    // the system refuses although the plan allowed it (another process took the allowance): no throw, nothing counted as locked, the errno in the line
124    {
125        auto parts = two_parts(a, 2 * MiB + 100, b, 8 * MiB + 17);
126        LockEnv e;   // no limit known
127        LockOutcome o = lock_parts(parts, e, fake_fail);
128        CHECK(o.locked == 0 && o.err == ENOMEM);
129        CHECK(lock_line(parts, o).find("the system refused") != std::string::npos);
130    }
131    // the allowance runs out in the middle (a kernel that fails a call whole): a partial state, no throw, the count equals what the fake locked
132    {
133        auto parts = two_parts(a, 2 * MiB + 100, b, 8 * MiB + 17);
134        g_locked = 0; g_cap = 6 * MiB;
135        LockOutcome o = lock_parts(parts, LockEnv{}, fake_cap);
136        CHECK(o.locked > 0 && o.locked < o.want);
137        CHECK(o.locked == g_locked.load());
138        CHECK(!lock_line(parts, o).empty());
139        g_cap = UINT64_MAX;
140    }
141    // RAM short: the line names the reserve
142    {
143        auto parts = two_parts(a, 2 * MiB + 100, b, 8 * MiB + 17);
144        LockEnv e;
145        e.avail = 6 * MiB; e.reserve = 5 * MiB;
146        LockOutcome o = lock_parts(parts, e, fake_ok);
147        CHECK(o.limited_by_ram && o.locked <= 1 * MiB + 4096);
148        CHECK(lock_line(parts, o).find("less than") != std::string::npos);
149    }
150    CHECK(sum(a, 2 * MiB + 100) == sa && sum(b, 8 * MiB + 17) == sb);   // the tables are exactly as they were
151    munmap(a, 2 * MiB + 100); munmap(b, 8 * MiB + 17);
152}
153
154// runs `f` in a child (limits set there stay there); returns the child's exit code
155template <class F> int in_child(F f) {
156    const pid_t pid = fork();
157    if (pid == 0) _exit(f());
158    int st = 0;
159    waitpid(pid, &st, 0);
160    return WIFEXITED(st) ? WEXITSTATUS(st) : 99;
161}
162
163// the sentences in the owner's wording of 11-11, at the real sizes
164void test_words() {
165    const uint64_t G = 1ull << 30;
166    std::vector<LockPart> none;
167    LockOutcome o;
168    o.want = (size_t) (27.5 * G);
169    o.env.limit = 8 * (1ull << 20);
170    o.locked = 0;
171    CHECK(lock_line(none, o) == "Split engine: its word tables (27.5 GiB) are not locked in RAM (this account may lock at most 8 MiB). It runs as usual. The tables are read into memory at the start; "
172                                "only if the PC runs short of memory can long prompts slow down.");
173    o.locked = 8u << 20;   // a sliver of a table of GiB counts as nothing locked
174    CHECK(lock_line(none, o).find("are not locked in RAM") != std::string::npos);
175    o.locked = (size_t) (14.0 * G);
176    o.env.limit = 14 * G;
177    CHECK(lock_line(none, o) == "Split engine: 14.0 of its 27.5 GiB of word tables are locked in RAM (this account may lock at most 14.0 GiB). It runs as usual. The rest is read into memory at the start; "
178                                "only if the PC runs short of memory can long prompts slow down.");
179    o.env.limit = UINT64_MAX;
180    o.limited_by_ram = true;
181    o.env.reserve = (uint64_t) (6.3 * G);
182    CHECK(lock_line(none, o).find("(locking more would leave less than 6.3 GiB of RAM free)") != std::string::npos);
183    o.locked = o.want;
184    CHECK(lock_line(none, o).empty());
185}
186
187void test_real() {
188    // the soft AND hard limit are lowered to 256 KiB: the soft limit cannot be raised, the real mlock refuses most of 10 MiB (a process with CAP_IPC_LOCK is not limited: then all locks)
189    const int rc = in_child([] {
190        struct rlimit lo { 256 * 1024, 256 * 1024 };
191        if (setrlimit(RLIMIT_MEMLOCK, &lo) != 0) return 90;
192        uint8_t* a = map_pages(2 * MiB, 5);
193        uint8_t* b = map_pages(8 * MiB, 6);
194        const uint64_t sa = sum(a, 2 * MiB), sb = sum(b, 8 * MiB);
195        auto parts = two_parts(a, 2 * MiB, b, 8 * MiB);
196        const LockEnv e = read_lock_env(10 * MiB);
197        LockOutcome o = lock_parts(parts, e);   // must return, whatever the kernel says
198        const bool privileged = o.locked == o.want;
199        if (!privileged && o.locked > 256 * 1024 + 4096) return 91;
200        if (!privileged && lock_line(parts, o).empty()) return 92;
201        if (sum(a, 2 * MiB) != sa || sum(b, 8 * MiB) != sb) return 93;
202        return 0;
203    });
204    CHECK(rc == 0);
205}
206
207void test_raise() {
208    // soft 128 KiB, hard 64 MiB, need 10 MiB: the soft limit is raised (privileged or not) and the whole lock succeeds
209    const int rc = in_child([] {
210        struct rlimit lo { 128 * 1024, 64 * MiB };
211        if (setrlimit(RLIMIT_MEMLOCK, &lo) != 0) return 77;   // the hard limit of this process is already below 64 MiB (a test run under ulimit -l 8192): it cannot be raised here, the case does not apply
212        const LockEnv e = read_lock_env(10 * MiB);
213        if (!e.raised) return 91;
214        struct rlimit now {};
215        getrlimit(RLIMIT_MEMLOCK, &now);
216        if (now.rlim_cur != 64 * MiB) return 92;   // need + 1 GiB, capped at the hard limit
217        uint8_t* a = map_pages(2 * MiB, 7);
218        uint8_t* b = map_pages(8 * MiB, 8);
219        auto parts = two_parts(a, 2 * MiB, b, 8 * MiB);
220        LockOutcome o = lock_parts(parts, e);
221        if (o.locked != o.want && !(e.avail != UINT64_MAX && e.avail < o.want + e.reserve)) return 93;   // all locked, unless this PC is short of RAM
222        return 0;
223    });
224    CHECK(rc == 0 || rc == 77);
225}
226
227}  // namespace
228
229int main() {
230    test_plan();
231    test_fake();
232    test_words();
233    test_real();
234    test_raise();
235    std::printf("%s\n", fails ? "memlock_test: FAILED" : "memlock_test: all passed");
236    return fails ? 1 : 0;
237}