okami.mom/strata

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

Niko1221Merge f-numa-card2: on two-socket Linux machines the engine runs on the graphics card's NUMA node2e279f758

main
12.9 KiB275 linesraw
1#pragma once
2
3#include "strata/core/conversation_cache.hpp"
4#include "strata/core/progress.hpp"
5#include "strata/platform/aux_cpus.hpp"
6#include "strata/platform/home_cpus.hpp"
7
8#include <cuda_runtime.h>
9
10#include <algorithm>
11#include <atomic>
12#include <chrono>
13#include <cstddef>
14#include <cstdlib>
15#include <mutex>
16#include <thread>
17#include <vector>
18
19#if defined(__linux__)
20#include <sched.h>
21#endif
22
23namespace strata::core { void conversation_checkpoint_join(const void* only); }
24namespace strata::core::conversation_detail {
25
26/// The private copy streams and ordering events (below) belong to a thread, but a thread can be short-lived: the layer
27/// split's later stages run each prompt chunk on a fresh std::async thread, and a checkpoint part is saved on it.  The
28/// handles used to be created per thread and never destroyed, so every such thread left one stream and one event per
29/// device behind - a few MiB of VRAM per long cold prompt on the later cards, until a stream could not be created any
30/// more and the copy failed with "out of memory" (#3350, #3470).  Now a thread hands its handles back to a process-wide
31/// pool when it ends and the next thread takes them: the number of handles is the number of threads copying at once.
32/// The pool is leaked on purpose (a thread may end after the statics are gone).
33struct CopyHandlePool {
34    std::mutex mu;
35    std::vector<std::vector<cudaStream_t>> streams;   // free ones, by device
36    std::vector<std::vector<cudaEvent_t>> events;
37    long streams_created = 0, events_created = 0;
38};
39inline CopyHandlePool& copy_handle_pool() {
40    static CopyHandlePool* p = new CopyHandlePool;
41    return *p;
42}
43/// How many streams / events the process has created for these copies (tests: it stays at the peak number of threads
44/// copying at once, not at the number of threads that ever copied).
45inline long copy_streams_created() {
46    CopyHandlePool& p = copy_handle_pool();
47    std::lock_guard<std::mutex> lk(p.mu);
48    return p.streams_created;
49}
50inline long copy_events_created() {
51    CopyHandlePool& p = copy_handle_pool();
52    std::lock_guard<std::mutex> lk(p.mu);
53    return p.events_created;
54}
55struct ThreadCopyHandles {
56    std::vector<cudaStream_t> streams;   // by device, nullptr = none yet
57    std::vector<cudaEvent_t> events;
58    ThreadCopyHandles() = default;
59    ThreadCopyHandles(const ThreadCopyHandles&) = delete;
60    ThreadCopyHandles& operator=(const ThreadCopyHandles&) = delete;
61    ~ThreadCopyHandles() {
62        CopyHandlePool& p = copy_handle_pool();
63        std::lock_guard<std::mutex> lk(p.mu);
64        if (p.streams.size() < streams.size()) p.streams.resize(streams.size());
65        if (p.events.size() < events.size()) p.events.resize(events.size());
66        for (size_t d = 0; d < streams.size(); ++d)
67            if (streams[d]) p.streams[d].push_back(streams[d]);
68        for (size_t d = 0; d < events.size(); ++d)
69            if (events[d]) p.events[d].push_back(events[d]);
70    }
71};
72inline ThreadCopyHandles& thread_copy_handles() {
73    thread_local ThreadCopyHandles t;
74    return t;
75}
76
77/// Conversation snapshot / checkpoint copies go through a private non-blocking stream of the current device
78/// instead of the legacy (null) stream.  A plain cudaMemcpy is ordered against every blocking stream of the
79/// device, and while another thread captures a graph on one (a drafter or a stage worker), HIP refuses it with
80/// "operation would make the legacy stream depend on a capturing blocking stream".  The caller's contract is
81/// unchanged: the device was synchronized before the copy (the copy itself is complete on return).
82/// private_stream: this thread's stream on the current device: one a finished thread handed back, else a new one on
83/// first use.
84inline cudaError_t private_stream(cudaStream_t& s) {
85    int dev = 0;
86    cudaError_t e = cudaGetDevice(&dev);
87    if (e != cudaSuccess) return e;
88    std::vector<cudaStream_t>& streams = thread_copy_handles().streams;
89    if (dev < 0) dev = 0;
90    if ((size_t) dev >= streams.size()) streams.resize((size_t) dev + 1, nullptr);
91    if (!streams[(size_t) dev]) {
92        CopyHandlePool& p = copy_handle_pool();
93        std::lock_guard<std::mutex> lk(p.mu);
94        if ((size_t) dev < p.streams.size() && !p.streams[(size_t) dev].empty()) {
95            streams[(size_t) dev] = p.streams[(size_t) dev].back();
96            p.streams[(size_t) dev].pop_back();
97        } else {
98            e = cudaStreamCreateWithFlags(&streams[(size_t) dev], cudaStreamNonBlocking);
99            if (e != cudaSuccess) { streams[(size_t) dev] = nullptr; return e; }
100            ++p.streams_created;
101        }
102    }
103    s = streams[(size_t) dev];
104    return cudaSuccess;
105}
106
107/// #2409: true when a copy on `dev` from this thread needs no new stream: the thread has one, or a thread that ended left
108/// one in the pool. false: the next copy creates one (a small device allocation, which can fail on a full card).
109inline bool copy_stream_ready(int dev) {
110    if (dev < 0) dev = 0;
111    const std::vector<cudaStream_t>& streams = thread_copy_handles().streams;
112    if ((size_t) dev < streams.size() && streams[(size_t) dev]) return true;
113    CopyHandlePool& p = copy_handle_pool();
114    std::lock_guard<std::mutex> lk(p.mu);
115    return (size_t) dev < p.streams.size() && !p.streams[(size_t) dev].empty();
116}
117
118/// STRATA_TEST_COPY_FAIL_AT=N (tests only, #3350): the N-th snapshot / checkpoint copy of the process fails with
119/// cudaErrorMemoryAllocation, as when a card has no memory left for the copy.  Unset: nothing.
120inline long test_copy_fail_at() {
121    static const long v = [] { const char* e = std::getenv("STRATA_TEST_COPY_FAIL_AT"); return e ? std::atol(e) : 0L; }();
122    return v;
123}
124
125/// First thing a background copy thread does (STRATA_CKPT_ASYNC, STRATA_PARK_ASYNC): a thread the host creates
126/// inherits the host's one CPU (strata/platform/aux_cpus.hpp), where its memcpys would take turns with the decode.
127/// Wide first: the mask the aux placement keeps as this thread's own is the one restore() puts back (a request with
128/// aux_cpus=0), and the host's one CPU must not be it.  Wide means the process's own CPU set from the start-up
129/// (strata/platform/home_cpus.hpp: every CPU unless the engine placed itself on the card's NUMA node).  No output
130/// depends on where a thread runs.
131inline void background_thread_placement() {
132#if defined(__linux__)
133    strata::platform::widen_to_home();               // the kernel keeps the CPUs the cgroup allows
134    strata::aux_cpus::pin_current_thread();          // (a no-op while the feature is off)
135#endif
136}
137
138/// `queued`: the copy is only queued on the private stream, and the caller synchronizes the device (or orders a
139/// later launch after it with order_after_queued) before anything reads the target or writes the source.
140inline cudaError_t copy_nonblocking(void* dst, const void* src, size_t bytes, bool queued = false) {
141    if (const long at = test_copy_fail_at(); at > 0) {
142        static std::atomic<long> copies{0};
143        if (++copies == at) return cudaErrorMemoryAllocation;
144    }
145    cudaStream_t s = nullptr;
146    cudaError_t e = private_stream(s);
147    if (e != cudaSuccess) return e;
148    e = cudaMemcpyAsync(dst, src, bytes, cudaMemcpyDefault, s);
149    if (e != cudaSuccess || queued) return e;
150    e = cudaStreamSynchronize(s);
151    core::progress_beat();   // #2049: a parked conversation is many of these; each one that lands is progress
152    return e;
153}
154
155/// #2049 #2065 #1971: a host-to-host copy that tells the watchdog it is moving.  Parked state (the running
156/// checkpoints, the K/V segments) sits in ordinary pageable memory for the whole session; when the OS has written
157/// it to the pagefile, copying it back runs at the drive's page-in speed (measured in the reports: ~190 hard faults
158/// a second, under 1 MB/s) and one memcpy of it stays silent past the 60 s limit, so the watchdog ended an engine
159/// that was only slow.  One beat per 1 MiB slice keeps a copy that moves alive and still lets a real stall show.
160/// STRATA_TEST_SLOW_COPY_US=N (tests only): every 1 MiB slice of a checkpoint copy takes N microseconds more, as when
161/// the OS has paged the checkpoints out and each slice is read back from the drive.  Unset: no delay.
162inline long test_slow_copy_us() {
163    static const long v = [] { const char* e = std::getenv("STRATA_TEST_SLOW_COPY_US"); return e ? std::atol(e) : 0L; }();
164    return v;
165}
166
167template<class T>
168inline std::vector<T> copy_beating(const std::vector<T>& src) {
169    std::vector<T> out;
170    out.reserve(src.size());
171    const size_t step = std::max<size_t>(1, ((size_t) 1 << 20) / sizeof(T));
172    for (size_t at = 0; at < src.size(); at += step) {
173        out.insert(out.end(), src.begin() + (std::ptrdiff_t) at,
174                   src.begin() + (std::ptrdiff_t) std::min(src.size(), at + step));
175        if (const long us = test_slow_copy_us(); us > 0) std::this_thread::sleep_for(std::chrono::microseconds(us));
176        core::progress_beat();
177    }
178    return out;
179}
180
181inline ConversationCheckpoint copy_checkpoint_beating(const ConversationCheckpoint& c) {
182    ConversationCheckpoint o;
183    o.ids = copy_beating(c.ids);
184    o.imgs = copy_beating(c.imgs);
185    o.gdn = copy_beating(c.gdn);
186    o.dev_tag = c.dev_tag;   // the same bytes
187    o.ple = copy_beating(c.ple);
188    o.tails = copy_beating(c.tails);
189    o.dead = copy_beating(c.dead);
190    o.block_pos = copy_beating(c.block_pos);
191    o.used = c.used;
192    o.pinned = c.pinned;
193    o.stage_parts.reserve(c.stage_parts.size());
194    for (const auto& part : c.stage_parts) o.stage_parts.push_back(copy_checkpoint_beating(part));
195    return o;
196}
197
198/// copy_beating into `out`'s storage (its capacity kept: a vector whose pages are in takes the copy without faults)
199template<class V>
200inline void assign_beating(V& out, const V& src) {
201    out.clear();
202    out.reserve(src.size());
203    const size_t step = std::max<size_t>(1, ((size_t) 1 << 20) / sizeof(typename V::value_type));
204    for (size_t at = 0; at < src.size(); at += step) {
205        out.insert(out.end(), src.begin() + (std::ptrdiff_t) at,
206                   src.begin() + (std::ptrdiff_t) std::min(src.size(), at + step));
207        if (const long us = test_slow_copy_us(); us > 0) std::this_thread::sleep_for(std::chrono::microseconds(us));
208        core::progress_beat();
209    }
210}
211
212/// copy_checkpoint_beating into `o`, a dropped checkpoint's storage (STRATA_CKPT_POOL): the same bytes
213inline void copy_checkpoint_into(ConversationCheckpoint& o, const ConversationCheckpoint& c) {
214    assign_beating(o.ids, c.ids);
215    assign_beating(o.imgs, c.imgs);
216    assign_beating(o.gdn, c.gdn);
217    o.dev_tag = c.dev_tag;
218    assign_beating(o.ple, c.ple);
219    assign_beating(o.tails, c.tails);
220    assign_beating(o.dead, c.dead);
221    assign_beating(o.block_pos, c.block_pos);
222    o.used = c.used;
223    o.pinned = c.pinned;
224    o.stage_parts.clear();
225    for (const auto& part : c.stage_parts) o.stage_parts.push_back(copy_checkpoint_beating(part));
226}
227
228/// `storage` (optional): dropped checkpoints whose vectors the copies go into, taken from its back while it lasts
229inline std::vector<ConversationCheckpoint> copy_checkpoints_beating(const std::vector<ConversationCheckpoint>& cs,
230                                                                    std::vector<ConversationCheckpoint>* storage = nullptr) {
231    for (const auto& c : cs) core::conversation_checkpoint_join(c.gdn.data());
232    std::vector<ConversationCheckpoint> out;
233    out.reserve(cs.size());
234    for (const auto& c : cs) {
235        if (storage != nullptr && !storage->empty()) {
236            out.push_back(std::move(storage->back()));
237            storage->pop_back();
238            copy_checkpoint_into(out.back(), c);
239        } else {
240            out.push_back(copy_checkpoint_beating(c));
241        }
242    }
243    return out;
244}
245
246/// Work queued on the legacy stream after this call starts after every copy this thread queued on the current
247/// device's private stream (an event the legacy stream waits for; no host wait).
248inline cudaError_t order_after_queued() {
249    cudaStream_t s = nullptr;
250    cudaError_t e = private_stream(s);
251    if (e != cudaSuccess) return e;
252    int dev = 0;
253    e = cudaGetDevice(&dev);
254    if (e != cudaSuccess) return e;
255    std::vector<cudaEvent_t>& events = thread_copy_handles().events;
256    if (dev < 0) dev = 0;
257    if ((size_t) dev >= events.size()) events.resize((size_t) dev + 1, nullptr);
258    if (!events[(size_t) dev]) {
259        CopyHandlePool& p = copy_handle_pool();
260        std::lock_guard<std::mutex> lk(p.mu);
261        if ((size_t) dev < p.events.size() && !p.events[(size_t) dev].empty()) {
262            events[(size_t) dev] = p.events[(size_t) dev].back();
263            p.events[(size_t) dev].pop_back();
264        } else {
265            e = cudaEventCreateWithFlags(&events[(size_t) dev], cudaEventDisableTiming);
266            if (e != cudaSuccess) { events[(size_t) dev] = nullptr; return e; }
267            ++p.events_created;
268        }
269    }
270    e = cudaEventRecord(events[(size_t) dev], s);
271    if (e != cudaSuccess) return e;
272    return cudaStreamWaitEvent(nullptr, events[(size_t) dev], 0);
273}
274
275} // namespace strata::core::conversation_detail