ggml
[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)
Brought by drakestapleton
ggml / src / ggml-cuda / allreduce.cu
| 1 | #include "allreduce.cuh" |
| 2 | |
| 3 | #if !defined(GGML_USE_MUSA) |
| 4 | |
| 5 | #include "convert.cuh" |
| 6 | #include "ggml-impl.h" |
| 7 | |
| 8 | #include <algorithm> |
| 9 | #include <cstdlib> |
| 10 | #include <cstring> |
| 11 | #include <limits> |
| 12 | |
| 13 | // --------------------------------------------------------------------------- |
| 14 | // AllReduce for tensor-parallel inference across two GPUs (CUDA or |
| 15 | // ROCm/HIP). |
| 16 | // |
| 17 | // Provides an in-place sum reduction over matching tensors on two GPUs |
| 18 | // in the same process. Used by the tensor-split path alongside NCCL; |
| 19 | // targets setups without NVLink/xGMI, where data is exchanged between the |
| 20 | // GPUs by staging it through pinned host memory over PCIe. |
| 21 | // |
| 22 | // Two reduction strategies are selected per call by tensor size: |
| 23 | // |
| 24 | // * Chunked kernel path (small reductions): a single CUDA kernel both |
| 25 | // stages data through pinned host memory and performs the local sum. |
| 26 | // Cross-GPU synchronization happens *inside the kernel* (busy-wait on |
| 27 | // a host-memory flag), which keeps launch overhead low for the |
| 28 | // latency-sensitive token-generation case. |
| 29 | // |
| 30 | // * Copy-engine path (large reductions): the transfer is split into |
| 31 | // D2H + H2D cudaMemcpyAsync chunks driven by the GPU's copy engine, |
| 32 | // followed by a small device-side add kernel. Cross-GPU |
| 33 | // synchronization happens *outside the kernel*, via CUDA events |
| 34 | // between streams. This keeps the compute engine free while large |
| 35 | // transfers are in flight, which matters for prefill-sized tensors. |
| 36 | // Reductions larger than the per-call inner cap are processed by an |
| 37 | // outer chunker that issues sequential inner calls. |
| 38 | // --------------------------------------------------------------------------- |
| 39 | |
| 40 | // --------------------------------------------------------------------------- |
| 41 | // Cross-GPU signal mechanism |
| 42 | // |
| 43 | // One int per (slot, rank) pair in pinned host memory. Each AR call writes a |
| 44 | // strictly increasing token (= the AR call number) into its own arrival int. |
| 45 | // The peer spins until its read of the other's arrival int equals the token |
| 46 | // it expects for this call -- a mismatch means the peer hasn't arrived yet. |
| 47 | // Tokens never repeat over realistic call rates (32-bit int wraps in tens of |
| 48 | // days at thousands of ARs/sec), so arrival ints don't need to be reset |
| 49 | // between calls; we initialize once at pipeline init and let the values |
| 50 | // accumulate. |
| 51 | // |
| 52 | // There is exactly one writer (the owning GPU) and one reader (the peer), so |
| 53 | // we don't need atomics. A volatile store paired with __threadfence_system() |
| 54 | // provides the release ordering that makes the D2H writes visible system-wide |
| 55 | // before the arrival token is observed. |
| 56 | // |
| 57 | // atomicAdd_system() requires hostNativeAtomicSupported, which is unavailable |
| 58 | // on PCIe-attached consumer GPUs without NVLink, so the volatile path is the |
| 59 | // portable choice. |
| 60 | // --------------------------------------------------------------------------- |
| 61 | |
| 62 | static __device__ __forceinline__ void ggml_cuda_ar_signal_set(int * p, int token) { |
| 63 | *(volatile int *)p = token; |
| 64 | } |
| 65 | static __device__ __forceinline__ int ggml_cuda_ar_signal_get(const int * p) { |
| 66 | return *(const volatile int *)p; |
| 67 | } |
| 68 | |
| 69 | // Byte spacing between adjacent arrival ints. 64 bytes (one cache line) |
| 70 | // ensures each GPU/block's arrival slot lives on its own line, preventing |
| 71 | // false-sharing stalls on the polling GPU. |
| 72 | static constexpr size_t GGML_CUDA_AR_ARRIVAL_STRIDE = 64; |
| 73 | |
| 74 | // Number of blocks the chunked kernel launches with. Each block stripes a |
| 75 | // disjoint slice of the data and synchronizes through its own arrival-token |
| 76 | // slot so multiple SMs can pump PCIe stores in parallel. |
| 77 | static constexpr int GGML_CUDA_AR_KERNEL_BLOCKS = 8; |
| 78 | |
| 79 | // --------------------------------------------------------------------------- |
| 80 | // Chunked kernel AllReduce -- 2 GPUs, supports float, half, and bfloat16. |
| 81 | // |
| 82 | // Both GPUs run this kernel simultaneously on independent streams. sendbuf |
| 83 | // and recvbuf live in T_dst (the caller's tensor type); host_mine / host_other |
| 84 | // carry data in T_wire (the on-wire type, possibly narrower than T_dst -- e.g. |
| 85 | // T_dst=F32 with T_wire=BF16 halves the bytes pushed across PCIe). When |
| 86 | // T_dst == T_wire the casts below are no-ops. |
| 87 | // |
| 88 | // Each GPU runs three phases: |
| 89 | // |
| 90 | // Phase 1 (all threads): cast sendbuf (T_dst) -> T_wire and store as |
| 91 | // single-instruction-width vectors into host_mine. |
| 92 | // __threadfence_system() commits these writes to host |
| 93 | // memory. |
| 94 | // Phase 2 (thread 0): write token to arrival_mine; spin until |
| 95 | // arrival_other == token. |
| 96 | // Phase 3 (all threads): read T_wire vectors from host_other, cast |
| 97 | // each element to T_dst, and sum with the local |
| 98 | // sendbuf value (also rounded through T_wire so that |
| 99 | // both GPUs truncate identically -- this guarantees |
| 100 | // bit-equivalent results across the two devices). |
| 101 | // |
| 102 | // Multi-block: blocks stripe vectors across (gridDim.x * blockDim.x) global |
| 103 | // threads to keep multiple SMs issuing PCIe stores in parallel. Each block |
| 104 | // has its own arrival-token slot (offset by blockIdx.x * ARRIVAL_STRIDE); |
| 105 | // thread 0 of each block signals/spins on that slot independently of other |
| 106 | // blocks. Tail elements (the leftover < ELEMS_PER_VEC at the end) are |
| 107 | // handled only by block 0 to avoid cross-block writes to the same slots. |
| 108 | // --------------------------------------------------------------------------- |
| 109 | template <typename T_dst, typename T_wire> |
| 110 | static __global__ void ggml_cuda_ar_kernel( |
| 111 | const T_dst * sendbuf, |
| 112 | T_dst * recvbuf, |
| 113 | T_wire * __restrict__ host_mine, |
| 114 | const T_wire * __restrict__ host_other, |
| 115 | int count, |
| 116 | int * arrival_mine, |
| 117 | int * arrival_other, |
| 118 | int token) { |
| 119 | |
| 120 | // Vector unit for the wire type, sized to the arch's widest single-instruction |
| 121 | // copy (16 B on Volta+). Each phase-1 iter writes one vector to host memory; |
| 122 | // each phase-3 iter reads one and produces ELEMS_PER_VEC sums. |
| 123 | constexpr int ELEMS_PER_VEC = ggml_cuda_get_max_cpy_bytes() / sizeof(T_wire); |
| 124 | constexpr int ARRIVAL_INTS = (int)(GGML_CUDA_AR_ARRIVAL_STRIDE / sizeof(int)); |
| 125 | |
| 126 | const int tid = threadIdx.x; |
| 127 | const int nt = blockDim.x; |
| 128 | const int bid = blockIdx.x; |
| 129 | const int gtid = bid * nt + tid; |
| 130 | const int gnt = gridDim.x * nt; |
| 131 | const int count_vec = count / ELEMS_PER_VEC; |
| 132 | const int tail = count_vec * ELEMS_PER_VEC; |
| 133 | |
| 134 | // Phase 1: cast sendbuf (T_dst) -> host_mine (T_wire) and store as vectors. |
| 135 | { |
| 136 | for (int i = gtid; i < count_vec; i += gnt) { |
| 137 | const int off = i * ELEMS_PER_VEC; |
| 138 | T_wire wire[ELEMS_PER_VEC]; |
| 139 | #pragma unroll |
| 140 | for (int k = 0; k < ELEMS_PER_VEC; ++k) { |
| 141 | wire[k] = ggml_cuda_cast<T_wire>(sendbuf[off + k]); |
| 142 | } |
| 143 | ggml_cuda_memcpy_1<sizeof(wire)>(&host_mine[off], wire); |
| 144 | } |
| 145 | if (bid == 0 && tid < count - tail) { |
| 146 | host_mine[tail + tid] = ggml_cuda_cast<T_wire>(sendbuf[tail + tid]); |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | // Commit this block's host writes before signalling. |
| 151 | __threadfence_system(); |
| 152 | __syncthreads(); |
| 153 | |
| 154 | // Phase 2: thread 0 of each block signals on its own arrival slot, then |
| 155 | // spins for the matching slot from peer. Per-block tokens mean blocks |
| 156 | // proceed independently -- no inter-block barrier needed. |
| 157 | if (tid == 0) { |
| 158 | int * my_slot = arrival_mine + bid * ARRIVAL_INTS; |
| 159 | const int * other_slot = arrival_other + bid * ARRIVAL_INTS; |
| 160 | |
| 161 | ggml_cuda_ar_signal_set(my_slot, token); |
| 162 | __threadfence_system(); // make our signal visible system-wide |
| 163 | |
| 164 | while (ggml_cuda_ar_signal_get(other_slot) != token) { |
| 165 | #ifdef GGML_USE_HIP |
| 166 | // Equals ~100ns at 2500 MHz (sleeps for n * [1,64] clock cycles) |
| 167 | __builtin_amdgcn_s_sleep(4); |
| 168 | #elif __CUDA_ARCH__ >= GGML_CUDA_CC_VOLTA |
| 169 | __nanosleep(100); |
| 170 | #else |
| 171 | NO_DEVICE_CODE; |
| 172 | #endif // GGML_USE_HIP |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | __syncthreads(); |
| 177 | |
| 178 | // Acquire peer's host_other writes (this block's stripe of them). |
| 179 | __threadfence_system(); |
| 180 | |
| 181 | // Phase 3: read peer's T_wire vector, cast both sides through T_wire for |
| 182 | // bit-equivalence, sum in T_dst precision, and write back to recvbuf. |
| 183 | { |
| 184 | for (int i = gtid; i < count_vec; i += gnt) { |
| 185 | const int off = i * ELEMS_PER_VEC; |
| 186 | T_wire wire[ELEMS_PER_VEC]; |
| 187 | ggml_cuda_memcpy_1<sizeof(wire)>(wire, &host_other[off]); |
| 188 | #pragma unroll |
| 189 | for (int k = 0; k < ELEMS_PER_VEC; ++k) { |
| 190 | const T_wire d_low = ggml_cuda_cast<T_wire>(sendbuf[off + k]); |
| 191 | recvbuf[off + k] = ggml_cuda_cast<T_dst>( |
| 192 | ggml_cuda_cast<float>(d_low) + ggml_cuda_cast<float>(wire[k])); |
| 193 | } |
| 194 | } |
| 195 | if (bid == 0 && tid < count - tail) { |
| 196 | const T_wire d_low = ggml_cuda_cast<T_wire>(sendbuf[tail + tid]); |
| 197 | recvbuf[tail + tid] = ggml_cuda_cast<T_dst>( |
| 198 | ggml_cuda_cast<float>(d_low) + |
| 199 | ggml_cuda_cast<float>(host_other[tail + tid])); |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | // Combined load-convert-add kernel. The peer's contribution arrives as T_src |
| 205 | // (which may be a lower-precision type than T_dst when the BF16 round-trip is |
| 206 | // active). For bit-equivalence between the two GPUs, dst is first rounded |
| 207 | // through T_src's precision via ggml_cuda_cast -- peer already truncated its |
| 208 | // own value the same way before sending -- so both sides perform identical |
| 209 | // arithmetic. When T_dst == T_src the round-trip cast is a no-op. |
| 210 | template <typename T_dst, typename T_src> |
| 211 | static __global__ void ggml_cuda_ar_add_kernel( |
| 212 | T_dst * __restrict__ dst, |
| 213 | const T_src * __restrict__ src, |
| 214 | int count) { |
| 215 | const int tid = blockIdx.x * blockDim.x + threadIdx.x; |
| 216 | const int nt = gridDim.x * blockDim.x; |
| 217 | for (int i = tid; i < count; i += nt) { |
| 218 | const T_src d_low = ggml_cuda_cast<T_src>(dst[i]); |
| 219 | dst[i] = ggml_cuda_cast<T_dst>( |
| 220 | ggml_cuda_cast<float>(d_low) + ggml_cuda_cast<float>(src[i])); |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | // --------------------------------------------------------------------------- |
| 225 | // Pipeline structure |
| 226 | // --------------------------------------------------------------------------- |
| 227 | |
| 228 | // Number of slots in the event / arrival ring. Two slots is sufficient: |
| 229 | // lockstep guarantees the two GPUs are at most one AR (or chunk) apart, so |
| 230 | // slot[N%2] is always safe to reuse -- peer has already consumed slot[N%2] |
| 231 | // from AR N-2 by the time we get to AR N. acquire_slot's |
| 232 | // cudaEventSynchronize on ev.ker for both devices makes that consumption |
| 233 | // explicit before we overwrite host_buf[slot] for the new AR. |
| 234 | static constexpr int GGML_CUDA_AR_POOL_SIZE = 2; |
| 235 | |
| 236 | // Maximum chunk size (bytes per GPU) handled by one chunked kernel launch. |
| 237 | // Larger tensors are reduced by issuing multiple chunked launches. |
| 238 | static constexpr size_t GGML_CUDA_AR_MAX_BYTES = 1024 * 1024; // 1 MB |
| 239 | |
| 240 | // Copy-engine path: largest tensor accepted on this path; sets host_large / |
| 241 | // dev_tmp allocation size. |
| 242 | static constexpr size_t GGML_CUDA_AR_COPY_MAX_BYTES = 32 * 1024 * 1024; // 32 MB |
| 243 | |
| 244 | // AR wire size at which the copy-engine path takes over from the chunked- |
| 245 | // kernel path. Override via GGML_CUDA_AR_COPY_THRESHOLD. |
| 246 | static constexpr size_t GGML_CUDA_AR_COPY_THRESHOLD_DEFAULT = 1024 * 1024; // 1 MB |
| 247 | // Per-call CE chunk-size heuristic: chunk_bytes = clamp(nbytes / 4, MIN, MAX). |
| 248 | // The /4 keeps ~4 chunks in flight at any moment (good D2H/H2D overlap with |
| 249 | // the peer); the clamps cover the cases where nbytes/4 is too small (per- |
| 250 | // memcpy fixed cost dominates) or too large (chunk-level pipelining stalls). |
| 251 | // Env var GGML_CUDA_AR_COPY_CHUNK_BYTES can override with a fixed value. |
| 252 | static constexpr size_t GGML_CUDA_AR_COPY_CHUNK_BYTES_HEURISTIC_MIN = 512 * 1024; // 512 KB |
| 253 | static constexpr size_t GGML_CUDA_AR_COPY_CHUNK_BYTES_HEURISTIC_MAX = 2 * 1024 * 1024; // 2 MB |
| 254 | // Absolute floor that an env-var override is allowed to set; this caps the |
| 255 | // per-slot copy-event array. 256 KB -> up to 128 chunks per 32 MB tensor. |
| 256 | static constexpr size_t GGML_CUDA_AR_COPY_CHUNK_BYTES_MIN = 256 * 1024; |
| 257 | static constexpr int GGML_CUDA_AR_COPY_MAX_CHUNKS = |
| 258 | static_cast<int>((GGML_CUDA_AR_COPY_MAX_BYTES + GGML_CUDA_AR_COPY_CHUNK_BYTES_MIN - 1) / |
| 259 | GGML_CUDA_AR_COPY_CHUNK_BYTES_MIN); |
| 260 | |
| 261 | struct ggml_cuda_ar_event_slot { |
| 262 | cudaEvent_t app = nullptr; // upstream computation complete |
| 263 | cudaEvent_t cpy[GGML_CUDA_AR_COPY_MAX_CHUNKS] = {}; // copy-engine D2H chunks complete |
| 264 | cudaEvent_t h2d = nullptr; // copy-engine H2Ds complete (handoff AR stream -> compute stream) |
| 265 | cudaEvent_t ker = nullptr; // AllReduce kernel complete |
| 266 | }; |
| 267 | |
| 268 | // Mapped pinned host allocation: cudaHostAlloc + cudaHostGetDevicePointer |
| 269 | // in one place, with the host handle preserved for cudaFreeHost. Used where |
| 270 | // the CPU never touches the buffer -- only the device reads/writes via the |
| 271 | // mapped device pointer. Required on systems where cudaDevAttrCanUseHost- |
| 272 | // PointerForRegisteredMem is 0 and the host pointer can't be used as a |
| 273 | // device pointer. |
| 274 | struct ggml_cuda_ar_host_mapping { |
| 275 | uint8_t * host = nullptr; // cudaFreeHost handle; also the H-side ptr for cudaMemcpyAsync |
| 276 | uint8_t * dev = nullptr; // device-side pointer for kernels / cudaMemset |
| 277 | |
| 278 | cudaError_t alloc(size_t bytes) { |
| 279 | cudaError_t rc = cudaHostAlloc(reinterpret_cast<void **>(&host), bytes, |
| 280 | cudaHostAllocPortable | cudaHostAllocMapped); |
| 281 | if (rc != cudaSuccess) { |
| 282 | host = nullptr; |
| 283 | return rc; |
| 284 | } |
| 285 | rc = cudaHostGetDevicePointer(reinterpret_cast<void **>(&dev), host, 0); |
| 286 | if (rc != cudaSuccess) { |
| 287 | CUDA_CHECK(cudaFreeHost(host)); |
| 288 | host = nullptr; |
| 289 | dev = nullptr; |
| 290 | } |
| 291 | return rc; |
| 292 | } |
| 293 | |
| 294 | void free() { |
| 295 | if (host) { |
| 296 | CUDA_CHECK(cudaFreeHost(host)); |
| 297 | host = nullptr; |
| 298 | dev = nullptr; |
| 299 | } |
| 300 | } |
| 301 | }; |
| 302 | |
| 303 | struct ggml_cuda_ar_pipeline { |
| 304 | int n_devices; |
| 305 | int devices[GGML_CUDA_MAX_DEVICES]; |
| 306 | size_t buf_bytes; // bytes per device in host_buf[] |
| 307 | size_t copy_bytes; // bytes per device in host_large[] / dev_tmp[] |
| 308 | size_t copy_threshold; |
| 309 | size_t copy_chunk_bytes; |
| 310 | size_t bf16_threshold; // tensors >= this size (bytes) are reduced via FP32->BF16 round-trip; 0 disables |
| 311 | uint64_t call_count; |
| 312 | |
| 313 | // Per-device resources. |
| 314 | ggml_cuda_ar_host_mapping host_buf[GGML_CUDA_MAX_DEVICES]; // pinned staging (chunked kernel) |
| 315 | ggml_cuda_ar_host_mapping host_large[GGML_CUDA_MAX_DEVICES]; // pinned staging (copy-engine) |
| 316 | char * dev_tmp[GGML_CUDA_MAX_DEVICES]; // device scratch for copy-engine path |
| 317 | cudaStream_t streams[GGML_CUDA_MAX_DEVICES]; // non-blocking |
| 318 | ggml_cuda_ar_event_slot ev_pool[GGML_CUDA_MAX_DEVICES][GGML_CUDA_AR_POOL_SIZE]; |
| 319 | |
| 320 | // Copy-engine: per-device "I finished reading my peer's host_large" |
| 321 | // event. Indexed by RECORDER device. Recorded same-device on streams[i] |
| 322 | // after stage 2's last H2D from host_large[peer]. Waited cross-device |
| 323 | // by peer's stage-1 stream before the next AR overwrites host_large[peer]. |
| 324 | cudaEvent_t host_large_read_done[GGML_CUDA_MAX_DEVICES]; |
| 325 | bool host_large_read_done_valid; |
| 326 | |
| 327 | // Copy-engine: per-device "my add_kernel is done with dev_tmp" event. |
| 328 | // Recorded on the compute stream after each add_kernel; the AR stream |
| 329 | // waits on it before the next copy_impl's H2D overwrites dev_tmp. Lets us |
| 330 | // single-buffer dev_tmp despite add_kernel running on a separate stream. |
| 331 | cudaEvent_t dev_tmp_kernel_done[GGML_CUDA_MAX_DEVICES]; |
| 332 | bool dev_tmp_kernel_done_valid; |
| 333 | |
| 334 | // Arrival ring: ARRIVAL_STRIDE bytes between adjacent ints. Mapped pinned |
| 335 | // memory; CPU never reads/writes -- only the kernel and cudaMemset. |
| 336 | // Use ggml_cuda_ar_arrival_ptr() to index. |
| 337 | ggml_cuda_ar_host_mapping arrival; |
| 338 | }; |
| 339 | |
| 340 | // Base pointer for the (slot, rank) per-block token block. The kernel adds |
| 341 | // blockIdx.x * (ARRIVAL_STRIDE/sizeof(int)) internally to land on its own slot. |
| 342 | static int * ggml_cuda_ar_arrival_ptr(const ggml_cuda_ar_pipeline * p, int slot, int rank) { |
| 343 | const size_t offset = ((size_t)slot * p->n_devices + rank) * |
| 344 | GGML_CUDA_AR_KERNEL_BLOCKS * GGML_CUDA_AR_ARRIVAL_STRIDE; |
| 345 | return reinterpret_cast<int *>(p->arrival.dev + offset); |
| 346 | } |
| 347 | |
| 348 | static uint64_t ggml_cuda_ar_env_u64(const char * name, uint64_t default_value) { |
| 349 | const char * value = getenv(name); |
| 350 | if (value == nullptr || value[0] == '\0') { |
| 351 | return default_value; |
| 352 | } |
| 353 | |
| 354 | char * end = nullptr; |
| 355 | const unsigned long long parsed = strtoull(value, &end, 10); |
| 356 | return end != value ? (uint64_t) parsed : default_value; |
| 357 | } |
| 358 | |
| 359 | struct ggml_cuda_ar_slot_info { |
| 360 | int slot; |
| 361 | int token; |
| 362 | }; |
| 363 | |
| 364 | static ggml_cuda_ar_slot_info ggml_cuda_ar_acquire_slot(ggml_cuda_ar_pipeline * p) { |
| 365 | const int slot = static_cast<int>(p->call_count % GGML_CUDA_AR_POOL_SIZE); |
| 366 | const bool pool_lapped = p->call_count >= GGML_CUDA_AR_POOL_SIZE; |
| 367 | p->call_count++; |
| 368 | |
| 369 | if (pool_lapped) { |
| 370 | for (int i = 0; i < p->n_devices; ++i) { |
| 371 | ggml_cuda_set_device(p->devices[i]); |
| 372 | CUDA_CHECK(cudaEventSynchronize(p->ev_pool[i][slot].ker)); |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | return { slot, (int) p->call_count }; |
| 377 | } |
| 378 | |
| 379 | // Per-AR copy-engine chunk size: env-var override if set, else heuristic |
| 380 | // (clamp(nbytes/4, HEURISTIC_MIN, HEURISTIC_MAX)). |
| 381 | static size_t ggml_cuda_ar_chunk_bytes(const ggml_cuda_ar_pipeline * p, size_t nbytes) { |
| 382 | if (p->copy_chunk_bytes > 0) { |
| 383 | return p->copy_chunk_bytes; |
| 384 | } |
| 385 | return std::min(GGML_CUDA_AR_COPY_CHUNK_BYTES_HEURISTIC_MAX, |
| 386 | std::max(GGML_CUDA_AR_COPY_CHUNK_BYTES_HEURISTIC_MIN, nbytes / 4)); |
| 387 | } |
| 388 | |
| 389 | static void ggml_cuda_ar_wait_for_compute( |
| 390 | ggml_cuda_ar_pipeline * p, ggml_backend_cuda_context * cuda_ctx, int rank, int slot) { |
| 391 | ggml_cuda_ar_event_slot & ev = p->ev_pool[rank][slot]; |
| 392 | CUDA_CHECK(cudaEventRecord(ev.app, cuda_ctx->stream())); |
| 393 | CUDA_CHECK(cudaStreamWaitEvent(p->streams[rank], ev.app)); |
| 394 | } |
| 395 | |
| 396 | // --------------------------------------------------------------------------- |
| 397 | // Init / free |
| 398 | // --------------------------------------------------------------------------- |
| 399 | |
| 400 | ggml_cuda_ar_pipeline * ggml_cuda_ar_pipeline_init(const int * devices, size_t n_devices) { |
| 401 | |
| 402 | if (n_devices != 2) { |
| 403 | GGML_LOG_DEBUG("%s: internal AllReduce only supports n_devices=2 (got %zu); " |
| 404 | "falling back\n", __func__, n_devices); |
| 405 | return nullptr; |
| 406 | } |
| 407 | |
| 408 | // The chunked kernel uses __nanosleep (NVIDIA, sm70+) or |
| 409 | // __builtin_amdgcn_s_sleep (AMD). |
| 410 | for (size_t i = 0; i < n_devices; ++i) { |
| 411 | const int cc = ggml_cuda_info().devices[devices[i]].cc; |
| 412 | if (cc < GGML_CUDA_CC_VOLTA) { |
| 413 | GGML_LOG_DEBUG("%s: internal AllReduce requires compute capability >= %d " |
| 414 | "(device %d has cc=%d); falling back\n", |
| 415 | __func__, GGML_CUDA_CC_VOLTA, devices[i], cc); |
| 416 | return nullptr; |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | auto * p = new ggml_cuda_ar_pipeline{}; |
| 421 | p->n_devices = n_devices; |
| 422 | p->copy_bytes = GGML_CUDA_AR_COPY_MAX_BYTES; |
| 423 | p->copy_threshold = ggml_cuda_ar_env_u64("GGML_CUDA_AR_COPY_THRESHOLD", GGML_CUDA_AR_COPY_THRESHOLD_DEFAULT); |
| 424 | // 0 = use the per-call heuristic (default). Non-zero env value forces a |
| 425 | // fixed chunk size for diagnostics, with a floor at COPY_CHUNK_BYTES_MIN. |
| 426 | p->copy_chunk_bytes = ggml_cuda_ar_env_u64("GGML_CUDA_AR_COPY_CHUNK_BYTES", 0); |
| 427 | if (p->copy_chunk_bytes > 0 && p->copy_chunk_bytes < GGML_CUDA_AR_COPY_CHUNK_BYTES_MIN) { |
| 428 | GGML_LOG_WARN("%s: GGML_CUDA_AR_COPY_CHUNK_BYTES=%zu below minimum %zu; clamping\n", |
| 429 | __func__, p->copy_chunk_bytes, GGML_CUDA_AR_COPY_CHUNK_BYTES_MIN); |
| 430 | p->copy_chunk_bytes = GGML_CUDA_AR_COPY_CHUNK_BYTES_MIN; |
| 431 | } |
| 432 | // Default 1: BF16 round-trip is always on for F32 inputs (any non-zero |
| 433 | // ne). Set GGML_CUDA_AR_BF16_THRESHOLD=0 to disable, or to a larger |
| 434 | // byte threshold to opt out for small tensors. |
| 435 | p->bf16_threshold = ggml_cuda_ar_env_u64("GGML_CUDA_AR_BF16_THRESHOLD", 1); |
| 436 | for (size_t i = 0; i < n_devices; ++i) { |
| 437 | p->devices[i] = devices[i]; |
| 438 | } |
| 439 | |
| 440 | // Per-device streams and event pools. |
| 441 | for (size_t i = 0; i < n_devices; ++i) { |
| 442 | ggml_cuda_set_device(p->devices[i]); |
| 443 | |
| 444 | cudaStream_t stream = nullptr; |
| 445 | if (cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) != cudaSuccess) { |
| 446 | GGML_LOG_ERROR("%s: cudaStreamCreateWithFlags failed for device %d\n", |
| 447 | __func__, p->devices[i]); |
| 448 | ggml_cuda_ar_pipeline_free(p); |
| 449 | return nullptr; |
| 450 | } |
| 451 | p->streams[i] = stream; |
| 452 | |
| 453 | for (int s = 0; s < GGML_CUDA_AR_POOL_SIZE; ++s) { |
| 454 | bool ok = |
| 455 | cudaEventCreateWithFlags(&p->ev_pool[i][s].app, cudaEventDisableTiming) == cudaSuccess && |
| 456 | cudaEventCreateWithFlags(&p->ev_pool[i][s].h2d, cudaEventDisableTiming) == cudaSuccess && |
| 457 | cudaEventCreateWithFlags(&p->ev_pool[i][s].ker, cudaEventDisableTiming) == cudaSuccess; |
| 458 | for (int c = 0; ok && c < GGML_CUDA_AR_COPY_MAX_CHUNKS; ++c) { |
| 459 | ok = cudaEventCreateWithFlags(&p->ev_pool[i][s].cpy[c], cudaEventDisableTiming) == cudaSuccess; |
| 460 | } |
| 461 | if (!ok) { |
| 462 | GGML_LOG_ERROR("%s: cudaEventCreate failed for device %d slot %d\n", |
| 463 | __func__, p->devices[i], s); |
| 464 | ggml_cuda_ar_pipeline_free(p); |
| 465 | return nullptr; |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | if (cudaEventCreateWithFlags(&p->host_large_read_done[i], cudaEventDisableTiming) != cudaSuccess) { |
| 470 | GGML_LOG_ERROR("%s: cudaEventCreate for host_large_read_done failed for device %d\n", |
| 471 | __func__, p->devices[i]); |
| 472 | ggml_cuda_ar_pipeline_free(p); |
| 473 | return nullptr; |
| 474 | } |
| 475 | if (cudaEventCreateWithFlags(&p->dev_tmp_kernel_done[i], cudaEventDisableTiming) != cudaSuccess) { |
| 476 | GGML_LOG_ERROR("%s: cudaEventCreate for dev_tmp_kernel_done failed for device %d\n", |
| 477 | __func__, p->devices[i]); |
| 478 | ggml_cuda_ar_pipeline_free(p); |
| 479 | return nullptr; |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | // Arrival ring: cache-line padded so each GPU's int is on its own line. |
| 484 | const size_t arrival_bytes = |
| 485 | (size_t)GGML_CUDA_AR_POOL_SIZE * n_devices * |
| 486 | GGML_CUDA_AR_KERNEL_BLOCKS * GGML_CUDA_AR_ARRIVAL_STRIDE; |
| 487 | if (p->arrival.alloc(arrival_bytes) != cudaSuccess) { |
| 488 | GGML_LOG_ERROR("%s: alloc for arrival ring failed (%zu bytes)\n", |
| 489 | __func__, arrival_bytes); |
| 490 | ggml_cuda_ar_pipeline_free(p); |
| 491 | return nullptr; |
| 492 | } |
| 493 | ggml_cuda_set_device(p->devices[0]); |
| 494 | if (cudaMemset(p->arrival.dev, 0, arrival_bytes) != cudaSuccess) { |
| 495 | GGML_LOG_ERROR("%s: cudaMemset for arrival ring failed (%zu bytes)\n", |
| 496 | __func__, arrival_bytes); |
| 497 | ggml_cuda_ar_pipeline_free(p); |
| 498 | return nullptr; |
| 499 | } |
| 500 | |
| 501 | // Per-device pinned staging buffers -- POOL_SIZE-deep ring so the chunked- |
| 502 | // kernel can write the next slot's data while the peer is still reading |
| 503 | // the previous slot's. Indexed by (slot * buf_bytes) at the call site. |
| 504 | p->buf_bytes = GGML_CUDA_AR_MAX_BYTES; |
| 505 | const size_t host_buf_total = (size_t) GGML_CUDA_AR_POOL_SIZE * p->buf_bytes; |
| 506 | for (size_t i = 0; i < n_devices; ++i) { |
| 507 | if (p->host_buf[i].alloc(host_buf_total) != cudaSuccess) { |
| 508 | GGML_LOG_ERROR("%s: alloc for staging failed (%zu bytes)\n", |
| 509 | __func__, host_buf_total); |
| 510 | ggml_cuda_ar_pipeline_free(p); |
| 511 | return nullptr; |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | // Copy-engine path: pinned host staging + device scratch, sized for the |
| 516 | // largest tensor we accept on this path (GGML_CUDA_AR_COPY_MAX_BYTES). |
| 517 | // dev_tmp is single-buffered; cross-AR safety is enforced by an explicit |
| 518 | // cross-stream wait in copy_impl on the prior AR's add_kernel-done event. |
| 519 | for (size_t i = 0; i < n_devices; ++i) { |
| 520 | ggml_cuda_set_device(p->devices[i]); |
| 521 | if (p->host_large[i].alloc(p->copy_bytes) != cudaSuccess) { |
| 522 | GGML_LOG_ERROR("%s: alloc for large staging failed (%zu bytes)\n", |
| 523 | __func__, p->copy_bytes); |
| 524 | ggml_cuda_ar_pipeline_free(p); |
| 525 | return nullptr; |
| 526 | } |
| 527 | if (cudaMalloc(reinterpret_cast<void **>(&p->dev_tmp[i]), p->copy_bytes) != cudaSuccess) { |
| 528 | GGML_LOG_ERROR("%s: cudaMalloc for copy scratch failed (%zu bytes) on device %d\n", |
| 529 | __func__, p->copy_bytes, p->devices[i]); |
| 530 | ggml_cuda_ar_pipeline_free(p); |
| 531 | return nullptr; |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | GGML_LOG_INFO("%s: initialized AllReduce pipeline: %zu GPUs, " |
| 536 | "%zu KB chunked kernel staging + %zu MB copy-engine staging per GPU\n", |
| 537 | __func__, n_devices, p->buf_bytes >> 10, p->copy_bytes >> 20); |
| 538 | |
| 539 | return p; |
| 540 | } |
| 541 | |
| 542 | void ggml_cuda_ar_pipeline_free(ggml_cuda_ar_pipeline * p) { |
| 543 | if (!p) { |
| 544 | return; |
| 545 | } |
| 546 | |
| 547 | // Drain all in-flight kernels before tearing down resources. |
| 548 | for (int i = 0; i < p->n_devices; ++i) { |
| 549 | if (p->streams[i]) { |
| 550 | ggml_cuda_set_device(p->devices[i]); |
| 551 | CUDA_CHECK(cudaStreamSynchronize(p->streams[i])); |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | for (int i = 0; i < p->n_devices; ++i) { |
| 556 | p->host_buf[i].free(); |
| 557 | p->host_large[i].free(); |
| 558 | if (p->dev_tmp[i]) { |
| 559 | ggml_cuda_set_device(p->devices[i]); |
| 560 | CUDA_CHECK(cudaFree(p->dev_tmp[i])); |
| 561 | } |
| 562 | ggml_cuda_set_device(p->devices[i]); |
| 563 | for (int s = 0; s < GGML_CUDA_AR_POOL_SIZE; ++s) { |
| 564 | if (p->ev_pool[i][s].app) { CUDA_CHECK(cudaEventDestroy(p->ev_pool[i][s].app)); } |
| 565 | for (int c = 0; c < GGML_CUDA_AR_COPY_MAX_CHUNKS; ++c) { |
| 566 | if (p->ev_pool[i][s].cpy[c]) { CUDA_CHECK(cudaEventDestroy(p->ev_pool[i][s].cpy[c])); } |
| 567 | } |
| 568 | if (p->ev_pool[i][s].h2d) { CUDA_CHECK(cudaEventDestroy(p->ev_pool[i][s].h2d)); } |
| 569 | if (p->ev_pool[i][s].ker) { CUDA_CHECK(cudaEventDestroy(p->ev_pool[i][s].ker)); } |
| 570 | } |
| 571 | if (p->host_large_read_done[i]) { |
| 572 | ggml_cuda_set_device(p->devices[i]); |
| 573 | CUDA_CHECK(cudaEventDestroy(p->host_large_read_done[i])); |
| 574 | } |
| 575 | if (p->dev_tmp_kernel_done[i]) { |
| 576 | ggml_cuda_set_device(p->devices[i]); |
| 577 | CUDA_CHECK(cudaEventDestroy(p->dev_tmp_kernel_done[i])); |
| 578 | } |
| 579 | if (p->streams[i]) { |
| 580 | ggml_cuda_set_device(p->devices[i]); |
| 581 | CUDA_CHECK(cudaStreamDestroy(p->streams[i])); |
| 582 | } |
| 583 | } |
| 584 | p->arrival.free(); |
| 585 | delete p; |
| 586 | } |
| 587 | |
| 588 | // --------------------------------------------------------------------------- |
| 589 | // Dispatch |
| 590 | // --------------------------------------------------------------------------- |
| 591 | |
| 592 | // Asymmetric copy_impl: data sent over PCIe in T_src precision (one element of |
| 593 | // nbytes per ne element); accumulated locally into a T_dst buffer. When |
| 594 | // T_src == T_dst this is the original homogeneous reduction. When they differ |
| 595 | // (e.g. BF16 wire / F32 accumulator) the add kernel rounds dst through T_src |
| 596 | // for bit-equivalence between GPUs and we skip the otherwise-needed |
| 597 | // post-conversion entirely. |
| 598 | template <typename T_src, typename T_dst> |
| 599 | static bool ggml_cuda_ar_allreduce_copy_impl( |
| 600 | ggml_cuda_ar_pipeline * p, |
| 601 | ggml_backend_t * backends, |
| 602 | T_src * const src_buf[GGML_CUDA_MAX_DEVICES], |
| 603 | T_dst * const dst_buf[GGML_CUDA_MAX_DEVICES], |
| 604 | const bool compute[GGML_CUDA_MAX_DEVICES], |
| 605 | int64_t ne, |
| 606 | size_t nbytes) { |
| 607 | GGML_ASSERT(p->n_devices == 2); |
| 608 | GGML_ASSERT(nbytes <= p->copy_bytes); |
| 609 | GGML_ASSERT(ne <= std::numeric_limits<int>::max()); |
| 610 | |
| 611 | const size_t chunk_bytes = ggml_cuda_ar_chunk_bytes(p, nbytes); |
| 612 | GGML_ASSERT(chunk_bytes > 0); |
| 613 | |
| 614 | const int slot = ggml_cuda_ar_acquire_slot(p).slot; |
| 615 | const size_t copy_chunks = (nbytes + chunk_bytes - 1) / chunk_bytes; |
| 616 | GGML_ASSERT(copy_chunks <= GGML_CUDA_AR_COPY_MAX_CHUNKS); |
| 617 | |
| 618 | ggml_backend_cuda_context * cuda_ctx[2] = {}; |
| 619 | |
| 620 | // Stage 1: both GPUs copy their local contribution to pinned host memory. |
| 621 | for (int i = 0; i < 2; ++i) { |
| 622 | ggml_cuda_set_device(p->devices[i]); |
| 623 | cuda_ctx[i] = static_cast<ggml_backend_cuda_context *>(backends[i]->context); |
| 624 | GGML_ASSERT(cuda_ctx[i]->device == p->devices[i]); |
| 625 | |
| 626 | ggml_cuda_ar_wait_for_compute(p, cuda_ctx[i], i, slot); |
| 627 | |
| 628 | // Wait for peer's H2D from our host_large[i] (recorded in the |
| 629 | // previous AR's stage 2) to complete before we overwrite host_large[i]. |
| 630 | // host_large_read_done[peer] = peer finished reading host_large[i]. |
| 631 | // No-op on the first AR -- no prior record exists. |
| 632 | if (p->host_large_read_done_valid) { |
| 633 | const int peer = 1 - i; |
| 634 | CUDA_CHECK(cudaStreamWaitEvent(p->streams[i], p->host_large_read_done[peer])); |
| 635 | } |
| 636 | |
| 637 | if (!compute[i]) { |
| 638 | CUDA_CHECK(cudaMemsetAsync(src_buf[i], 0, nbytes, p->streams[i])); |
| 639 | } |
| 640 | |
| 641 | for (size_t c = 0; c < copy_chunks; ++c) { |
| 642 | const size_t offset = c * chunk_bytes; |
| 643 | const size_t this_bytes = (nbytes - offset) < chunk_bytes ? |
| 644 | (nbytes - offset) : chunk_bytes; |
| 645 | |
| 646 | CUDA_CHECK(cudaMemcpyAsync( |
| 647 | p->host_large[i].host + offset, reinterpret_cast<char *>(src_buf[i]) + offset, this_bytes, |
| 648 | cudaMemcpyDeviceToHost, p->streams[i])); |
| 649 | CUDA_CHECK(cudaEventRecord(p->ev_pool[i][slot].cpy[c], p->streams[i])); |
| 650 | } |
| 651 | } |
| 652 | |
| 653 | // Stage 2: each GPU waits for each peer D2H chunk, pulls that chunk back to |
| 654 | // local device scratch (dev_tmp), then performs one device-local add over |
| 655 | // the assembled peer tensor. The H2Ds run on the AR stream (copy engine) |
| 656 | // and the add_kernel runs on the caller's compute stream, so the AR stream |
| 657 | // stays pure-copy and avoids an in-stream copy->compute engine switch every |
| 658 | // AR. dev_tmp is single-buffered: the AR stream waits cross-stream on the |
| 659 | // prior AR's add_kernel-done event before overwriting it. |
| 660 | for (int i = 0; i < 2; ++i) { |
| 661 | const int peer = 1 - i; |
| 662 | ggml_cuda_set_device(p->devices[i]); |
| 663 | |
| 664 | // Wait for the previous AR's add_kernel (on the compute stream) to |
| 665 | // finish reading dev_tmp before our H2D overwrites it. No-op on the |
| 666 | // first copy_impl call. |
| 667 | if (p->dev_tmp_kernel_done_valid) { |
| 668 | CUDA_CHECK(cudaStreamWaitEvent(p->streams[i], p->dev_tmp_kernel_done[i])); |
| 669 | } |
| 670 | |
| 671 | for (size_t c = 0; c < copy_chunks; ++c) { |
| 672 | const size_t offset = c * chunk_bytes; |
| 673 | const size_t this_bytes = (nbytes - offset) < chunk_bytes ? |
| 674 | (nbytes - offset) : chunk_bytes; |
| 675 | |
| 676 | CUDA_CHECK(cudaStreamWaitEvent(p->streams[i], p->ev_pool[peer][slot].cpy[c])); |
| 677 | CUDA_CHECK(cudaMemcpyAsync( |
| 678 | p->dev_tmp[i] + offset, p->host_large[peer].host + offset, this_bytes, |
| 679 | cudaMemcpyHostToDevice, p->streams[i])); |
| 680 | } |
| 681 | |
| 682 | // Mark our reads of host_large[peer] complete so peer's next AR can |
| 683 | // safely overwrite it. |
| 684 | CUDA_CHECK(cudaEventRecord(p->host_large_read_done[i], p->streams[i])); |
| 685 | |
| 686 | // Hand off from AR stream (copy engine) to compute stream: compute |
| 687 | // stream waits for all H2Ds to finish, then runs the add_kernel. |
| 688 | CUDA_CHECK(cudaEventRecord(p->ev_pool[i][slot].h2d, p->streams[i])); |
| 689 | CUDA_CHECK(cudaStreamWaitEvent(cuda_ctx[i]->stream(), p->ev_pool[i][slot].h2d)); |
| 690 | |
| 691 | const int block_size = 256; |
| 692 | int n_blocks = (int) ((ne + block_size - 1) / block_size); |
| 693 | if (n_blocks > 1024) { |
| 694 | n_blocks = 1024; |
| 695 | } |
| 696 | ggml_cuda_ar_add_kernel<T_dst, T_src><<<n_blocks, block_size, 0, cuda_ctx[i]->stream()>>>( |
| 697 | dst_buf[i], |
| 698 | reinterpret_cast<const T_src *>(p->dev_tmp[i]), |
| 699 | (int) ne); |
| 700 | CUDA_CHECK(cudaGetLastError()); |
| 701 | |
| 702 | // Record dev_tmp-released on the compute stream so the next copy_impl |
| 703 | // can wait for the kernel to finish before overwriting dev_tmp. Also |
| 704 | // record AR-done as ev.ker for acquire_slot's pool-wraparound sync. |
| 705 | CUDA_CHECK(cudaEventRecord(p->dev_tmp_kernel_done[i], cuda_ctx[i]->stream())); |
| 706 | CUDA_CHECK(cudaEventRecord(p->ev_pool[i][slot].ker, cuda_ctx[i]->stream())); |
| 707 | } |
| 708 | p->host_large_read_done_valid = true; |
| 709 | p->dev_tmp_kernel_done_valid = true; |
| 710 | |
| 711 | return true; |
| 712 | } |
| 713 | |
| 714 | // Outer-level chunker: copy_impl handles up to copy_bytes per call (limited by |
| 715 | // the host_large / dev_tmp allocation size). When the full AR exceeds that, |
| 716 | // slice the tensor into copy_bytes-sized pieces and call copy_impl repeatedly. |
| 717 | // Each slice goes through its own stage 1 -> stage 2 cycle and acquires its own |
| 718 | // slot, so cross-AR fences and pool wraparound work the same way as for any |
| 719 | // other sequence of small ARs. |
| 720 | template <typename T_src, typename T_dst> |
| 721 | static bool ggml_cuda_ar_allreduce_copy_outer( |
| 722 | ggml_cuda_ar_pipeline * p, |
| 723 | ggml_backend_t * backends, |
| 724 | T_src * const src_buf[GGML_CUDA_MAX_DEVICES], |
| 725 | T_dst * const dst_buf[GGML_CUDA_MAX_DEVICES], |
| 726 | const bool compute[GGML_CUDA_MAX_DEVICES], |
| 727 | int64_t ne) { |
| 728 | const int64_t outer_max_elems = (int64_t) (p->copy_bytes / sizeof(T_src)); |
| 729 | GGML_ASSERT(outer_max_elems > 0); |
| 730 | |
| 731 | bool ok = true; |
| 732 | for (int64_t outer_start = 0; outer_start < ne && ok; outer_start += outer_max_elems) { |
| 733 | const int64_t outer_ne = std::min(outer_max_elems, ne - outer_start); |
| 734 | const size_t outer_nbytes = (size_t) outer_ne * sizeof(T_src); |
| 735 | |
| 736 | T_src * src[GGML_CUDA_MAX_DEVICES] = {}; |
| 737 | T_dst * dst[GGML_CUDA_MAX_DEVICES] = {}; |
| 738 | for (int i = 0; i < p->n_devices; ++i) { |
| 739 | src[i] = src_buf[i] + outer_start; |
| 740 | dst[i] = dst_buf[i] + outer_start; |
| 741 | } |
| 742 | ok = ggml_cuda_ar_allreduce_copy_impl<T_src, T_dst>( |
| 743 | p, backends, src, dst, compute, outer_ne, outer_nbytes); |
| 744 | } |
| 745 | return ok; |
| 746 | } |
| 747 | |
| 748 | bool ggml_cuda_ar_allreduce( |
| 749 | ggml_cuda_ar_pipeline * p, |
| 750 | ggml_backend_t * backends, |
| 751 | ggml_tensor ** tensors) { |
| 752 | GGML_ASSERT(p != nullptr); |
| 753 | |
| 754 | const int n = p->n_devices; |
| 755 | GGML_ASSERT(n == 2); |
| 756 | |
| 757 | const ggml_type input_type = tensors[0]->type; |
| 758 | GGML_ASSERT(input_type == GGML_TYPE_F32 || input_type == GGML_TYPE_F16 || input_type == GGML_TYPE_BF16); |
| 759 | |
| 760 | const int64_t ne = ggml_nelements(tensors[0]); |
| 761 | GGML_ASSERT(ne > 0); |
| 762 | |
| 763 | const size_t input_nbytes = ggml_nbytes(tensors[0]); |
| 764 | |
| 765 | // BF16 round-trip: F32 inputs >= bf16_threshold are converted to BF16 for |
| 766 | // the reduction (chunked or copy-engine), halving on-wire bytes. Matches |
| 767 | // NCCL's behaviour. The pre-conversion zeroes inactive shards so the |
| 768 | // inner paths see them as already-prepared compute tensors. |
| 769 | const bool use_bf16 = |
| 770 | input_type == GGML_TYPE_F32 && |
| 771 | p->bf16_threshold > 0 && |
| 772 | input_nbytes >= p->bf16_threshold; |
| 773 | |
| 774 | const ggml_type kernel_type = use_bf16 ? GGML_TYPE_BF16 : input_type; |
| 775 | const size_t type_size = ggml_type_size(kernel_type); |
| 776 | GGML_ASSERT(p->buf_bytes >= type_size); |
| 777 | const size_t nbytes = (size_t) ne * type_size; |
| 778 | |
| 779 | bool compute_flag[GGML_CUDA_MAX_DEVICES] = {}; |
| 780 | for (int i = 0; i < n; ++i) { |
| 781 | compute_flag[i] = (tensors[i]->flags & GGML_TENSOR_FLAG_COMPUTE) != 0; |
| 782 | } |
| 783 | |
| 784 | // Decide between copy-engine and chunked kernel paths based on the working |
| 785 | // type's actual byte count. No upper bound: copy_outer slices reductions |
| 786 | // larger than copy_bytes into copy_bytes-sized pieces. |
| 787 | const bool use_copy_engine = |
| 788 | p->copy_threshold > 0 && |
| 789 | nbytes >= p->copy_threshold; |
| 790 | |
| 791 | // BF16 inactive-shard zeroing: when use_bf16 is on, the combined kernel |
| 792 | // (chunked kernel path) and the combined add kernel (copy_engine path) |
| 793 | // both accumulate into the F32 tensor data directly, so an inactive |
| 794 | // shard's accumulator must start at zero. |
| 795 | if (use_bf16) { |
| 796 | for (int i = 0; i < n; ++i) { |
| 797 | if (!compute_flag[i]) { |
| 798 | auto * cuda_ctx = static_cast<ggml_backend_cuda_context *>(backends[i]->context); |
| 799 | GGML_ASSERT(cuda_ctx->device == p->devices[i]); |
| 800 | ggml_cuda_set_device(p->devices[i]); |
| 801 | CUDA_CHECK(cudaMemsetAsync(tensors[i]->data, 0, (size_t) ne * sizeof(float), cuda_ctx->stream())); |
| 802 | } |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | // Pre-convert F32 -> BF16 into bf16_tmp ONLY for the copy_engine + use_bf16 |
| 807 | // path; the chunked kernel path's combined kernel does the conversion |
| 808 | // inline as it writes to host_buf. |
| 809 | ggml_cuda_pool_alloc<nv_bfloat16> bf16_tmp[GGML_CUDA_MAX_DEVICES]; |
| 810 | void * copy_src_ptr[GGML_CUDA_MAX_DEVICES] = {}; |
| 811 | |
| 812 | if (use_copy_engine && use_bf16) { |
| 813 | to_bf16_cuda_t to_bf16 = ggml_get_to_bf16_cuda(GGML_TYPE_F32); |
| 814 | for (int i = 0; i < n; ++i) { |
| 815 | auto * cuda_ctx = static_cast<ggml_backend_cuda_context *>(backends[i]->context); |
| 816 | GGML_ASSERT(cuda_ctx->device == p->devices[i]); |
| 817 | bf16_tmp[i].pool = &cuda_ctx->pool(); |
| 818 | bf16_tmp[i].alloc(ne); |
| 819 | ggml_cuda_set_device(p->devices[i]); |
| 820 | if (compute_flag[i]) { |
| 821 | to_bf16(tensors[i]->data, bf16_tmp[i].get(), ne, cuda_ctx->stream()); |
| 822 | CUDA_CHECK(cudaGetLastError()); |
| 823 | } else { |
| 824 | CUDA_CHECK(cudaMemsetAsync(bf16_tmp[i].get(), 0, nbytes, cuda_ctx->stream())); |
| 825 | } |
| 826 | copy_src_ptr[i] = bf16_tmp[i].get(); |
| 827 | } |
| 828 | } |
| 829 | |
| 830 | bool ok = true; |
| 831 | if (use_copy_engine) { |
| 832 | // After up-front BF16 conversion, the tmp buffers already hold the |
| 833 | // (possibly zeroed-for-inactive) data, so the inner path can treat |
| 834 | // every shard as compute. |
| 835 | bool inner_compute[GGML_CUDA_MAX_DEVICES]; |
| 836 | for (int i = 0; i < n; ++i) { |
| 837 | inner_compute[i] = use_bf16 ? true : compute_flag[i]; |
| 838 | } |
| 839 | |
| 840 | // Dispatch into copy_impl with explicit src/dst types. When use_bf16 |
| 841 | // is on, the wire type is BF16 (src = bf16_tmp) and the accumulator |
| 842 | // is F32 (dst = tensors[i]->data); the combined add kernel rounds dst |
| 843 | // through BF16 for bit-equivalence and writes F32 directly, so no |
| 844 | // post-conversion is needed. Otherwise src == dst (same native type). |
| 845 | if (use_bf16) { |
| 846 | GGML_ASSERT(kernel_type == GGML_TYPE_BF16); |
| 847 | nv_bfloat16 * src[GGML_CUDA_MAX_DEVICES] = {}; |
| 848 | float * dst[GGML_CUDA_MAX_DEVICES] = {}; |
| 849 | for (int i = 0; i < n; ++i) { |
| 850 | src[i] = static_cast<nv_bfloat16 *>(copy_src_ptr[i]); |
| 851 | dst[i] = static_cast<float *>(tensors[i]->data); |
| 852 | } |
| 853 | ok = ggml_cuda_ar_allreduce_copy_outer<nv_bfloat16, float>( |
| 854 | p, backends, src, dst, inner_compute, ne); |
| 855 | } else { |
| 856 | switch (kernel_type) { |
| 857 | case GGML_TYPE_F32: { |
| 858 | float * buf[GGML_CUDA_MAX_DEVICES] = {}; |
| 859 | for (int i = 0; i < n; ++i) { |
| 860 | buf[i] = static_cast<float *>(tensors[i]->data); |
| 861 | } |
| 862 | ok = ggml_cuda_ar_allreduce_copy_outer<float, float>( |
| 863 | p, backends, buf, buf, inner_compute, ne); |
| 864 | break; |
| 865 | } |
| 866 | case GGML_TYPE_BF16: { |
| 867 | nv_bfloat16 * buf[GGML_CUDA_MAX_DEVICES] = {}; |
| 868 | for (int i = 0; i < n; ++i) { |
| 869 | buf[i] = static_cast<nv_bfloat16 *>(tensors[i]->data); |
| 870 | } |
| 871 | ok = ggml_cuda_ar_allreduce_copy_outer<nv_bfloat16, nv_bfloat16>( |
| 872 | p, backends, buf, buf, inner_compute, ne); |
| 873 | break; |
| 874 | } |
| 875 | case GGML_TYPE_F16: { |
| 876 | half * buf[GGML_CUDA_MAX_DEVICES] = {}; |
| 877 | for (int i = 0; i < n; ++i) { |
| 878 | buf[i] = static_cast<half *>(tensors[i]->data); |
| 879 | } |
| 880 | ok = ggml_cuda_ar_allreduce_copy_outer<half, half>( |
| 881 | p, backends, buf, buf, inner_compute, ne); |
| 882 | break; |
| 883 | } |
| 884 | default: |
| 885 | GGML_ASSERT(false); |
| 886 | } |
| 887 | } |
| 888 | } else { |
| 889 | // host_buf carries T_wire-typed data; max_chunk_elems is the count that |
| 890 | // fits in one host_buf at the wire size. |
| 891 | const size_t max_chunk_elems = p->buf_bytes / type_size; |
| 892 | const size_t input_type_size = ggml_type_size(input_type); |
| 893 | |
| 894 | // Chunked kernel path runs entirely on the caller's compute stream: |
| 895 | // since AR is a barrier here, same-stream ordering subsumes any |
| 896 | // cross-stream event handshake that the copy-engine path needs, and |
| 897 | // skips the cross-stream scheduling overhead that was hurting the |
| 898 | // small-tensor (tg) latency on the AR-stream variant. Only ev.ker is |
| 899 | // still recorded at end-of-AR for acquire_slot's pool-wraparound check. |
| 900 | for (int64_t chunk_start = 0; chunk_start < ne; chunk_start += (int64_t) max_chunk_elems) { |
| 901 | const size_t remaining_elems = (size_t) (ne - chunk_start); |
| 902 | const size_t chunk_elems = remaining_elems < max_chunk_elems ? remaining_elems : max_chunk_elems; |
| 903 | const size_t chunk_dst_bytes = chunk_elems * input_type_size; |
| 904 | |
| 905 | const auto [slot, token] = ggml_cuda_ar_acquire_slot(p); |
| 906 | const bool last_chunk = chunk_start + (int64_t) chunk_elems == ne; |
| 907 | |
| 908 | for (int i = 0; i < n; ++i) { |
| 909 | const int peer = 1 - i; // valid for n == 2 only |
| 910 | ggml_cuda_set_device(p->devices[i]); |
| 911 | auto * cuda_ctx = static_cast<ggml_backend_cuda_context *>(backends[i]->context); |
| 912 | GGML_ASSERT(cuda_ctx->device == p->devices[i]); |
| 913 | cudaStream_t stream = cuda_ctx->stream(); |
| 914 | |
| 915 | char * data = static_cast<char *>(tensors[i]->data) + chunk_start * (int64_t) input_type_size; |
| 916 | |
| 917 | // Match NCCL/meta-backend semantics: inactive shards contribute |
| 918 | // zeros. On the BF16 path the F32 tensor data was already |
| 919 | // zeroed up-front (above), so per-chunk zeroing isn't needed. |
| 920 | if (!compute_flag[i] && !use_bf16) { |
| 921 | CUDA_CHECK(cudaMemsetAsync(data, 0, chunk_dst_bytes, stream)); |
| 922 | } |
| 923 | |
| 924 | #define LAUNCH_AR_KERNEL(T_dst, T_wire) \ |
| 925 | ggml_cuda_ar_kernel<T_dst, T_wire><<<dim3(GGML_CUDA_AR_KERNEL_BLOCKS), dim3(256), 0, stream>>>( \ |
| 926 | reinterpret_cast<const T_dst *>(data), \ |
| 927 | reinterpret_cast<T_dst *>(data), \ |
| 928 | reinterpret_cast<T_wire *>(p->host_buf[i].dev + (size_t) slot * p->buf_bytes), \ |
| 929 | reinterpret_cast<const T_wire *>(p->host_buf[peer].dev + (size_t) slot * p->buf_bytes), \ |
| 930 | static_cast<int>(chunk_elems), \ |
| 931 | ggml_cuda_ar_arrival_ptr(p, slot, i), \ |
| 932 | ggml_cuda_ar_arrival_ptr(p, slot, peer), \ |
| 933 | token) |
| 934 | |
| 935 | if (use_bf16) { |
| 936 | GGML_ASSERT(input_type == GGML_TYPE_F32); |
| 937 | LAUNCH_AR_KERNEL(float, nv_bfloat16); |
| 938 | } else { |
| 939 | switch (input_type) { |
| 940 | case GGML_TYPE_F32: LAUNCH_AR_KERNEL(float, float); break; |
| 941 | case GGML_TYPE_F16: LAUNCH_AR_KERNEL(half, half); break; |
| 942 | case GGML_TYPE_BF16: LAUNCH_AR_KERNEL(nv_bfloat16, nv_bfloat16); break; |
| 943 | default: GGML_ASSERT(false); |
| 944 | } |
| 945 | } |
| 946 | |
| 947 | #undef LAUNCH_AR_KERNEL |
| 948 | CUDA_CHECK(cudaGetLastError()); |
| 949 | |
| 950 | if (last_chunk) { |
| 951 | CUDA_CHECK(cudaEventRecord(p->ev_pool[i][slot].ker, stream)); |
| 952 | } |
| 953 | } |
| 954 | } |
| 955 | } |
| 956 | |
| 957 | return ok; |
| 958 | } |
| 959 | |
| 960 | #else // defined(GGML_USE_MUSA) |
| 961 | |
| 962 | // MUSA lacks the host-mapped pinned-memory APIs (cudaHostAllocPortable |
| 963 | // / cudaHostAllocMapped / cudaHostGetDevicePointer) and a device-side |
| 964 | // sleep intrinsic that this implementation relies on, so the internal |
| 965 | // AllReduce is unavailable there. The dispatcher in ggml-cuda.cu treats |
| 966 | // a nullptr pipeline as "init failed" and silently falls back to the meta |
| 967 | // backend's generic AllReduce. |
| 968 | ggml_cuda_ar_pipeline * ggml_cuda_ar_pipeline_init(const int *, size_t) { |
| 969 | return nullptr; |
| 970 | } |
| 971 | void ggml_cuda_ar_pipeline_free(ggml_cuda_ar_pipeline *) { |
| 972 | } |
| 973 | bool ggml_cuda_ar_allreduce(ggml_cuda_ar_pipeline *, ggml_backend_t *, ggml_tensor **) { |
| 974 | return false; |
| 975 | } |
| 976 | |
| 977 | #endif // !defined(GGML_USE_MUSA) |