okami.mom/strata

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

Niko1221Trial2 merge f-0291-pr-nv (97b3d614f)1306424be

main
19.5 KiB410 linesraw
1// routed_stream_test: STRATA_PREFILL_ROUTED_STREAM's issuer walk and route gate (include/strata/prefill/routed_stream.hpp).
2// CPU only.  A simulated chunk: an in-order link that lands one copy every few ticks, a consumer that walks the layers as
3// prefill.cpp's streamed walk does (publish a layer's routing, give back unrouted entries, read a routed entry's slot
4// once its copy has landed), and the issuer walk itself, each idle() of which advances the simulation by one tick.
5#include "strata/prefill/routed_stream.hpp"
6
7#include <atomic>
8#include <cstdio>
9#include <cstring>
10#include <deque>
11#include <mutex>
12#include <random>
13#include <thread>
14#include <vector>
15
16namespace rs = strata::prefill::routed_stream;
17
18static int g_fail = 0;
19static void expect(bool ok, const char* what) {
20    if (!ok) {
21        ++g_fail;
22        std::fprintf(stderr, "FAIL: %s\n", what);
23    }
24}
25
26struct Entry { int32_t l, e; int job; };
27
28struct Case {
29    int layers = 6, n_expert = 64, resident_every = 3, ring = 48, depth = 4;
30    double unrouted = 0.4;   // share of the streamed experts no token routes to
31    int link_ticks = 3;      // ticks per copy
32    int publish_delay = 5;   // ticks from the end of layer l-1 to layer l's routing
33    int compute_ticks = 1;   // ticks per routed entry
34    bool publish = true;     // false: no layer is ever published (the fused path, or the switch off)
35    int staged_every = 0;    // every n-th entry has a stager job (never dropped); 0: none
36    unsigned seed = 1;
37};
38
39struct Sim {
40    Case c;
41    std::vector<Entry> seq;
42    std::vector<size_t> seq_start;
43    std::vector<std::vector<int32_t>> cnt;   // [layer][expert] tokens
44    rs::RouteGate gate;
45    std::atomic<size_t> a_issued{0}, a_consumed{0};
46    // the link: copies in issue order, each lands link_ticks after it starts
47    struct Copy { size_t k; int slot; };
48    std::deque<Copy> queue;
49    int link_left = 0;
50    std::vector<long> slot_content;          // the entry whose bytes a ring slot holds (-1: none)
51    std::vector<long> slot_last_issue;       // the entry last issued into a slot (its `copied` event)
52    std::vector<char> landed_k;              // per entry: its copy has landed
53    std::vector<char> issued_k, dropped_k, pub_at_drop;
54    size_t max_out = 0, outstanding = 0;
55    bool ring_violation = false, depth_violation = false, wrong_bytes = false, read_before_issue = false;
56    // the consumer
57    int64_t cl = 0;            // layer being walked
58    size_t ck = 0;             // next entry of the walk
59    int phase = 0;             // 0: waiting to publish, 1: walking the layer
60    int wait = 0;
61    int64_t tick = 0;
62
63    explicit Sim(const Case& cc) : c(cc) {
64        std::mt19937 rng(c.seed);
65        std::uniform_real_distribution<double> u(0.0, 1.0);
66        seq_start.assign((size_t) c.layers + 1, 0);
67        cnt.assign((size_t) c.layers, std::vector<int32_t>((size_t) c.n_expert, 0));
68        for (int l = 0; l < c.layers; ++l) {
69            seq_start[(size_t) l] = seq.size();
70            for (int e = 0; e < c.n_expert; ++e) {
71                cnt[(size_t) l][(size_t) e] = u(rng) < c.unrouted ? 0 : 1 + (int) (u(rng) * 7);
72                if (c.resident_every > 0 && e % c.resident_every == 0) continue;   // resident: not in the stream
73                const int job = c.staged_every > 0 && seq.size() % (size_t) c.staged_every == 0 ? (int) seq.size() : -1;
74                seq.push_back({l, e, job});
75            }
76        }
77        seq_start[(size_t) c.layers] = seq.size();
78        gate.reset(c.layers, c.n_expert);
79        slot_content.assign((size_t) c.ring, -1);
80        slot_last_issue.assign((size_t) c.ring, -1);
81        landed_k.assign(seq.size(), 0);
82        issued_k.assign(seq.size(), 0);
83        dropped_k.assign(seq.size(), 0);
84        pub_at_drop.assign(seq.size(), 0);
85        wait = c.publish_delay;
86    }
87
88    void step_link() {
89        if (queue.empty()) return;
90        if (--link_left > 0) return;
91        const Copy cp = queue.front();
92        queue.pop_front();
93        slot_content[(size_t) cp.slot] = (long) cp.k;   // the bytes land
94        landed_k[cp.k] = 1;
95        --outstanding;
96        link_left = c.link_ticks;
97    }
98    void give_back(size_t upto) { a_consumed.store(upto, std::memory_order_release); }
99    void step_consumer() {
100        if (cl >= c.layers) return;
101        const size_t kend = seq_start[(size_t) cl + 1];
102        if (phase == 0) {   // the layer's attention and router: then the routing is known
103            if (--wait > 0) return;
104            if (c.publish) gate.publish(cl, cnt[(size_t) cl].data());
105            ck = seq_start[(size_t) cl];
106            phase = 1;
107            wait = 0;
108            return;
109        }
110        if (wait > 0) { --wait; return; }
111        if (ck < kend) {
112            const Entry& en = seq[ck];
113            if (cnt[(size_t) cl][(size_t) en.e] == 0) {   // release_to: an unrouted entry only gives its slot back
114                give_back(++ck);
115                return;
116            }
117            // a routed entry: wait_issued, then the copy's event, then compute from the slot
118            if (a_issued.load(std::memory_order_acquire) <= ck) return;
119            if (!issued_k[ck]) { read_before_issue = true; give_back(++ck); return; }
120            if (!landed_k[ck]) return;
121            if (slot_content[ck % (size_t) c.ring] != (long) ck) wrong_bytes = true;
122            wait = c.compute_ticks;
123            give_back(++ck);
124            return;
125        }
126        ++cl;   // the next layer's attention and router
127        phase = 0;
128        wait = c.publish_delay;
129    }
130    void tick_world() {
131        ++tick;
132        step_link();
133        step_consumer();
134    }
135};
136
137struct SimOps {
138    Sim& s;
139    size_t consumed() { return s.a_consumed.load(std::memory_order_acquire); }
140    bool stop() { return s.tick > 50000000; }
141    bool landed(int slot) {
142        const long k = s.slot_last_issue[(size_t) slot];
143        return k < 0 || s.landed_k[(size_t) k];
144    }
145    bool droppable(const Entry& en) { return en.job < 0; }
146    void issue(size_t k, int sl) {
147        if (k >= consumed() + (size_t) s.c.ring) s.ring_violation = true;
148        // the copy waits for the slot's previous entry to be released (its `used` event): the ring rule above
149        s.slot_last_issue[(size_t) sl] = (long) k;
150        s.queue.push_back({k, sl});
151        if (s.queue.size() == 1) s.link_left = s.c.link_ticks;
152        ++s.outstanding;
153        s.max_out = std::max(s.max_out, s.outstanding);
154        if (s.outstanding > (size_t) s.c.depth) s.depth_violation = true;
155        s.issued_k[k] = 1;
156    }
157    void idle() { s.tick_world(); }
158};
159
160// drops are recorded through the gate as seen at the walk's end; check each dropped entry was unrouted and published
161static void run_case(const Case& c, const char* name, size_t* dropped_out = nullptr, size_t* unrouted_out = nullptr) {
162    Sim s(c);
163    // the walk ticks the world only while it waits; ticks between its steps (the issuer's own work) advance it too
164    struct TickingOps : SimOps {
165        void issue(size_t k, int sl) { SimOps::issue(k, sl); s.tick_world(); }
166    } tops{{s}};
167    const rs::WalkResult r = rs::issue_walk(s.seq, (size_t) c.ring, c.depth, s.gate, s.a_issued, tops);
168    for (size_t k = 0; k < s.seq.size(); ++k)
169        if (!s.issued_k[k]) s.dropped_k[k] = 1;
170    // let the consumer finish the chunk
171    while (s.cl < c.layers && s.tick < 50000000) s.tick_world();
172    char buf[256];
173    std::snprintf(buf, sizeof buf, "%s: walk not stopped", name);
174    expect(!r.stopped, buf);
175    std::snprintf(buf, sizeof buf, "%s: issued + dropped == entries (%zu + %zu vs %zu)", name, r.issued, r.dropped, s.seq.size());
176    expect(r.issued + r.dropped == s.seq.size(), buf);
177    std::snprintf(buf, sizeof buf, "%s: a_issued covers every entry", name);
178    expect(s.a_issued.load() == s.seq.size(), buf);
179    std::snprintf(buf, sizeof buf, "%s: the consumer walked every layer", name);
180    expect(s.cl == c.layers, buf);
181    std::snprintf(buf, sizeof buf, "%s: no copy beyond the ring", name);
182    expect(!s.ring_violation, buf);
183    std::snprintf(buf, sizeof buf, "%s: at most depth copies queued (max %zu, depth %d)", name, s.max_out, c.depth);
184    expect(!s.depth_violation, buf);
185    std::snprintf(buf, sizeof buf, "%s: every routed entry read its own bytes from slot k %% ring", name);
186    expect(!s.wrong_bytes && !s.read_before_issue, buf);
187    size_t unrouted = 0, bad_drop = 0;
188    for (size_t k = 0; k < s.seq.size(); ++k) {
189        const Entry& en = s.seq[k];
190        const bool unr = s.cnt[(size_t) en.l][(size_t) en.e] == 0;
191        if (unr && en.job < 0) ++unrouted;
192        if (s.dropped_k[k] && (!unr || en.job >= 0 || !c.publish)) ++bad_drop;
193    }
194    std::snprintf(buf, sizeof buf, "%s: only unrouted, arena-copied entries of published layers dropped (%zu bad)", name, bad_drop);
195    expect(bad_drop == 0, buf);
196    std::printf("  %-34s entries %5zu  unrouted %5zu  dropped %5zu (%.0f%% of unrouted)  max queued %zu  ticks %lld\n", name,
197                s.seq.size(), unrouted, r.dropped, unrouted ? 100.0 * (double) r.dropped / (double) unrouted : 0.0,
198                s.max_out, (long long) s.tick);
199    if (dropped_out) *dropped_out = r.dropped;
200    if (unrouted_out) *unrouted_out = unrouted;
201}
202
203// The same walk on three threads (issuer, consumer, link), real atomics, no simulated clock: the bookkeeping holds
204// whatever the interleaving.
205static void threaded_case(unsigned seed, int depth) {
206    Case c;
207    c.layers = 8; c.n_expert = 128; c.ring = 96; c.depth = depth; c.seed = seed; c.unrouted = 0.45;
208    Sim s(c);
209    std::atomic<bool> done{false};
210    std::vector<std::atomic<int>> landed(s.seq.size());
211    for (auto& x : landed) x.store(0);
212    std::vector<std::atomic<long>> content((size_t) c.ring);
213    for (auto& x : content) x.store(-1);
214    std::vector<std::atomic<long>> last((size_t) c.ring);
215    for (auto& x : last) x.store(-1);
216    std::vector<std::atomic<int>> issued(s.seq.size());
217    for (auto& x : issued) x.store(0);
218    std::mutex qm;
219    std::deque<std::pair<size_t, int>> q;
220    std::atomic<size_t> out{0};
221    std::atomic<bool> depth_bad{false}, ring_bad{false}, bytes_bad{false};
222    struct ThreadOps {
223        Sim& s; std::mutex& qm; std::deque<std::pair<size_t, int>>& q; std::vector<std::atomic<long>>& last;
224        std::vector<std::atomic<int>>& landed_v; std::vector<std::atomic<int>>& issued; std::atomic<size_t>& out;
225        std::atomic<bool>& depth_bad; std::atomic<bool>& ring_bad; int depth;
226        size_t consumed() { return s.a_consumed.load(std::memory_order_acquire); }
227        bool stop() { return false; }
228        bool landed(int slot) { const long k = last[(size_t) slot].load(); return k < 0 || landed_v[(size_t) k].load(); }
229        bool droppable(const Entry& en) { return en.job < 0; }
230        void issue(size_t k, int sl) {
231            if (k >= consumed() + (size_t) s.c.ring) ring_bad = true;
232            last[(size_t) sl].store((long) k);
233            issued[k].store(1);
234            if (out.fetch_add(1) + 1 > (size_t) depth) depth_bad = true;
235            std::lock_guard<std::mutex> g(qm);
236            q.emplace_back(k, sl);
237        }
238        void idle() { std::this_thread::yield(); }
239    } ops{s, qm, q, last, landed, issued, out, depth_bad, ring_bad, depth};
240    std::thread link([&] {
241        while (!done.load()) {
242            std::pair<size_t, int> cp;
243            {
244                std::lock_guard<std::mutex> g(qm);
245                if (q.empty()) { cp.second = -1; } else { cp = q.front(); q.pop_front(); }
246            }
247            if (cp.second < 0) { std::this_thread::yield(); continue; }
248            for (int i = 0; i < 50; ++i) std::this_thread::yield();   // the copy's time
249            content[(size_t) cp.second].store((long) cp.first);
250            out.fetch_sub(1);   // before `landed`: the issuer counts a queued copy until it sees this one land
251            landed[cp.first].store(1);
252        }
253    });
254    std::thread consumer([&] {
255        for (int l = 0; l < c.layers; ++l) {
256            for (int i = 0; i < 200; ++i) std::this_thread::yield();   // attention and router
257            s.gate.publish(l, s.cnt[(size_t) l].data());
258            for (size_t k = s.seq_start[(size_t) l]; k < s.seq_start[(size_t) l + 1]; ++k) {
259                if (s.cnt[(size_t) l][(size_t) s.seq[k].e] == 0) { s.a_consumed.store(k + 1, std::memory_order_release); continue; }
260                while (s.a_issued.load(std::memory_order_acquire) <= k) std::this_thread::yield();
261                while (!landed[k].load()) std::this_thread::yield();
262                if (!issued[k].load() || content[k % (size_t) c.ring].load() != (long) k) bytes_bad = true;
263                s.a_consumed.store(k + 1, std::memory_order_release);
264            }
265        }
266    });
267    const rs::WalkResult r = rs::issue_walk(s.seq, (size_t) c.ring, depth, s.gate, s.a_issued, ops);
268    consumer.join();
269    done = true;
270    link.join();
271    char buf[200];
272    std::snprintf(buf, sizeof buf, "threaded seed %u depth %d: bookkeeping (issued %zu dropped %zu of %zu)", seed, depth,
273                  r.issued, r.dropped, s.seq.size());
274    expect(r.issued + r.dropped == s.seq.size() && !depth_bad && !ring_bad && !bytes_bad, buf);
275    size_t bad = 0;
276    for (size_t k = 0; k < s.seq.size(); ++k)
277        if (!issued[k].load() && s.cnt[(size_t) s.seq[k].l][(size_t) s.seq[k].e] != 0) ++bad;
278    std::snprintf(buf, sizeof buf, "threaded seed %u depth %d: every routed entry issued", seed, depth);
279    expect(bad == 0, buf);
280    std::printf("  threaded seed %u depth %-3d        entries %5zu  dropped %5zu\n", seed, depth, s.seq.size(), r.dropped);
281}
282
283int main() {
284    // the switch and its depth
285    expect(!rs::enabled_from(nullptr), "unset: off");
286    expect(!rs::enabled_from(""), "empty: off");
287    expect(!rs::enabled_from("0"), "0: off");
288    expect(rs::enabled_from("1"), "1: on");
289    expect(rs::depth_from(nullptr) == rs::kDefaultDepth, "depth unset: default");
290    expect(rs::depth_from("8") == 8, "depth 8");
291    expect(rs::depth_from("0") == 1 && rs::depth_from("-4") == 1, "depth clamps to 1");
292    expect(rs::depth_from("100000") == rs::kMaxDepth, "depth clamps to the maximum");
293
294    // Which chunks take the routed walk: the copy policies of STRATA_PREFILL_COPY_EVENT_EVERY > 1 and
295    // STRATA_PREFILL_COPY_WAIT_DEDUPE=1 keep the default issuer.  Otherwise a sparse consumer's wait_copied would spin
296    // on an a_rec the routed walk never publishes, and the requested release-wait deduplication would be bypassed.
297    expect(rs::eligible(true, true, false, 1, false), "streamed threaded single GPU: routed walk eligible");
298    expect(!rs::eligible(false, true, false, 1, false), "short prompt: default walk");
299    expect(!rs::eligible(true, false, false, 1, false), "inline issuer: default walk");
300    expect(!rs::eligible(true, true, true, 1, false), "peer prompt ring: default walk");
301    for (int every : {2, 16, 64}) {
302        expect(!rs::eligible(true, true, false, every, false), "sparse copied events: default walk");
303        expect(!rs::eligible(true, true, false, every, true), "sparse events and dedupe: default walk");
304    }
305    expect(!rs::eligible(true, true, false, 1, true), "release-wait dedupe: default walk");
306    // the reason the engine prints once when the switch is set and a streamed chunk keeps the default walk
307    expect(rs::held_off(true, false, 1, false) == nullptr, "eligible: no reason");
308    for (bool iss : {false, true})
309        for (bool peer : {false, true})
310            for (int every : {1, 2, 16})
311                for (bool dedupe : {false, true}) {
312                    const char* why = rs::held_off(iss, peer, every, dedupe);
313                    expect((why == nullptr) == rs::eligible(true, iss, peer, every, dedupe), "a reason exactly when held off");
314                }
315    auto names = [](const char* why, const char* what) { return why != nullptr && std::strstr(why, what) != nullptr; };
316    expect(names(rs::held_off(false, false, 1, false), "STRATA_PREFILL_ISSUER=0"), "inline issuer named");
317    expect(names(rs::held_off(true, true, 1, false), "--peer-device"), "peer ring named");
318    expect(names(rs::held_off(true, false, 4, false), "STRATA_PREFILL_COPY_EVENT_EVERY") &&
319               names(rs::held_off(true, false, 1, true), "STRATA_PREFILL_COPY_WAIT_DEDUPE"),
320           "copy policies named");
321
322    // the gate
323    {
324        rs::RouteGate g;
325        g.reset(3, 8);
326        const int32_t c1[8] = {0, 2, 0, 1, 0, 0, 5, 0};
327        expect(!g.published(1) && !g.unrouted(1, 0), "nothing published: nothing unrouted");
328        g.publish(1, c1);
329        expect(g.published(1) && !g.published(0) && !g.published(2), "one layer published");
330        bool ok = true;
331        for (int e = 0; e < 8; ++e) ok = ok && g.unrouted(1, e) == (c1[e] == 0);
332        expect(ok, "unrouted exactly where the count is 0");
333        expect(!g.unrouted(0, 0) && !g.unrouted(2, 0), "other layers keep every entry");
334        expect(!g.unrouted(1, -1) && !g.unrouted(1, 8) && !g.unrouted(-1, 0) && !g.unrouted(3, 0), "out of range: kept");
335        g.reset(3, 8);
336        expect(!g.published(1) && !g.unrouted(1, 0), "reset: nothing published");
337    }
338
339    std::printf("routed_stream_test: simulated chunks\n");
340    {
341        Case c;   // routing never published (the default walk's behaviour): every entry copied, in order
342        c.publish = false;
343        size_t d = 1;
344        run_case(c, "never published", &d);
345        expect(d == 0, "never published: nothing dropped");
346    }
347    {
348        Case c;   // the routing of every layer known before the walk could reach it: every unrouted entry dropped
349        c.publish_delay = 1; c.link_ticks = 40; c.ring = 20;
350        size_t d = 0, u = 0;
351        run_case(c, "routing long before the link", &d, &u);
352        expect(d > 0 && d >= u * 8 / 10, "early routing: most unrouted entries dropped");
353    }
354    {
355        Case c;   // a link-bound chunk: some of each layer is issued before its routing lands
356        c.publish_delay = 30; c.link_ticks = 4;
357        size_t d = 0;
358        run_case(c, "link-bound", &d);
359        expect(d > 0, "link-bound: some entries dropped");
360    }
361    {
362        Case c;   // stager jobs are never dropped
363        c.staged_every = 3; c.publish_delay = 1; c.link_ticks = 20;
364        run_case(c, "with stager jobs");
365    }
366    {
367        Case c;   // a ring smaller than a layer, depth larger than the ring
368        c.ring = 10; c.depth = 64; c.link_ticks = 2;
369        run_case(c, "ring < layer, depth > ring");
370    }
371    {
372        Case c;   // depth 1: one copy in flight at a time
373        c.depth = 1; c.link_ticks = 2;
374        run_case(c, "depth 1");
375    }
376    {
377        Case c;   // every expert routed: nothing to drop
378        c.unrouted = 0.0;
379        size_t d = 1;
380        run_case(c, "all routed", &d);
381        expect(d == 0, "all routed: nothing dropped");
382    }
383    {
384        Case c;   // nothing routed in the stream (all unrouted), fast compute
385        c.unrouted = 1.0; c.link_ticks = 5;
386        run_case(c, "none routed");
387    }
388    for (unsigned seed = 2; seed < 40; ++seed) {
389        Case c;
390        c.seed = seed;
391        c.layers = 3 + (int) (seed % 5);
392        c.n_expert = 32 + (int) (seed * 7 % 97);
393        c.ring = 4 + (int) (seed * 13 % 120);
394        c.depth = 1 + (int) (seed * 5 % 40);
395        c.unrouted = (seed % 10) / 10.0;
396        c.link_ticks = 1 + (int) (seed % 6);
397        c.publish_delay = 1 + (int) (seed * 3 % 60);
398        c.compute_ticks = (int) (seed % 4);
399        c.staged_every = seed % 3 == 0 ? 4 : 0;
400        char name[64];
401        std::snprintf(name, sizeof name, "random seed %u", seed);
402        run_case(c, name);
403    }
404    std::printf("routed_stream_test: threaded walks\n");
405    for (unsigned seed = 1; seed <= 6; ++seed) threaded_case(seed, seed % 2 ? 4 : 16);
406
407    if (g_fail) { std::fprintf(stderr, "routed_stream_test: %d failure(s)\n", g_fail); return 1; }
408    std::printf("routed_stream_test: OK\n");
409    return 0;
410}