okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2e279f758
main
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 ; 37long streams_created = 0 ,events_created = 0 ; 38}; 39inline CopyHandlePool & copy_handle_pool () { 40static CopyHandlePool * p = new CopyHandlePool ; 41return * 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 () { 46CopyHandlePool & p = copy_handle_pool (); 47 std::lock_guard < std::mutex > lk (p .mu ); 48return p .streams_created ; 49} 50inline long copy_events_created () { 51CopyHandlePool & p = copy_handle_pool (); 52 std::lock_guard < std::mutex > lk (p .mu ); 53return p .events_created ; 54} 55struct ThreadCopyHandles { 56 std::vector < cudaStream_t > streams ;// by device, nullptr = none yet 57 std::vector < cudaEvent_t > events ; 58ThreadCopyHandles ()= default ; 59ThreadCopyHandles (const ThreadCopyHandles & )= delete ; 60ThreadCopyHandles & operator= (const ThreadCopyHandles & )= delete ; 61 ~ThreadCopyHandles () { 62CopyHandlePool & p = copy_handle_pool (); 63 std::lock_guard < std::mutex > lk (p .mu ); 64if (p .streams .size ()< streams .size ())p .streams .resize (streams .size ()); 65if (p .events .size ()< events .size ())p .events .resize (events .size ()); 66for (size_t d = 0 ;d < streams .size ();++ d ) 67if (streams [d ])p .streams [d ].push_back (streams [d ]); 68for (size_t d = 0 ;d < events .size ();++ d ) 69if (events [d ])p .events [d ].push_back (events [d ]); 70 } 71}; 72inline ThreadCopyHandles & thread_copy_handles () { 73 thread_localThreadCopyHandles t ; 74return 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 ) { 85int dev = 0 ; 86cudaError_t e = cudaGetDevice (& dev ); 87if (e != cudaSuccess )return e ; 88 std::vector < cudaStream_t >& streams = thread_copy_handles ().streams ; 89if (dev < 0 )dev = 0 ; 90if ((size_t )dev >=streams .size ())streams .resize ((size_t )dev + 1 ,nullptr ); 91if (!streams [(size_t )dev ]) { 92CopyHandlePool & p = copy_handle_pool (); 93 std::lock_guard < std::mutex > lk (p .mu ); 94if ((size_t )dev < p .streams .size ()&& !p .streams [(size_t )dev ].empty ()) { 95streams [(size_t )dev ]= p .streams [(size_t )dev ].back (); 96p .streams [(size_t )dev ].pop_back (); 97 }else { 98e = cudaStreamCreateWithFlags (& streams [(size_t )dev ],cudaStreamNonBlocking ); 99if (e != cudaSuccess ) {streams [(size_t )dev ]= nullptr ;return e ; } 100++ p .streams_created ; 101 } 102 } 103s = streams [(size_t )dev ]; 104return 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 ) { 110if (dev < 0 )dev = 0 ; 111const std::vector < cudaStream_t >& streams = thread_copy_handles ().streams ; 112if ((size_t )dev < streams .size ()&& streams [(size_t )dev ])return true; 113CopyHandlePool & p = copy_handle_pool (); 114 std::lock_guard < std::mutex > lk (p .mu ); 115return (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 () { 121static const long v = [] {const char * e = std::getenv ("STRATA_TEST_COPY_FAIL_AT" );return e ? std::atol (e ) :0L ; }(); 122return 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) { 141if (const long at = test_copy_fail_at ();at > 0 ) { 142static std::atomic < long > copies {0 }; 143if (++ copies == at )return cudaErrorMemoryAllocation ; 144 } 145cudaStream_t s = nullptr ; 146cudaError_t e = private_stream (s ); 147if (e != cudaSuccess )return e ; 148e = cudaMemcpyAsync (dst ,src ,bytes ,cudaMemcpyDefault ,s ); 149if (e != cudaSuccess || queued )return e ; 150e = cudaStreamSynchronize (s ); 151 core::progress_beat ();// #2049: a parked conversation is many of these; each one that lands is progress 152return 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 () { 163static const long v = [] {const char * e = std::getenv ("STRATA_TEST_SLOW_COPY_US" );return e ? std::atol (e ) :0L ; }(); 164return v ; 165} 166 167template < class T > 168inline std::vector < T > copy_beating (const std::vector < T >& src ) { 169 std::vector < T > out ; 170out .reserve (src .size ()); 171const size_t step = std::max < size_t > (1 , ((size_t )1 <<20 ) /sizeof (T )); 172for (size_t at = 0 ;at < src .size ();at += step ) { 173out .insert (out .end (),src .begin ()+ (std::ptrdiff_t )at , 174src .begin ()+ (std::ptrdiff_t ) std::min (src .size (),at + step )); 175if (const long us = test_slow_copy_us ();us > 0 ) std::this_thread::sleep_for (std::chrono::microseconds (us )); 176 core::progress_beat (); 177 } 178return out ; 179} 180 181inline ConversationCheckpoint copy_checkpoint_beating (const ConversationCheckpoint & c ) { 182ConversationCheckpoint o ; 183o .ids = copy_beating (c .ids ); 184o .imgs = copy_beating (c .imgs ); 185o .gdn = copy_beating (c .gdn ); 186o .dev_tag = c .dev_tag ;// the same bytes 187o .ple = copy_beating (c .ple ); 188o .tails = copy_beating (c .tails ); 189o .dead = copy_beating (c .dead ); 190o .block_pos = copy_beating (c .block_pos ); 191o .used = c .used ; 192o .pinned = c .pinned ; 193o .stage_parts .reserve (c .stage_parts .size ()); 194for (const auto & part :c .stage_parts )o .stage_parts .push_back (copy_checkpoint_beating (part )); 195return 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 ) { 201out .clear (); 202out .reserve (src .size ()); 203const size_t step = std::max < size_t > (1 , ((size_t )1 <<20 ) /sizeof (typename V ::value_type )); 204for (size_t at = 0 ;at < src .size ();at += step ) { 205out .insert (out .end (),src .begin ()+ (std::ptrdiff_t )at , 206src .begin ()+ (std::ptrdiff_t ) std::min (src .size (),at + step )); 207if (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 ) { 214assign_beating (o .ids ,c .ids ); 215assign_beating (o .imgs ,c .imgs ); 216assign_beating (o .gdn ,c .gdn ); 217o .dev_tag = c .dev_tag ; 218assign_beating (o .ple ,c .ple ); 219assign_beating (o .tails ,c .tails ); 220assign_beating (o .dead ,c .dead ); 221assign_beating (o .block_pos ,c .block_pos ); 222o .used = c .used ; 223o .pinned = c .pinned ; 224o .stage_parts .clear (); 225for (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 ) { 231for (const auto & c :cs ) core::conversation_checkpoint_join (c .gdn .data ()); 232 std::vector < ConversationCheckpoint > out ; 233out .reserve (cs .size ()); 234for (const auto & c :cs ) { 235if (storage != nullptr && !storage -> empty ()) { 236out .push_back (std::move (storage -> back ())); 237storage -> pop_back (); 238copy_checkpoint_into (out .back (),c ); 239 }else { 240out .push_back (copy_checkpoint_beating (c )); 241 } 242 } 243return 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 () { 249cudaStream_t s = nullptr ; 250cudaError_t e = private_stream (s ); 251if (e != cudaSuccess )return e ; 252int dev = 0 ; 253e = cudaGetDevice (& dev ); 254if (e != cudaSuccess )return e ; 255 std::vector < cudaEvent_t >& events = thread_copy_handles ().events ; 256if (dev < 0 )dev = 0 ; 257if ((size_t )dev >=events .size ())events .resize ((size_t )dev + 1 ,nullptr ); 258if (!events [(size_t )dev ]) { 259CopyHandlePool & p = copy_handle_pool (); 260 std::lock_guard < std::mutex > lk (p .mu ); 261if ((size_t )dev < p .events .size ()&& !p .events [(size_t )dev ].empty ()) { 262events [(size_t )dev ]= p .events [(size_t )dev ].back (); 263p .events [(size_t )dev ].pop_back (); 264 }else { 265e = cudaEventCreateWithFlags (& events [(size_t )dev ],cudaEventDisableTiming ); 266if (e != cudaSuccess ) {events [(size_t )dev ]= nullptr ;return e ; } 267++ p .events_created ; 268 } 269 } 270e = cudaEventRecord (events [(size_t )dev ],s ); 271if (e != cudaSuccess )return e ; 272return cudaStreamWaitEvent (nullptr ,events [(size_t )dev ],0 ); 273} 274 275}// namespace strata::core::conversation_detail