okami.mom/strata

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

Niko1221Merge branch 'f-split-int' into f-split-vision7c5e84612

main
14.1 KiB229 linesraw
1#include "strata/core/exchange_storage.hpp"
2
3#include <algorithm>
4#include <cstring>
5#include <iostream>
6#include <random>
7#include <set>
8#include <thread>
9#include <stdexcept>
10#include <vector>
11
12using strata::core::detail::ExchangeStorage;
13constexpr uint64_t absent = ~uint64_t{0};
14void require(bool ok, const char* why) { if (!ok) throw std::runtime_error(why); }
15
16void exercise(size_t bytes, size_t rounds) {
17    constexpr size_t n = 24, resident = 16, spare_count = 4, guard = 19;
18    std::vector<uint8_t> arena(guard + resident * bytes + guard, 0xcd);
19    std::vector<uint8_t> spare(guard + spare_count * bytes + guard, 0xef);
20    // Distinct alias arrays catch accidentally retaining the old CUDA address.
21    std::vector<uint8_t> aliases(resident * bytes), spare_aliases(spare_count * bytes);
22    std::vector<std::vector<uint8_t>> reference(n, std::vector<uint8_t>(bytes));
23    std::mt19937 random(601);
24    for (auto& row : reference) for (auto& v : row) v = (uint8_t)random();
25    std::vector<uint64_t> offsets(n, absent);
26    for (size_t i = 0; i < resident; ++i) {
27        offsets[i] = i * bytes;
28        std::memcpy(arena.data() + guard + offsets[i], reference[i].data(), bytes);
29    }
30    ExchangeStorage storage;
31    std::string error;
32    require(storage.initialize(offsets, arena.data() + guard, aliases.data(), resident * bytes,
33        spare.data() + guard, spare_aliases.data(), spare_count, bytes, error), error.c_str());
34    std::set<uint8_t*> original;
35    for (size_t i = 0; i < n; ++i) if (auto p = storage.resident(i).host) original.insert(p);
36    for (size_t q = 0; q < spare_count; ++q) original.insert(storage.spare(q).host);
37    // A lookahead thread may inspect residency while ownership is committed.
38    // It only observes immutable address pairs, never reads mutable expert bytes.
39    std::atomic<bool> stop{false}, reader_failed{false};
40    std::atomic<uint64_t> observations{0};
41    std::vector<ExchangeStorage::View> valid;
42    for (size_t i = 0; i < n; ++i) if (storage.resident(i).host) valid.push_back(storage.resident(i));
43    for (size_t q = 0; q < spare_count; ++q) valid.push_back(storage.spare(q));
44    std::thread reader([&] {
45        while (!stop.load()) {
46            for (size_t i = 0; i < n; ++i) {
47                const auto view = storage.resident(i);
48                if (view.host && std::none_of(valid.begin(), valid.end(), [&](auto v) {
49                        return v.host == view.host && v.device == view.device; })) reader_failed.store(true);
50            }
51            ++observations;
52        }
53    });
54    struct Join {
55        std::atomic<bool>& stop; std::thread& reader;
56        void finish() { stop.store(true); if (reader.joinable()) reader.join(); }
57        ~Join() { finish(); }
58    } join{stop, reader};
59    while (!observations.load()) std::this_thread::yield();
60    uint64_t exchanges = 0;
61    for (size_t round = 0; round < rounds; ++round) {
62        std::vector<size_t> ins, outs;
63        for (size_t i = 0; i < n; ++i) (storage.resident(i).host ? ins : outs).push_back(i);
64        std::shuffle(ins.begin(), ins.end(), random);
65        std::shuffle(outs.begin(), outs.end(), random);
66        ExchangeStorage::View before[spare_count], staged[spare_count];
67        for (size_t q = 0; q < spare_count; ++q) {
68            before[q] = storage.resident(ins[q]); staged[q] = storage.spare(q);
69            // Simulated completed D2H eviction. The old RAM input stays readable
70            // until simulated H2D and all readers finish, before commit.
71            std::memcpy(staged[q].host, reference[outs[q]].data(), bytes);
72            require(!std::memcmp(before[q].host, reference[ins[q]].data(), bytes), "incoming expert overwritten early");
73        }
74        for (size_t q = 0; q < spare_count; ++q) {
75            require(!storage.commit(ins[q], ins[q], q, staged[q].host, bytes), "self swap accepted");
76            require(!storage.commit(ins[q], outs[q], q, staged[q].host, bytes + 1), "wrong size accepted");
77            require(!storage.commit(ins[q], outs[q], q, nullptr, bytes), "missing staged buffer accepted");
78            require(!storage.commit(ins[q], outs[q], spare_count, staged[q].host, bytes), "bad spare accepted");
79            require(!storage.commit(n, outs[q], q, staged[q].host, bytes), "bad expert accepted");
80            require(storage.commit(ins[q], outs[q], q, staged[q].host, bytes), "valid swap rejected");
81            require(!storage.commit(ins[q], outs[q], q, staged[q].host, bytes), "duplicate commit accepted");
82            require(storage.resident(outs[q]).host == staged[q].host &&
83                    storage.resident(outs[q]).device == staged[q].device, "evicted buffer was not adopted with its alias");
84            require(storage.spare(q).host == before[q].host && storage.spare(q).device == before[q].device,
85                    "old RAM input was not recycled with its alias");
86            // Even the old incoming bytes have not changed: commit copies metadata only.
87            require(!std::memcmp(storage.spare(q).host, reference[ins[q]].data(), bytes), "commit changed spare bytes");
88            ++exchanges;
89        }
90        std::set<uint8_t*> live;
91        for (size_t i = 0; i < n; ++i) if (auto p = storage.resident(i).host) {
92            require(live.insert(p).second, "two experts share storage");
93            require(!std::memcmp(p, reference[i].data(), bytes), "resident bytes corrupted");
94        }
95        for (size_t q = 0; q < spare_count; ++q)
96            require(live.insert(storage.spare(q).host).second, "spare aliases live expert");
97        require(live == original, "storage leaked or duplicated");
98    }
99    require(storage.exchanges() == exchanges && storage.avoided_bytes() == exchanges * bytes, "wrong accounting");
100    require(std::all_of(arena.begin(), arena.begin() + guard, [](auto x) { return x == 0xcd; }) &&
101            std::all_of(arena.end() - guard, arena.end(), [](auto x) { return x == 0xcd; }) &&
102            std::all_of(spare.begin(), spare.begin() + guard, [](auto x) { return x == 0xef; }) &&
103            std::all_of(spare.end() - guard, spare.end(), [](auto x) { return x == 0xef; }), "guard overwritten");
104    require(!storage.initialize(offsets, arena.data() + guard, aliases.data(), resident * bytes,
105        spare.data() + guard, spare_aliases.data(), spare_count, bytes, error), "live storage reinitialized");
106    join.finish();
107    require(!reader_failed.load() && observations.load(), "concurrent residency reader observed invalid alias");
108    storage.clear();
109    require(!storage.active() && !storage.resident(0).host && !storage.spare(0).host &&
110            !storage.exchanges() && !storage.avoided_bytes(), "clear retained state");
111}
112
113// Layers of different block sizes: the spares are kept per size, and a swap (two experts of one layer) hands back a
114// buffer of the size it took.
115void exercise_sized(size_t rounds) {
116    const size_t layer_bytes[3] = {33, 4097, 64};
117    constexpr size_t per_layer = 10, resident_per_layer = 6, n = 3 * per_layer, count = 4, bounce = 1, guard = 19;
118    std::vector<uint64_t> sizes(n), offsets(n, absent);
119    uint64_t resident_bytes = 0;
120    for (size_t i = 0; i < n; ++i) {
121        sizes[i] = layer_bytes[i / per_layer];
122        if (i % per_layer < resident_per_layer) { offsets[i] = resident_bytes; resident_bytes += sizes[i]; }
123    }
124    const uint64_t need = ExchangeStorage::exchange_bytes_needed(sizes, count, bounce);
125    require(need == (count - bounce) * (33 + 64 + 4097) + bounce * 4097, "wrong exchange allocation size");
126    std::vector<uint8_t> arena(guard + resident_bytes + guard, 0xcd), spare(guard + need + guard, 0xef);
127    std::vector<uint8_t> aliases(resident_bytes), spare_aliases(need);
128    std::vector<std::vector<uint8_t>> reference(n);
129    std::mt19937 random(603);
130    for (size_t i = 0; i < n; ++i) {
131        reference[i].resize(sizes[i]);
132        for (auto& v : reference[i]) v = (uint8_t)random();
133        if (offsets[i] != absent) std::memcpy(arena.data() + guard + offsets[i], reference[i].data(), sizes[i]);
134    }
135    ExchangeStorage storage;
136    std::string error;
137    require(!storage.initialize_sized(offsets, sizes, arena.data() + guard, aliases.data(), resident_bytes,
138        spare.data() + guard, spare_aliases.data(), need - 1, count, bounce, error), "short exchange allocation accepted");
139    require(storage.initialize_sized(offsets, sizes, arena.data() + guard, aliases.data(), resident_bytes,
140        spare.data() + guard, spare_aliases.data(), need, count, bounce, error), error.c_str());
141    require(storage.block_sizes() == 3, "wrong number of block sizes");
142    // the bounce ordinal exists in the largest size only; the others in every size
143    require(storage.spare(count - 1, 4097).host && !storage.spare(count - 1, 33).host && !storage.spare(count - 1, 64).host,
144            "bounce buffers of a smaller size");
145    require(storage.spare(count - 1).host == storage.spare(count - 1, 4097).host, "the size-less spare is not the largest");
146    require(!storage.spare(0, 34).host && !storage.spare(count, 33).host, "a spare of no size or ordinal");
147    std::set<uint8_t*> original;
148    for (size_t i = 0; i < n; ++i) if (auto q = storage.resident(i).host) original.insert(q);
149    for (size_t c = 0; c < 3; ++c)
150        for (size_t q = 0; q < count; ++q) if (auto b = storage.spare(q, layer_bytes[c]).host) original.insert(b);
151    uint64_t exchanges = 0, bytes_moved = 0;
152    for (size_t round = 0; round < rounds; ++round) {
153        size_t used[3] = {0, 0, 0};   // the ordinal is the swap's number in the round, whatever its layer
154        size_t ordinal = 0;
155        std::vector<size_t> order = {0, 1, 2, 0, 1, 2};
156        std::shuffle(order.begin(), order.end(), random);
157        for (const size_t layer : order) {
158            if (ordinal >= count - bounce) break;
159            const size_t bytes = layer_bytes[layer], q = ordinal++;
160            std::vector<size_t> ins, outs;
161            for (size_t i = layer * per_layer; i < (layer + 1) * per_layer; ++i) (storage.resident(i).host ? ins : outs).push_back(i);
162            std::shuffle(ins.begin(), ins.end(), random);
163            std::shuffle(outs.begin(), outs.end(), random);
164            const size_t in = ins[0], out = outs[0];
165            const ExchangeStorage::View before = storage.resident(in), staged = storage.spare(q, bytes);
166            require(staged.host != nullptr, "no spare of the layer's size");
167            std::memcpy(staged.host, reference[out].data(), bytes);
168            const size_t other = layer_bytes[(layer + 1) % 3];
169            require(!storage.commit(in, out, q, staged.host, other), "another size's commit accepted");
170            size_t stranger = ((layer + 1) % 3) * per_layer;   // an expert of another layer that RAM does not hold
171            while (storage.resident(stranger).host) ++stranger;
172            require(!storage.commit(in, stranger, q, staged.host, bytes), "another layer's expert accepted");
173            require(storage.commit(in, out, q, staged.host, bytes), "valid sized swap rejected");
174            require(storage.resident(out).host == staged.host && storage.resident(out).device == staged.device,
175                    "evicted buffer was not adopted with its alias");
176            require(storage.spare(q, bytes).host == before.host && storage.spare(q, bytes).device == before.device,
177                    "old RAM input was not recycled with its alias");
178            ++used[layer]; ++exchanges; bytes_moved += bytes;
179        }
180        std::set<uint8_t*> live;
181        for (size_t i = 0; i < n; ++i) if (auto q = storage.resident(i).host) {
182            require(live.insert(q).second, "two experts share storage");
183            require(!std::memcmp(q, reference[i].data(), sizes[i]), "resident bytes corrupted");
184        }
185        for (size_t c = 0; c < 3; ++c)
186            for (size_t q = 0; q < count; ++q) if (auto b = storage.spare(q, layer_bytes[c]).host)
187                require(live.insert(b).second, "spare aliases live expert");
188        require(live == original, "storage leaked or duplicated");
189        for (size_t layer = 0; layer < 3; ++layer) {
190            size_t held = 0;
191            for (size_t i = layer * per_layer; i < (layer + 1) * per_layer; ++i) held += storage.resident(i).host != nullptr;
192            require(held == resident_per_layer, "a layer's resident count changed");
193        }
194    }
195    require(storage.exchanges() == exchanges && storage.avoided_bytes() == bytes_moved, "wrong accounting");
196    require(std::all_of(arena.begin(), arena.begin() + guard, [](auto x) { return x == 0xcd; }) &&
197            std::all_of(arena.end() - guard, arena.end(), [](auto x) { return x == 0xcd; }) &&
198            std::all_of(spare.begin(), spare.begin() + guard, [](auto x) { return x == 0xef; }) &&
199            std::all_of(spare.end() - guard, spare.end(), [](auto x) { return x == 0xef; }), "guard overwritten");
200    // overlapping resident blocks are refused
201    std::vector<uint64_t> bad = offsets;
202    bad[1] = offsets[0] + 1;
203    ExchangeStorage t;
204    require(!t.initialize_sized(bad, sizes, arena.data() + guard, aliases.data(), resident_bytes,
205        spare.data() + guard, spare_aliases.data(), need, count, bounce, error) && !t.active(), "overlapping blocks accepted");
206}
207
208void invalid_geometry() {
209    uint8_t h[64]{}, d[64]{}, x[64]{}, xd[64]{};
210    ExchangeStorage s; std::string e;
211    require(!s.initialize({0, 3}, h, d, 8, x, xd, 2, 4, e), "unaligned slot accepted");
212    require(!s.initialize({0, 0}, h, d, 8, x, xd, 2, 4, e), "duplicate offset accepted");
213    require(!s.initialize({0, 8}, h, d, 8, x, xd, 2, 4, e), "out of bounds accepted");
214    require(!s.initialize({0, absent}, h, d, 8, x, xd, 2, 4, e), "lost slot accepted");
215    require(!s.initialize({0, 4}, h, nullptr, 8, x, xd, 2, 4, e), "unmapped resident accepted");
216    require(!s.initialize({0, 4}, h, d, 8, x, nullptr, 2, 4, e), "unmapped spare accepted");
217    require(!s.initialize({0, 4}, h, d, 8, x, xd, 2, 0, e), "zero blob accepted");
218    require(!s.active(), "failed initialization left active state");
219}
220
221int main() {
222    try {
223        invalid_geometry();
224        for (size_t bytes : {1u, 33u, 4097u}) exercise(bytes, 1024);
225        exercise(5222400, 4); // actual Q8 expert size
226        exercise_sized(2048);
227        std::cout << "exchange_storage_test: PASS (byte/alias/ownership checks, 12304 exchanges; several block sizes)\n";
228    } catch (const std::exception& e) { std::cerr << e.what() << '\n'; return 1; }
229}