main
cuh 332 lines 10.8 KB
Raw
1 #pragma once
2
3 #include <cuda.h>
4 #include <cuda_bf16.h>
5 #include <cuda_fp16.h>
6 #include <cuda_runtime.h>
7
8 #if defined(USE_ROCM)
9 typedef __hip_bfloat16 nv_bfloat16;
10 #endif
11
12 #include <iostream>
13 #include <array>
14 #include <limits>
15 #include <map>
16 #include <unordered_map>
17 #include <vector>
18 #include <cstdlib>
19 #include <cstring>
20
21 namespace vllm {
22 constexpr int kMaxCustomCollectiveRanks = 16;
23
24 #define CUDACHECK(cmd) \
25 do { \
26 cudaError_t e = cmd; \
27 if (e != cudaSuccess) { \
28 printf("Failed: Cuda error %s:%d '%s'\n", __FILE__, __LINE__, \
29 cudaGetErrorString(e)); \
30 exit(EXIT_FAILURE); \
31 } \
32 } while (0)
33
34 // Maximal number of blocks in allreduce kernel.
35 constexpr int kMaxBlocks = 36;
36
37 // Default number of blocks in allreduce kernel.
38 #ifndef USE_ROCM
39 inline constexpr int defaultBlockLimit = 36;
40 inline CUpointer_attribute rangeStartAddrAttr =
41 CU_POINTER_ATTRIBUTE_RANGE_START_ADDR;
42 #else
43 inline constexpr int defaultBlockLimit = 16;
44 inline hipPointer_attribute rangeStartAddrAttr =
45 HIP_POINTER_ATTRIBUTE_RANGE_START_ADDR;
46 #endif
47
48 // Counter may overflow, but it's fine since unsigned int overflow is
49 // well-defined behavior.
50 using FlagType = uint32_t;
51
52 // Two sets of peer counters are needed for two syncs: starting and ending an
53 // operation. The reason is that it's possible for peer GPU block to arrive at
54 // the second sync point while the current GPU block haven't passed the first
55 // sync point. Thus, peer GPU may write counter+1 while current GPU is busy
56 // waiting for counter. We use alternating counter array to avoid this
57 // possibility.
58 struct Signal {
59 alignas(128) FlagType start[kMaxBlocks][kMaxCustomCollectiveRanks];
60 alignas(128) FlagType end[kMaxBlocks][kMaxCustomCollectiveRanks];
61 alignas(128) FlagType _flag[kMaxBlocks]; // incremental flags for each rank
62 };
63
64 struct __align__(16) RankData {
65 const void* ptrs[kMaxCustomCollectiveRanks];
66 };
67
68 struct __align__(16) RankSignals {
69 Signal* signals[kMaxCustomCollectiveRanks];
70 };
71
72 // like std::array, but aligned
73 template <typename T, int sz>
74 struct __align__(alignof(T) * sz) array_t {
75 T data[sz];
76 using type = T;
77 static constexpr int size = sz;
78 };
79
80 // use packed type to maximize memory efficiency
81 // goal: generate ld.128 and st.128 instructions
82 template <typename T>
83 struct packed_t {
84 // the (P)acked type for load/store
85 using P = array_t<T, 16 / sizeof(T)>;
86 // the (A)ccumulator type for reduction
87 using A = array_t<float, 16 / sizeof(T)>;
88 };
89
90 #define DINLINE __device__ __forceinline__
91
92 // scalar cast functions
93 DINLINE float upcast_s(half val) { return __half2float(val); }
94
95 template <typename T>
96 DINLINE T downcast_s(float val);
97 template <>
98 DINLINE half downcast_s(float val) {
99 return __float2half(val);
100 }
101
102 // scalar add functions
103 // for some reason when compiling with Pytorch, the + operator for half and
104 // bfloat is disabled so we call the intrinsics directly
105 DINLINE half& assign_add(half& a, half b) {
106 a = __hadd(a, b);
107 return a;
108 }
109 DINLINE float& assign_add(float& a, float b) { return a += b; }
110
111 #if (__CUDA_ARCH__ >= 800 || !defined(__CUDA_ARCH__))
112 DINLINE float upcast_s(nv_bfloat16 val) { return __bfloat162float(val); }
113 template <>
114 DINLINE nv_bfloat16 downcast_s(float val) {
115 return __float2bfloat16(val);
116 }
117 DINLINE nv_bfloat16& assign_add(nv_bfloat16& a, nv_bfloat16 b) {
118 a = __hadd(a, b);
119 return a;
120 }
121 #endif
122
123 template <typename T, int N>
124 DINLINE array_t<T, N>& packed_assign_add(array_t<T, N>& a, array_t<T, N> b) {
125 #pragma unroll
126 for (int i = 0; i < N; i++) {
127 assign_add(a.data[i], b.data[i]);
128 }
129 return a;
130 }
131
132 template <typename T, int N>
133 DINLINE array_t<float, N> upcast(array_t<T, N> val) {
134 if constexpr (std::is_same<T, float>::value) {
135 return val;
136 } else {
137 array_t<float, N> out;
138 #pragma unroll
139 for (int i = 0; i < N; i++) {
140 out.data[i] = upcast_s(val.data[i]);
141 }
142 return out;
143 }
144 }
145
146 template <typename O>
147 DINLINE O downcast(array_t<float, O::size> val) {
148 if constexpr (std::is_same<typename O::type, float>::value) {
149 return val;
150 } else {
151 O out;
152 #pragma unroll
153 for (int i = 0; i < O::size; i++) {
154 out.data[i] = downcast_s<typename O::type>(val.data[i]);
155 }
156 return out;
157 }
158 }
159
160 #if !defined(USE_ROCM)
161
162 static DINLINE void st_flag_release(FlagType* flag_addr, FlagType flag) {
163 #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700
164 asm volatile("st.release.sys.global.u32 [%1], %0;" ::"r"(flag),
165 "l"(flag_addr));
166 #else
167 asm volatile("membar.sys; st.volatile.global.u32 [%1], %0;" ::"r"(flag),
168 "l"(flag_addr));
169 #endif
170 }
171
172 static DINLINE FlagType ld_flag_acquire(FlagType* flag_addr) {
173 FlagType flag;
174 #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700
175 asm volatile("ld.acquire.sys.global.u32 %0, [%1];"
176 : "=r"(flag)
177 : "l"(flag_addr));
178 #else
179 asm volatile("ld.volatile.global.u32 %0, [%1]; membar.gl;"
180 : "=r"(flag)
181 : "l"(flag_addr));
182 #endif
183 return flag;
184 }
185
186 static DINLINE void st_flag_volatile(FlagType* flag_addr, FlagType flag) {
187 asm volatile("st.volatile.global.u32 [%1], %0;" ::"r"(flag), "l"(flag_addr));
188 }
189
190 static DINLINE FlagType ld_flag_volatile(FlagType* flag_addr) {
191 FlagType flag;
192 asm volatile("ld.volatile.global.u32 %0, [%1];"
193 : "=r"(flag)
194 : "l"(flag_addr));
195 return flag;
196 }
197
198 // This function is meant to be used as the first synchronization in the all
199 // reduce kernel. Thus, it doesn't need to make any visibility guarantees for
200 // prior memory accesses. Note: volatile writes will not be reordered against
201 // other volatile writes.
202 template <int ngpus>
203 DINLINE void barrier_at_start(const RankSignals& sg, Signal* self_sg,
204 int rank) {
205 uint32_t flag = self_sg->_flag[blockIdx.x] + 1;
206 if (threadIdx.x < ngpus) {
207 auto peer_counter_ptr = &sg.signals[threadIdx.x]->start[blockIdx.x][rank];
208 auto self_counter_ptr = &self_sg->start[blockIdx.x][threadIdx.x];
209 // Write the expected counter value to peer and wait for correct value
210 // from peer.
211 st_flag_volatile(peer_counter_ptr, flag);
212 while (ld_flag_volatile(self_counter_ptr) != flag);
213 }
214 __syncthreads();
215 // use one thread to update flag
216 if (threadIdx.x == 0) self_sg->_flag[blockIdx.x] = flag;
217 }
218
219 template <int ngpus>
220 DINLINE void barrier_at_start_release(const RankSignals& sg, Signal* self_sg,
221 int rank) {
222 __syncthreads();
223 uint32_t flag = self_sg->_flag[blockIdx.x] + 1;
224 if (threadIdx.x < ngpus) {
225 auto peer_counter_ptr = &sg.signals[threadIdx.x]->start[blockIdx.x][rank];
226 auto self_counter_ptr = &self_sg->start[blockIdx.x][threadIdx.x];
227 st_flag_release(peer_counter_ptr, flag);
228 while (ld_flag_acquire(self_counter_ptr) != flag);
229 }
230 __syncthreads();
231 if (threadIdx.x == 0) self_sg->_flag[blockIdx.x] = flag;
232 }
233
234 // This function is meant to be used as the second or the final
235 // synchronization barrier in the all reduce kernel. If it's the final
236 // synchronization barrier, we don't need to make any visibility guarantees
237 // for prior memory accesses.
238 template <int ngpus, bool final_sync = false>
239 DINLINE void barrier_at_end(const RankSignals& sg, Signal* self_sg, int rank) {
240 __syncthreads();
241 uint32_t flag = self_sg->_flag[blockIdx.x] + 1;
242 if (threadIdx.x < ngpus) {
243 auto peer_counter_ptr = &sg.signals[threadIdx.x]->end[blockIdx.x][rank];
244 auto self_counter_ptr = &self_sg->end[blockIdx.x][threadIdx.x];
245 // Write the expected counter value to peer and wait for correct value from
246 // peer.
247 if constexpr (!final_sync) {
248 st_flag_release(peer_counter_ptr, flag);
249 while (ld_flag_acquire(self_counter_ptr) != flag);
250 } else {
251 st_flag_volatile(peer_counter_ptr, flag);
252 while (ld_flag_volatile(self_counter_ptr) != flag);
253 }
254 }
255 if constexpr (!final_sync) __syncthreads();
256
257 // use one thread to update flag
258 if (threadIdx.x == 0) self_sg->_flag[blockIdx.x] = flag;
259 }
260
261 #else
262
263 template <int ngpus>
264 DINLINE void barrier_at_start(const RankSignals& sg, Signal* self_sg,
265 int rank) {
266 uint32_t flag = self_sg->_flag[blockIdx.x] + 1;
267 if (threadIdx.x < ngpus) {
268 // simultaneously write to the corresponding flag of all ranks.
269 // Latency = 1 p2p write
270 __scoped_atomic_store_n(&sg.signals[threadIdx.x]->start[blockIdx.x][rank],
271 flag, __ATOMIC_RELAXED, __MEMORY_SCOPE_SYSTEM);
272 // wait until we got true from all ranks
273 while (__scoped_atomic_load_n(&self_sg->start[blockIdx.x][threadIdx.x],
274 __ATOMIC_RELAXED,
275 __MEMORY_SCOPE_DEVICE) < flag);
276 }
277 __syncthreads();
278 // use one thread to update flag
279 if (threadIdx.x == 0) self_sg->_flag[blockIdx.x] = flag;
280 }
281
282 template <int ngpus>
283 DINLINE void barrier_at_start_release(const RankSignals& sg, Signal* self_sg,
284 int rank) {
285 __syncthreads();
286 uint32_t flag = self_sg->_flag[blockIdx.x] + 1;
287 if (threadIdx.x < ngpus) {
288 __scoped_atomic_store_n(&sg.signals[threadIdx.x]->start[blockIdx.x][rank],
289 flag, __ATOMIC_RELEASE, __MEMORY_SCOPE_SYSTEM);
290 while (__scoped_atomic_load_n(&self_sg->start[blockIdx.x][threadIdx.x],
291 __ATOMIC_ACQUIRE,
292 __MEMORY_SCOPE_DEVICE) < flag);
293 }
294 __syncthreads();
295 if (threadIdx.x == 0) self_sg->_flag[blockIdx.x] = flag;
296 }
297
298 template <int ngpus, bool final_sync = false>
299 DINLINE void barrier_at_end(const RankSignals& sg, Signal* self_sg, int rank) {
300 __syncthreads();
301 uint32_t flag = self_sg->_flag[blockIdx.x] + 1;
302 if (threadIdx.x < ngpus) {
303 // simultaneously write to the corresponding flag of all ranks.
304 // Latency = 1 p2p write
305 __scoped_atomic_store_n(&sg.signals[threadIdx.x]->end[blockIdx.x][rank],
306 flag,
307 final_sync ? __ATOMIC_RELAXED : __ATOMIC_RELEASE,
308 __MEMORY_SCOPE_SYSTEM);
309 // wait until we got true from all ranks
310 while (
311 __scoped_atomic_load_n(&self_sg->end[blockIdx.x][threadIdx.x],
312 final_sync ? __ATOMIC_RELAXED : __ATOMIC_ACQUIRE,
313 __MEMORY_SCOPE_DEVICE) < flag);
314 }
315 if constexpr (!final_sync) __syncthreads();
316 // use one thread to update flag
317 if (threadIdx.x == 0) self_sg->_flag[blockIdx.x] = flag;
318 }
319
320 #endif
321
322 template <typename P, int ngpus, typename A>
323 DINLINE P packed_reduce(const P* ptrs[], int idx) {
324 A tmp = upcast(ptrs[0][idx]);
325 #pragma unroll
326 for (int i = 1; i < ngpus; i++) {
327 packed_assign_add(tmp, upcast(ptrs[i][idx]));
328 }
329 return downcast<P>(tmp);
330 }
331
332 } // namespace vllm