custom_all_reduce.cu 27.3 KB
Newer Older
Xiaowei.zhang's avatar
Xiaowei.zhang committed
1
/*
2
3
 * Copyright © Advanced Micro Devices, Inc. All rights reserved.
 * Copyright (C) 2024-2026, The vLLM team.
Xiaowei.zhang's avatar
Xiaowei.zhang committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "custom_all_reduce.cuh"
18
19
20
21
22
#include "aiter_stream.h"
#include "aiter_tensor.h"
#include <cstring>

using fp8_type = opus::fp8_t;
Xiaowei.zhang's avatar
Xiaowei.zhang committed
23

24
// fake pointer type, must match fptr_t type in custom_all_reduce.h
Xiaowei.zhang's avatar
Xiaowei.zhang committed
25
26
27
28
29
using fptr_t = int64_t;
static_assert(sizeof(void*) == sizeof(fptr_t));

namespace aiter {

30
31
32
33
34
35
// ---- init / dispose / meta_size ----

fptr_t init_custom_ar(int64_t meta_ptr,
                      int64_t rank_data_ptr,
                      int64_t rank_data_sz,
                      const std::vector<int64_t>& ipc_handle_ptrs,
Xiaowei.zhang's avatar
Xiaowei.zhang committed
36
37
38
39
40
41
42
43
44
                      const std::vector<int64_t>& offsets,
                      int64_t rank,
                      bool fully_connected)
{
    int world_size = offsets.size();
    if(world_size > 8)
        throw std::invalid_argument("world size > 8 is not supported");
    if(world_size % 2 != 0)
        throw std::invalid_argument("Odd num gpus is not supported for now");
45
    if(world_size != (int)ipc_handle_ptrs.size())
Xiaowei.zhang's avatar
Xiaowei.zhang committed
46
47
48
49
50
51
52
        throw std::invalid_argument("handles length should equal to offsets length");
    if(rank < 0 || rank >= world_size)
        throw std::invalid_argument("invalid rank passed in");

    hipIpcMemHandle_t ipc_handles[8];
    for(int i = 0; i < world_size; i++)
    {
53
        std::memcpy(&ipc_handles[i], (void*)ipc_handle_ptrs[i], sizeof(hipIpcMemHandle_t));
Xiaowei.zhang's avatar
Xiaowei.zhang committed
54
    }
55
56
57
    return (fptr_t) new aiter::CustomAllreduce(reinterpret_cast<aiter::Signal*>(meta_ptr),
                                               (void*)rank_data_ptr,
                                               rank_data_sz,
Xiaowei.zhang's avatar
Xiaowei.zhang committed
58
59
60
61
62
63
                                               ipc_handles,
                                               offsets,
                                               rank,
                                               fully_connected);
}

64
void dispose(fptr_t _fa)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
65
{
66
67
    auto fa = reinterpret_cast<aiter::CustomAllreduce*>(_fa);
    delete fa;
Xiaowei.zhang's avatar
Xiaowei.zhang committed
68
69
}

70
71
72
73
74
75
76
int64_t meta_size() { return sizeof(aiter::Signal); }

// ---- Internal dispatch helpers ----

static void _all_reduce(fptr_t _fa, void* inp, void* out,
                        int64_t numel, AiterDtype dtype,
                        bool use_new, bool open_fp8_quant, bool is_broadcast_reg_outptr)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
77
{
78
    hipStream_t stream = aiter::getCurrentHIPStream();
Xiaowei.zhang's avatar
Xiaowei.zhang committed
79
    auto fa = reinterpret_cast<aiter::CustomAllreduce*>(_fa);
80
    switch(dtype)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
81
    {
82
83
84
85
86
    case AITER_DTYPE_fp32: {
        fa->allreduce<opus::fp32_t>(stream,
                             reinterpret_cast<opus::fp32_t*>(inp),
                             reinterpret_cast<opus::fp32_t*>(out),
                             numel, use_new, is_broadcast_reg_outptr);
Xiaowei.zhang's avatar
Xiaowei.zhang committed
87
88
        break;
    }
89
90
    case AITER_DTYPE_fp16: {
        if(open_fp8_quant && numel >= 128 * 2048)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
91
        {
92
93
94
95
            fa->runFp8QuantKernel<opus::fp16_t>(stream,
                                        reinterpret_cast<opus::fp16_t*>(inp),
                                        reinterpret_cast<opus::fp16_t*>(out),
                                        numel);
Xiaowei.zhang's avatar
Xiaowei.zhang committed
96
97
98
        }
        else
        {
99
100
101
102
            fa->allreduce<opus::fp16_t>(stream,
                                reinterpret_cast<opus::fp16_t*>(inp),
                                reinterpret_cast<opus::fp16_t*>(out),
                                numel, use_new, is_broadcast_reg_outptr);
Xiaowei.zhang's avatar
Xiaowei.zhang committed
103
104
105
106
        }
        break;
    }
#if (__CUDA_ARCH__ >= 800 || !defined(__CUDA_ARCH__))
107
108
109
110
111
    case AITER_DTYPE_bf16: {
        fa->allreduce<opus::bf16_t>(stream,
                                      reinterpret_cast<opus::bf16_t*>(inp),
                                      reinterpret_cast<opus::bf16_t*>(out),
                                      numel, use_new);
Xiaowei.zhang's avatar
Xiaowei.zhang committed
112
113
114
115
116
117
118
119
        break;
    }
#endif
    default:
        throw std::runtime_error("custom allreduce only supports float32, float16 and bfloat16");
    }
}

120
121
static void _reduce_scatter(fptr_t _fa, void* inp, void* out,
                            int64_t size, AiterDtype dtype)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
122
{
123
    hipStream_t stream = aiter::getCurrentHIPStream();
Xiaowei.zhang's avatar
Xiaowei.zhang committed
124
    auto fa = reinterpret_cast<aiter::CustomAllreduce*>(_fa);
125
    switch(dtype)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
126
    {
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
    case AITER_DTYPE_fp32: {
        fa->dispatchReduceScatter<opus::fp32_t>(stream,
                                     reinterpret_cast<opus::fp32_t*>(inp),
                                     reinterpret_cast<opus::fp32_t*>(out),
                                     size);
        break;
    }
    case AITER_DTYPE_fp16: {
        fa->dispatchReduceScatter<opus::fp16_t>(stream,
                                    reinterpret_cast<opus::fp16_t*>(inp),
                                    reinterpret_cast<opus::fp16_t*>(out),
                                    size);
        break;
    }
#if (__CUDA_ARCH__ >= 800 || !defined(__CUDA_ARCH__))
    case AITER_DTYPE_bf16: {
        fa->dispatchReduceScatter<opus::bf16_t>(stream,
                                              reinterpret_cast<opus::bf16_t*>(inp),
                                              reinterpret_cast<opus::bf16_t*>(out),
                                              size);
        break;
Xiaowei.zhang's avatar
Xiaowei.zhang committed
148
149
    }
#endif
150
151
    default:
        throw std::runtime_error("custom allreduce only supports float32, float16 and bfloat16");
Xiaowei.zhang's avatar
Xiaowei.zhang committed
152
153
154
    }
}

155
156
157
static void _all_gather(fptr_t _fa, void* inp, void* out,
                        int64_t size, AiterDtype dtype,
                        int64_t last_dim_size, int64_t gather_dim)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
158
{
159
    hipStream_t stream = aiter::getCurrentHIPStream();
Xiaowei.zhang's avatar
Xiaowei.zhang committed
160
    auto fa = reinterpret_cast<aiter::CustomAllreduce*>(_fa);
161
    switch(dtype)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
162
    {
163
164
165
166
167
    case AITER_DTYPE_fp32: {
        fa->dispatchAllGather<opus::fp32_t>(stream,
                                     reinterpret_cast<opus::fp32_t*>(inp),
                                     reinterpret_cast<opus::fp32_t*>(out),
                                     size, last_dim_size, gather_dim);
Xiaowei.zhang's avatar
Xiaowei.zhang committed
168
169
        break;
    }
170
171
172
173
174
    case AITER_DTYPE_fp16: {
        fa->dispatchAllGather<opus::fp16_t>(stream,
                                    reinterpret_cast<opus::fp16_t*>(inp),
                                    reinterpret_cast<opus::fp16_t*>(out),
                                    size, last_dim_size, gather_dim);
Xiaowei.zhang's avatar
Xiaowei.zhang committed
175
176
177
        break;
    }
#if (__CUDA_ARCH__ >= 800 || !defined(__CUDA_ARCH__))
178
179
180
181
182
    case AITER_DTYPE_bf16: {
        fa->dispatchAllGather<opus::bf16_t>(stream,
                                    reinterpret_cast<opus::bf16_t*>(inp),
                                    reinterpret_cast<opus::bf16_t*>(out),
                                    size, last_dim_size, gather_dim);
Xiaowei.zhang's avatar
Xiaowei.zhang committed
183
184
185
186
187
188
189
190
        break;
    }
#endif
    default:
        throw std::runtime_error("custom allreduce only supports float32, float16 and bfloat16");
    }
}

191
192
193
194
195
196
197
static void _fused_allreduce_rmsnorm(fptr_t _fa,
                                     void* inp, void* residual_inp,
                                     void* residual_out, void* out,
                                     void* scale_out, void* w,
                                     AiterDtype dtype, float eps,
                                     int m, int n,
                                     bool use_1stage)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
198
{
199
200
201
    hipStream_t stream = aiter::getCurrentHIPStream();
    auto fa = reinterpret_cast<aiter::CustomAllreduce*>(_fa);
    bool use_fp8_per_token_quant = (scale_out != nullptr);
Xiaowei.zhang's avatar
Xiaowei.zhang committed
202

203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
#define DISPATCH_AR_FUSION(DTYPE)                                \
    if(!use_fp8_per_token_quant)                                 \
    {                                                            \
        fa->dispatchFusedAllReduceRMSNorm<DTYPE>(                \
            stream,                                              \
            reinterpret_cast<DTYPE*>(inp),                       \
            reinterpret_cast<DTYPE*>(residual_inp),              \
            reinterpret_cast<DTYPE*>(residual_out),              \
            reinterpret_cast<DTYPE*>(out),                       \
            reinterpret_cast<DTYPE*>(w),                         \
            eps,                                                 \
            m,                                                   \
            n,                                                   \
            use_1stage);                                         \
    }                                                            \
    else                                                         \
    {                                                            \
        fa->dispatchFusedAllReduceRMSNormQuant<DTYPE, fp8_type>( \
            stream,                                              \
            reinterpret_cast<DTYPE*>(inp),                       \
            reinterpret_cast<DTYPE*>(residual_inp),              \
            reinterpret_cast<DTYPE*>(residual_out),              \
            reinterpret_cast<fp8_type*>(out),                    \
            reinterpret_cast<float*>(scale_out),                 \
            reinterpret_cast<DTYPE*>(w),                         \
            eps,                                                 \
            m,                                                   \
            n,                                                   \
            use_1stage);                                         \
    }
Xiaowei.zhang's avatar
Xiaowei.zhang committed
233

234
    switch(dtype)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
235
    {
236
237
    case AITER_DTYPE_fp32: {
        DISPATCH_AR_FUSION(opus::fp32_t)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
238
239
        break;
    }
240
241
    case AITER_DTYPE_fp16: {
        DISPATCH_AR_FUSION(opus::fp16_t)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
242
243
        break;
    }
244
245
246
#if(__CUDA_ARCH__ >= 800 || !defined(__CUDA_ARCH__))
    case AITER_DTYPE_bf16: {
        DISPATCH_AR_FUSION(opus::bf16_t)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
247
248
249
250
251
252
        break;
    }
#endif
    default:
        throw std::runtime_error("custom allreduce only supports float32, float16 and bfloat16");
    }
253
254

#undef DISPATCH_AR_FUSION
Xiaowei.zhang's avatar
Xiaowei.zhang committed
255
256
}

257
258
259
260
261
262
// ---- Buffer registration ----

void register_input_buffer(fptr_t _fa,
                           int64_t self_ptr,
                           const std::vector<int64_t>& ipc_handle_ptrs,
                           const std::vector<int64_t>& offsets)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
263
{
264
265
266
267
    auto fa = reinterpret_cast<aiter::CustomAllreduce*>(_fa);
    int world_size = ipc_handle_ptrs.size();
    std::vector<hipIpcMemHandle_t> ipc_handles(world_size);
    for(int i = 0; i < world_size; i++)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
268
    {
269
        std::memcpy(&ipc_handles[i], (void*)ipc_handle_ptrs[i], sizeof(hipIpcMemHandle_t));
Xiaowei.zhang's avatar
Xiaowei.zhang committed
270
    }
271
    fa->register_input_buffer(ipc_handles.data(), offsets.data(), (void*)self_ptr);
Xiaowei.zhang's avatar
Xiaowei.zhang committed
272
273
}

274
275
276
277
void register_output_buffer(fptr_t _fa,
                            int64_t self_ptr,
                            const std::vector<int64_t>& ipc_handle_ptrs,
                            const std::vector<int64_t>& offsets)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
278
279
{
    auto fa = reinterpret_cast<aiter::CustomAllreduce*>(_fa);
280
281
282
283
284
285
286
    int world_size = ipc_handle_ptrs.size();
    std::vector<hipIpcMemHandle_t> ipc_handles(world_size);
    for(int i = 0; i < world_size; i++)
    {
        std::memcpy(&ipc_handles[i], (void*)ipc_handle_ptrs[i], sizeof(hipIpcMemHandle_t));
    }
    fa->register_output_buffer(ipc_handles.data(), offsets.data(), (void*)self_ptr);
Xiaowei.zhang's avatar
Xiaowei.zhang committed
287
288
}

289
int64_t get_graph_buffer_count(fptr_t _fa)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
290
291
{
    auto fa = reinterpret_cast<aiter::CustomAllreduce*>(_fa);
292
293
    return (int64_t)(fa->graph_unreg_input_buffers_.size() +
                     fa->graph_unreg_output_buffers_.size());
Xiaowei.zhang's avatar
Xiaowei.zhang committed
294
295
}

296
297
298
void get_graph_buffer_ipc_meta(fptr_t _fa,
                               int64_t handle_out,
                               int64_t offset_out)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
299
{
300
    auto fa = reinterpret_cast<aiter::CustomAllreduce*>(_fa);
Xiaowei.zhang's avatar
Xiaowei.zhang committed
301
    auto [handle_bytes, offsets] = fa->get_graph_buffer_ipc_meta();
302
303
    std::memcpy((void*)handle_out, handle_bytes.data(), handle_bytes.size());
    std::memcpy((void*)offset_out, offsets.data(), offsets.size() * sizeof(int64_t));
Xiaowei.zhang's avatar
Xiaowei.zhang committed
304
305
306
}

void register_graph_buffers(fptr_t _fa,
307
308
                            const std::vector<int64_t>& handle_ptrs,
                            const std::vector<int64_t>& offset_ptrs)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
309
310
{
    auto fa = reinterpret_cast<aiter::CustomAllreduce*>(_fa);
311
312
313
314
315
316
317
318
319
    int world_size = handle_ptrs.size();
    std::vector<const void*> handles(world_size);
    std::vector<const int64_t*> offsets(world_size);
    for(int i = 0; i < world_size; i++)
    {
        handles[i] = (const void*)handle_ptrs[i];
        offsets[i] = (const int64_t*)offset_ptrs[i];
    }
    fa->register_graph_buffers(handles.data(), offsets.data());
Xiaowei.zhang's avatar
Xiaowei.zhang committed
320
321
}

322
// ---- ROCm-specific utilities ----
Xiaowei.zhang's avatar
Xiaowei.zhang committed
323

324
#ifdef USE_ROCM
Xiaowei.zhang's avatar
Xiaowei.zhang committed
325

326
int64_t allocate_meta_buffer(int64_t size)
Xiaowei.zhang's avatar
Xiaowei.zhang committed
327
{
328
329
330
331
332
    int device_index;
    HIP_CALL(hipGetDevice(&device_index));
    HipDeviceGuard device_guard(device_index);
    hipStream_t stream = aiter::getCurrentHIPStream();
    void* buffer = nullptr;
Xiaowei.zhang's avatar
Xiaowei.zhang committed
333
334
    hipStreamCaptureMode mode = hipStreamCaptureModeRelaxed;
    HIP_CALL(hipThreadExchangeStreamCaptureMode(&mode));
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
    // Try uncached allocation first; fall back to regular hipMalloc if the
    // platform does not support hipDeviceMallocUncached (e.g. gfx936).
    hipError_t err = hipExtMallocWithFlags((void**)&buffer, size, hipDeviceMallocUncached);
    if(err != hipSuccess)
    {
        err = hipMalloc((void**)&buffer, size);
        if(err != hipSuccess)
        {
            HIP_CALL(hipThreadExchangeStreamCaptureMode(&mode));
            throw std::runtime_error(
                std::string("allocate_meta_buffer: hipMalloc(") +
                std::to_string(size) + " bytes) failed: " +
                hipGetErrorString(err));
        }
    }
Xiaowei.zhang's avatar
Xiaowei.zhang committed
350
351
352
    HIP_CALL(hipMemsetAsync(buffer, 0, size, stream));
    HIP_CALL(hipStreamSynchronize(stream));
    HIP_CALL(hipThreadExchangeStreamCaptureMode(&mode));
353
354
355
356
357
358
359
360
361
362
363
    return (int64_t)buffer;
}

void free_meta_buffer(int64_t ptr)
{
    HIP_CALL(hipFree((void*)ptr));
}

void get_meta_buffer_ipc_handle(int64_t inp_ptr, int64_t out_handle_ptr)
{
    HIP_CALL(hipIpcGetMemHandle((hipIpcMemHandle_t*)out_handle_ptr, (void*)inp_ptr));
Xiaowei.zhang's avatar
Xiaowei.zhang committed
364
365
366
367
}

#endif

368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
// ---- Public collective APIs ----

void all_reduce(fptr_t _fa,
                const aiter_tensor_t& inp,
                const aiter_tensor_t& out,
                bool use_new, bool open_fp8_quant,
                int64_t reg_inp_ptr, int64_t reg_inp_bytes)
{
    HipDeviceGuard device_guard(inp.device_id);
    hipStream_t stream = aiter::getCurrentHIPStream();
    auto dtype     = inp.dtype();
    int64_t numel  = inp.numel();
    int64_t data_bytes = numel * inp.element_size();

    void* actual_inp = inp.data_ptr();
    void* actual_out = out.data_ptr();

    // reg_inp_ptr == 0 means the input tensor itself is IPC-registered
    // (graph mode), so the write-mode kernel can directly write to peer
    // GPUs via IPC-registered output buffers.  In eager mode (reg_inp_ptr
    // != 0) the output is not IPC-registered, kernel uses temp-buffer path.
    bool is_broadcast_reg_outptr = (reg_inp_ptr == 0);

    if(reg_inp_ptr != 0)
    {
        if(data_bytes > reg_inp_bytes)
            throw std::runtime_error("registered buffer is too small to contain the input");
        HIP_CALL(hipMemcpyAsync((void*)reg_inp_ptr, actual_inp, data_bytes,
                                hipMemcpyDeviceToDevice, stream));
        actual_inp = (void*)reg_inp_ptr;
    }

    _all_reduce(_fa, actual_inp, actual_out, numel, dtype,
                use_new, open_fp8_quant, is_broadcast_reg_outptr);
}

void reduce_scatter(fptr_t _fa,
                    const aiter_tensor_t& inp,
                    const aiter_tensor_t& out,
                    int64_t reg_ptr, int64_t reg_bytes)
{
    HipDeviceGuard device_guard(inp.device_id);
    hipStream_t stream = aiter::getCurrentHIPStream();
    auto dtype     = inp.dtype();
    int64_t inp_numel  = inp.numel();
    int64_t data_bytes = inp_numel * inp.element_size();

    if(reg_ptr != 0)
    {
        if(data_bytes > reg_bytes)
            throw std::runtime_error("registered buffer is too small to contain the input");
        HIP_CALL(hipMemcpyAsync((void*)reg_ptr, inp.data_ptr(), data_bytes,
                                hipMemcpyDeviceToDevice, stream));
        _reduce_scatter(_fa, (void*)reg_ptr, out.data_ptr(), inp_numel, dtype);
    }
    else
    {
        _reduce_scatter(_fa, inp.data_ptr(), out.data_ptr(), inp_numel, dtype);
    }
}

void all_gather_reg(fptr_t _fa,
                    const aiter_tensor_t& inp,
                    const aiter_tensor_t& out,
                    int64_t dim)
{
    HipDeviceGuard device_guard(inp.device_id);
    int64_t last_dim_size = inp.size(-1);
    _all_gather(_fa, inp.data_ptr(), out.data_ptr(), inp.numel(), inp.dtype(),
                last_dim_size, dim);
}

void all_gather_unreg(fptr_t _fa,
                      const aiter_tensor_t& inp,
                      int64_t reg_buffer,
                      const aiter_tensor_t& out,
                      int64_t reg_bytes,
                      int64_t dim)
{
    HipDeviceGuard device_guard(inp.device_id);
    hipStream_t stream = aiter::getCurrentHIPStream();
    int64_t data_bytes = inp.numel() * inp.element_size();
    int64_t last_dim_size = inp.size(-1);

    if(data_bytes > reg_bytes)
        throw std::runtime_error("registered buffer is too small to contain the input");
    HIP_CALL(hipMemcpyAsync((void*)reg_buffer, inp.data_ptr(), data_bytes,
                            hipMemcpyDeviceToDevice, stream));
    _all_gather(_fa, (void*)reg_buffer, out.data_ptr(), inp.numel(), inp.dtype(),
                last_dim_size, dim);
}

void fused_allreduce_rmsnorm(fptr_t _fa,
                             const aiter_tensor_t& inp,
                             const aiter_tensor_t& res_inp,
                             const aiter_tensor_t& res_out,
                             const aiter_tensor_t& out,
                             const aiter_tensor_t& w,
                             double eps,
                             int64_t reg_ptr, int64_t reg_bytes,
                             bool use_1stage)
{
    HipDeviceGuard device_guard(inp.device_id);
    hipStream_t stream = aiter::getCurrentHIPStream();
    auto dtype     = inp.dtype();
    int64_t numel  = inp.numel();
    int64_t data_bytes = numel * inp.element_size();
    int n = (int)w.numel();
    int m = (int)(numel / w.numel());

    if(reg_ptr != 0)
    {
        if(data_bytes > reg_bytes)
            throw std::runtime_error("registered buffer is too small to contain the input");
        HIP_CALL(hipMemcpyAsync((void*)reg_ptr, inp.data_ptr(), data_bytes,
                                hipMemcpyDeviceToDevice, stream));
        _fused_allreduce_rmsnorm(_fa,
                                 (void*)reg_ptr, res_inp.data_ptr(), res_out.data_ptr(),
                                 out.data_ptr(), nullptr, w.data_ptr(),
                                 dtype, (float)eps, m, n, use_1stage);
    }
    else
    {
        _fused_allreduce_rmsnorm(_fa,
                                 inp.data_ptr(), res_inp.data_ptr(), res_out.data_ptr(),
                                 out.data_ptr(), nullptr, w.data_ptr(),
                                 dtype, (float)eps, m, n, use_1stage);
    }
}

void fused_allreduce_rmsnorm_quant(fptr_t _fa,
                                   const aiter_tensor_t& inp,
                                   const aiter_tensor_t& res_inp,
                                   const aiter_tensor_t& res_out,
                                   const aiter_tensor_t& out,
                                   const aiter_tensor_t& scale_out,
                                   const aiter_tensor_t& w,
                                   double eps,
                                   int64_t reg_ptr, int64_t reg_bytes,
                                   bool use_1stage)
{
    HipDeviceGuard device_guard(inp.device_id);
    hipStream_t stream = aiter::getCurrentHIPStream();
    auto dtype     = inp.dtype();
    int64_t numel  = inp.numel();
    int64_t data_bytes = numel * inp.element_size();
    int n = (int)w.numel();
    int m = (int)(numel / w.numel());

    if(reg_ptr != 0)
    {
        if(data_bytes > reg_bytes)
            throw std::runtime_error("registered buffer is too small to contain the input");
        HIP_CALL(hipMemcpyAsync((void*)reg_ptr, inp.data_ptr(), data_bytes,
                                hipMemcpyDeviceToDevice, stream));
        _fused_allreduce_rmsnorm(_fa,
                                 (void*)reg_ptr, res_inp.data_ptr(), res_out.data_ptr(),
                                 out.data_ptr(), scale_out.data_ptr(), w.data_ptr(),
                                 dtype, (float)eps, m, n, use_1stage);
    }
    else
    {
        _fused_allreduce_rmsnorm(_fa,
                                 inp.data_ptr(), res_inp.data_ptr(), res_out.data_ptr(),
                                 out.data_ptr(), scale_out.data_ptr(), w.data_ptr(),
                                 dtype, (float)eps, m, n, use_1stage);
    }
}

void fused_allreduce_rmsnorm_quant_per_group(fptr_t _fa,
                                             const aiter_tensor_t& inp,
                                             const aiter_tensor_t& res_inp,
                                             const aiter_tensor_t& res_out,
                                             const aiter_tensor_t& out,
                                             const aiter_tensor_t& scale_out,
                                             const aiter_tensor_t& w,
                                             double eps,
                                             int64_t group_size,
                                             int64_t reg_ptr, int64_t reg_bytes,
                                             bool use_1stage,
                                             int64_t bf16_out_ptr)
{
    HipDeviceGuard device_guard(inp.device_id);
    hipStream_t stream = aiter::getCurrentHIPStream();
    auto dtype     = inp.dtype();
    int64_t numel  = inp.numel();
    int64_t data_bytes = numel * inp.element_size();
    int n = (int)w.numel();
    int m = (int)(numel / w.numel());

    auto fa = reinterpret_cast<aiter::CustomAllreduce*>(_fa);

    void* inp_ptr = inp.data_ptr();
    if(reg_ptr != 0)
    {
        if(data_bytes > reg_bytes)
            throw std::runtime_error("registered buffer is too small to contain the input");
        HIP_CALL(hipMemcpyAsync((void*)reg_ptr, inp.data_ptr(), data_bytes,
                                hipMemcpyDeviceToDevice, stream));
        inp_ptr = (void*)reg_ptr;
    }

    // bf16_out_ptr is an opaque data pointer (0 = not requested). When non-zero
    // the fused kernel writes the pre-quantization bf16/fp16 normed output so
    // GDN-style callers can keep an unquantized view without launching a
    // separate per-group quant kernel.
    void* bf16_out = reinterpret_cast<void*>(bf16_out_ptr);

    switch(dtype)
    {
#if(__CUDA_ARCH__ >= 800 || !defined(__CUDA_ARCH__))
    case AITER_DTYPE_bf16: {
        fa->dispatchFusedAllReduceRMSNormQuantPerGroup<opus::bf16_t, fp8_type>(
            stream,
            reinterpret_cast<opus::bf16_t*>(inp_ptr),
            reinterpret_cast<opus::bf16_t*>(res_inp.data_ptr()),
            reinterpret_cast<opus::bf16_t*>(res_out.data_ptr()),
            reinterpret_cast<fp8_type*>(out.data_ptr()),
            reinterpret_cast<float*>(scale_out.data_ptr()),
            reinterpret_cast<opus::bf16_t*>(w.data_ptr()),
            (float)eps, m, n, (int)group_size, use_1stage,
            reinterpret_cast<opus::bf16_t*>(bf16_out));
        break;
    }
#endif
    case AITER_DTYPE_fp16: {
        fa->dispatchFusedAllReduceRMSNormQuantPerGroup<opus::fp16_t, fp8_type>(
            stream,
            reinterpret_cast<opus::fp16_t*>(inp_ptr),
            reinterpret_cast<opus::fp16_t*>(res_inp.data_ptr()),
            reinterpret_cast<opus::fp16_t*>(res_out.data_ptr()),
            reinterpret_cast<fp8_type*>(out.data_ptr()),
            reinterpret_cast<float*>(scale_out.data_ptr()),
            reinterpret_cast<opus::fp16_t*>(w.data_ptr()),
            (float)eps, m, n, (int)group_size, use_1stage,
            reinterpret_cast<opus::fp16_t*>(bf16_out));
        break;
    }
    default:
        throw std::runtime_error(
            "fused_allreduce_rmsnorm_quant_per_group only supports float16 and bfloat16");
    }
}

void fused_qknorm_allreduce(fptr_t _fa,
                            const aiter_tensor_t& qkv_in,
                            const aiter_tensor_t& q_w,
                            const aiter_tensor_t& k_w,
                            const aiter_tensor_t& q_out,
                            const aiter_tensor_t& k_out,
                            const aiter_tensor_t& v_out,
                            double eps,
                            int64_t reg_ptr,
                            int64_t reg_bytes)
{
    HipDeviceGuard device_guard(qkv_in.device_id);
    hipStream_t stream   = aiter::getCurrentHIPStream();
    auto dtype           = qkv_in.dtype();
    int64_t hidden_dim_q = q_w.numel();
    int64_t hidden_dim_k = k_w.numel();
    int64_t token_num    = qkv_in.size(0);
    int64_t hidden_dim_v = qkv_in.size(1) - (hidden_dim_q + hidden_dim_k);
    auto fa              = reinterpret_cast<aiter::CustomAllreduce*>(_fa);
    int64_t data_bytes   = qkv_in.numel() * qkv_in.element_size();
    void* inp_ptr        = qkv_in.data_ptr();

    if(reg_ptr != 0)
    {
        if(data_bytes > reg_bytes)
            throw std::runtime_error("registered buffer is too small to contain the input");
        HIP_CALL(hipMemcpyAsync((void*)reg_ptr, qkv_in.data_ptr(), data_bytes,
                                hipMemcpyDeviceToDevice, stream));
        inp_ptr = (void*)reg_ptr;
    }

#define DISPATCH_AR_FUSION(DTYPE)                                                           \
    {                                                                                       \
        fa->dispatchFusedQKNormAllReduce<DTYPE>(stream,                                     \
                                                reinterpret_cast<DTYPE*>(inp_ptr),          \
                                                reinterpret_cast<DTYPE*>(q_w.data_ptr()),   \
                                                reinterpret_cast<DTYPE*>(k_w.data_ptr()),   \
                                                reinterpret_cast<DTYPE*>(q_out.data_ptr()), \
                                                reinterpret_cast<DTYPE*>(k_out.data_ptr()), \
                                                reinterpret_cast<DTYPE*>(v_out.data_ptr()), \
                                                token_num,                                  \
                                                hidden_dim_q,                               \
                                                hidden_dim_k,                               \
                                                hidden_dim_v,                               \
                                                eps);                                       \
    }

    switch(dtype)
    {
    case AITER_DTYPE_fp32: {
        DISPATCH_AR_FUSION(opus::fp32_t)
        break;
    }
    case AITER_DTYPE_fp16: {
        DISPATCH_AR_FUSION(opus::fp16_t)
        break;
    }
#if(__CUDA_ARCH__ >= 800 || !defined(__CUDA_ARCH__))
    case AITER_DTYPE_bf16: {
        DISPATCH_AR_FUSION(opus::bf16_t)
        break;
    }
#endif
    default:
        throw std::runtime_error("custom allreduce only supports float32, float16 and bfloat16");
    }
}

Xiaowei.zhang's avatar
Xiaowei.zhang committed
680
} // namespace aiter