okami.mom/strata

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

Niko1221Merge f-own-3v (aec86299d) into f-own-int: our own Qwen vision tower (mtmd stays the default)0479b72e9

main
5.0 KiB123 linesraw
1// tools/vision/own/cpu_team.h - a small fork-join team of persistent threads for the CPU tower.
2//
3// run(n, f) calls f(task, thread) for task = 0 .. n-1 on the team (the caller is thread 0) and returns when all are done.  Workers spin for a short time
4// between runs (a tower makes hundreds of runs per picture, a few microseconds apart) and then sleep on a condition variable, so an idle reader costs nothing.
5// Claiming a task is a compare-and-swap on a counter tagged with the run's generation (the completion protocol of the engine's expert pool): a worker that
6// wakes late can never take a task of the next run, and no task runs twice.
7#pragma once
8
9#include <atomic>
10#include <chrono>
11#include <condition_variable>
12#include <cstdint>
13#include <functional>
14#include <mutex>
15#include <thread>
16#include <vector>
17
18#if defined(__x86_64__) || defined(_M_X64) || defined(__i386__)
19#if defined(_MSC_VER)
20#include <intrin.h>
21#define STRATA_VIT_PAUSE() _mm_pause()
22#else
23#define STRATA_VIT_PAUSE() __builtin_ia32_pause()
24#endif
25#else
26#define STRATA_VIT_PAUSE() ((void) 0)
27#endif
28
29namespace strata_vit {
30
31class Team {
32public:
33    explicit Team(int n) : n_(n < 1 ? 1 : n) {
34        for (int t = 1; t < n_; ++t) workers_.emplace_back([this, t] { loop(t); });
35    }
36    ~Team() {
37        {
38            std::lock_guard<std::mutex> lk(mu_);
39            stop_.store(true);
40            gen_.fetch_add(1);
41        }
42        cv_.notify_all();
43        for (auto& w : workers_) w.join();
44    }
45    Team(const Team&) = delete;
46    Team& operator=(const Team&) = delete;
47    int size() const { return n_; }
48
49    void run(int ntasks, const std::function<void(int task, int thread)>& f) {
50        if (ntasks <= 0) return;
51        if (n_ == 1 || ntasks == 1) {
52            for (int i = 0; i < ntasks; ++i) f(i, 0);
53            return;
54        }
55        fn_ = &f;
56        remaining_.store(ntasks, std::memory_order_relaxed);
57        const uint64_t g = gen_.load(std::memory_order_relaxed) + 1;
58        limit_.store((g << 32) | (uint32_t) ntasks, std::memory_order_relaxed);     // the task count carries the run's tag, as the claim counter does
59        next_.store(g << 32, std::memory_order_release);
60        gen_.store(g, std::memory_order_seq_cst);
61        if (sleepers_.load(std::memory_order_seq_cst) > 0) {
62            std::lock_guard<std::mutex> lk(mu_);
63            cv_.notify_all();
64        }
65        work(g, 0);
66        while (remaining_.load(std::memory_order_acquire) > 0) STRATA_VIT_PAUSE();
67    }
68
69private:
70    // claim and run tasks of generation g
71    void work(uint64_t g, int thread) {
72        for (;;) {
73            uint64_t cur = next_.load(std::memory_order_acquire);
74            if ((cur >> 32) != g) return;                    // a later run is on: this one is over
75            const uint32_t idx = (uint32_t) cur;
76            // The task count must be read WITH its tag: a late worker (a run behind) that read a plain count already rewritten for the next run could claim an
77            // index past its own run's end while the counter still shows the old run, and run a task of the new run's function twice (found by the unit test, 31
78            // failures in 60 runs).  A count of another run ends this worker's pass.
79            const uint64_t lim = limit_.load(std::memory_order_relaxed);
80            if ((lim >> 32) != g || idx >= (uint32_t) lim) return;
81            if (!next_.compare_exchange_weak(cur, cur + 1, std::memory_order_acq_rel)) continue;
82            (*fn_)((int) idx, thread);
83            remaining_.fetch_sub(1, std::memory_order_release);
84        }
85    }
86
87    void loop(int thread) {
88        uint64_t seen = 0;
89        for (;;) {
90            uint64_t g = gen_.load(std::memory_order_seq_cst);
91            if (g == seen) {
92                const auto t0 = std::chrono::steady_clock::now();
93                int spins = 0;
94                while ((g = gen_.load(std::memory_order_acquire)) == seen) {
95                    STRATA_VIT_PAUSE();
96                    if ((++spins & 255) == 0 && std::chrono::steady_clock::now() - t0 > std::chrono::microseconds(150)) {
97                        std::unique_lock<std::mutex> lk(mu_);
98                        sleepers_.fetch_add(1, std::memory_order_seq_cst);
99                        cv_.wait(lk, [&] { return gen_.load(std::memory_order_seq_cst) != seen; });
100                        sleepers_.fetch_sub(1, std::memory_order_seq_cst);
101                        g = gen_.load(std::memory_order_seq_cst);
102                        break;
103                    }
104                }
105            }
106            if (stop_.load()) return;
107            seen = g;
108            work(g, thread);
109        }
110    }
111
112    const int n_;
113    std::vector<std::thread> workers_;
114    const std::function<void(int, int)>* fn_ = nullptr;
115    std::atomic<int> remaining_{0};
116    std::atomic<uint64_t> next_{0}, gen_{0}, limit_{0};      // next_: (run tag << 32) | next task; limit_: (run tag << 32) | task count
117    std::atomic<int> sleepers_{0};
118    std::atomic<bool> stop_{false};
119    std::mutex mu_;
120    std::condition_variable cv_;
121};
122
123}  // namespace strata_vit