Featured image of post HCCL通信库创新大赛记录——分块MESH

HCCL通信库创新大赛记录——分块MESH

HCCL集合通信库(Huawei Collective Communication Library,简称HCCL)是基于昇腾AI处理器的高性能通信库,聚焦于超大计算集群中的流量调度难题,为大集群提供高效可靠的通信服务,是华为AI软件生态CANN的核心组件之一,本文针对大数据量采用分块MESH算法

赛题回顾

环境:单机8卡昇腾910B服务器一台

赛题内容:在8PMesh中,断掉一根Full Mesh直连的路径(Rank0和Rank1之间的一根链路),完成AllReduce的集合通信语义

评分指标:使用算法分析工具验证,语义实现正确;在物理环境上运行HCCL Test工具,考察1KB、1MB、1GB这三种数据量下的算法带宽的均值,根据三种数据量下的算法带宽作为评判依据

算法思路

在中数据量的MESH算法中,每个健康节点将从其它节点接收完整的数据,总数据收发量为7倍的数据量,因此在大数据量下需要尽可能减少数据的通信量:

  1. 第一步(ReduceScatter):每个健康节点只负责一块数据块,并从所有节点拉取、聚合所负责的数据块;
  2. 第二步(AllGather):每个健康节点将所负责的数据块为最终的聚合结果,将该数据块推送到所有节点(包括不健康节点)。

在该算法中,每个健康节点仅负责1/6的数据量,因此数据收发量为7/3倍的数据量。

算法设计

ReduceScatter

相较于Mesh算法,CCL_OUT中仅放入节点所负责的数据块,而不是全部数据,例如Rank7仅负责下标为5的数据块,因此Rank7仅需将User Input中的数据块5拷贝至CCL_OUT,随后其它节点将数据块5直接推送到Rank7的CCL_OUT中进行聚合。其它健康节点同理。

AllGather

在ReduceScatter步骤后,Rank7中存放的是数据块5的最终聚合结果,该聚合结果需要告知其它各节点,例如Rank6直接从Rank7的CCL_OUT中拉取数据、拷贝到本地的User Output中。其它健康节点同理。

数据对齐

由于整块数据拆分为6块,很可能导致数据块的大小不满足16KB对齐,会导致严重影响DMA传输效率、缓存利用率、带宽利用率,因此在数据块划分时需注意16KB对齐。

任务编排

编程实现

cc

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
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
#include "coll_custom_huge_all_reduce_mesh_executor.h"

namespace hccl
{
    CollCustomHugeAllReduceMeshExecutor::CollCustomHugeAllReduceMeshExecutor(const HcclDispatcher dispatcher,
                                                                             std::unique_ptr<TopoMatcher> &topoMatcher)
        : CollCommExecutor(dispatcher, topoMatcher)
    {
    }

    // Calculate the amount of scratch memory to request
    HcclResult CollCustomHugeAllReduceMeshExecutor::CalcScratchMemSize(u64 &scratchMemSize)
    {
        // We don't need to use Scratch memory
        scratchMemSize = 0U;
        HCCL_WARNING("[HCCLContest][CollCustomHugeAllReduceMeshExecutor][CalcScratchMemSize] scratchMemSize: %u", scratchMemSize);
        return HCCL_SUCCESS;
    }

    // Calculate the number of streams to be requested
    HcclResult CollCustomHugeAllReduceMeshExecutor::CalcStreamNum(u32 &streamNum)
    {
        u32 totalStreamNum = topoAttr_.deviceNumPerAggregation;
        streamNum = totalStreamNum - 1U;
        HCCL_WARNING("[HCCLContest][CollCustomHugeAllReduceMeshExecutor][CalcStreamNum] streamNum: %u", streamNum);
        return HCCL_SUCCESS;
    }

    // Calculate the number of Notify to be requested
    HcclResult CollCustomHugeAllReduceMeshExecutor::CalcNotifyNum(u32 streamNum, u32 &notifyNum)
    {
        // ReducesScatter needs 2 Notify, AllGather needs 2 Notify
        notifyNum = 4U * streamNum;
        HCCL_WARNING("[HCCLContest][CollCustomHugeAllReduceMeshExecutor][CalcNotifyNum] notifyNum: %u", notifyNum);
        return HCCL_SUCCESS;
    }

    // Set up the level-0 mesh topology required for the AllReduce operation
    HcclResult CollCustomHugeAllReduceMeshExecutor::CalcCommInfo(std::vector<LevelNSubCommTransport> &opTransport)
    {
        HCCL_WARNING("[HCCLContest][CollCustomHugeAllReduceMeshExecutor][CalcCommInfo]");

        // Define the source and destination memory types for communication
        TransportMemType inputType = TransportMemType::CCL_INPUT;
        TransportMemType outputType = TransportMemType::CCL_OUTPUT;
        // Construct a mesh topology for level 0
        CommParaInfo commParaLevel0(COMM_LEVEL0, CommType::COMM_TAG_MESH);
        // Compute and populate the transport plan for level-0 communication domain
        CHK_RET(CalcCommPlaneInfo(tag_, commParaLevel0, opTransport[COMM_LEVEL0], inputType, outputType));
        return HCCL_SUCCESS;
    }

    // Calculate the number of iterations for loop processing
    u64 CollCustomHugeAllReduceMeshExecutor::CalcLoopMaxCount(const u64 cclBuffSize, const u32 unitSize)
    {
        u64 maxCountPerLoop = cclBuffSize / unitSize;
        HCCL_WARNING("[HCCLContest][CollCustomHugeAllReduceMeshExecutor][CalcLoopMaxCount] maxCountPerLoop: %u", maxCountPerLoop);
        return maxCountPerLoop;
    }

    // Entry point for orchestrating the AllReduce algorithm execution
    HcclResult CollCustomHugeAllReduceMeshExecutor::Orchestrate(OpParam &param, AlgResourceResponse &algRes)
    {
        HCCL_WARNING("[HCCLContest][CollCustomHugeAllReduceMeshExecutor][Orchestrate] count: %u", param.DataDes.count);
        tag_ = param.tag;
        algResResp_ = &algRes;

        // Cast and validate pointers to the user-provided input and output memory buffers
        u8 *userInputPtr = static_cast<u8 *>(param.inputPtr);
        u8 *userOutputPtr = static_cast<u8 *>(param.outputPtr);
        CHK_PTR_NULL(userInputPtr);
        CHK_PTR_NULL(userOutputPtr);

        // Determine the number of ranks in the communication domain
        CHK_RET(CheckCommSize(COMM_LEVEL0, COMM_INDEX_0 + 1));
        SubCommInfo level0CommInfo = GetSubCommInfo(COMM_LEVEL0, COMM_INDEX_0);
        u32 rankSize = level0CommInfo.localRankSize;

        // Determine the size of a single data unit (e.g., 4 bytes for fp32)
        u32 unitSize = SIZE_TABLE[param.DataDes.dataType];
        // Calculate max number of elements per iteration based on available CCL_Out memory
        u64 maxCountPerLoop = CalcLoopMaxCount(algRes.cclOutputMem.size(), unitSize) * (rankSize - BROKEN_RANK_COUNT);

        // Loop to process data in chunks if the total data count exceeds maxCountPerLoop
        // countLeft: Remaining number of data elements to process
        // curCount: Number of data elements processed in the current loop iteration
        // inputOffset: Current byte offset in user's input memory buffer
        // outputOffset: Current byte offset in user's output memory buffer
        for (u64 countLeft = param.DataDes.count, curCount = 0, inputOffset = 0, outputOffset = 0; countLeft > 0;)
        {
            // Determine the number of data elements for the current iteration
            curCount = (countLeft > maxCountPerLoop) ? maxCountPerLoop : countLeft;
            // Determine the total data size for the current iteration (unit: bytes)
            u64 curSize = curCount * unitSize;

            // Construct memory information for the current loop iteration
            ExecMem execMem;
            execMem.count = curCount;                         // Number of data elements to process in this loop
            execMem.inputPtr = userInputPtr + inputOffset;    // Pointer to the current offset of user's input memory buffer
            execMem.outputPtr = userOutputPtr + outputOffset; // Pointer to the current offset of user's output memory buffer
            execMem.inputMem = algRes.cclInputMem;            // Local CCL_Input memory
            execMem.outputMem = algRes.cclOutputMem;          // Local CCL_Output memory
            execMem.scratchMem = algRes.scratchMem;           // Local Scratch memory

            // Execute the kernel logic for the current data chunk
            CHK_RET(KernelRun(param, execMem));

            // Update offsets for the next loop iteration
            countLeft -= curCount;
            inputOffset += curSize;
            outputOffset += curSize;
        }
        return HCCL_SUCCESS;
    }

    // Process data for a single iteration of the AllReduce algorithm execution
    HcclResult CollCustomHugeAllReduceMeshExecutor::KernelRun(const OpParam &param, ExecMem &execMem)
    {
        // Get sub-communication domain information for level 0
        CHK_RET(CheckCommSize(COMM_LEVEL0, COMM_INDEX_0 + 1));
        SubCommInfo level0CommInfo = GetSubCommInfo(COMM_LEVEL0, COMM_INDEX_0);
        u32 rankSize = level0CommInfo.localRankSize;
        u32 rankId = level0CommInfo.localRank;
        u32 unitSize = SIZE_TABLE[param.DataDes.dataType];

        // Cut the chunk into multiple blocks
        CHK_RET(PrepareBlock(execMem.count, unitSize, rankSize - BROKEN_RANK_COUNT));

        // Perform ReduceScatter
        if (IsHealthyRank(rankId))
        {
            CHK_RET(HealthyPerformReduceScatter(param, execMem));
        }
        else
        {
            CHK_RET(UnhealthyPerformReduceScatter(param, execMem));
        }

        // Perform AllGather
        if (IsHealthyRank(rankId))
        {
            CHK_RET(HealthyPerformAllGather(param, execMem));
        }
        else
        {
            CHK_RET(UnhealthyPerformAllGather(param, execMem));
        }

        HCCL_WARNING("[HCCLContest][CollCustomHugeAllReduceMeshExecutor][KernelRun] localRank: %u, localRankSize: %u",
                     level0CommInfo.localRank, level0CommInfo.localRankSize);

        return HCCL_SUCCESS;
    }

    // Perform ReduceScatter
    //      col0 col1 col2 |      col0 col1 col2
    // R0: [ 2,   2,   2 ] | R0: [ 8,   2,   2 ]
    // R1: [ 2,   2,   2 ] | R1: [ 2,   8,   2 ]
    // R2: [ 2,   2,   2 ] | R2: [ 2,   2,   8 ]
    // -------------------   --------------------
    // R3: [ 2,   2,   2 ] | R3: [ 2,   2,   2 ]
    HcclResult CollCustomHugeAllReduceMeshExecutor::HealthyPerformReduceScatter(const OpParam &param, ExecMem &execMem)
    {
        // Retrieve the sub-communication domain information and master stream
        CHK_RET(CheckCommSize(COMM_LEVEL0, COMM_INDEX_0 + 1));
        SubCommInfo level0CommInfo = GetSubCommInfo(COMM_LEVEL0, COMM_INDEX_0);
        hccl::Stream &masterStream = const_cast<hccl::Stream &>(param.stream);

        // Dertermine the information for the topology and the data
        u32 rankSize = level0CommInfo.localRankSize;
        u32 rankId = level0CommInfo.localRank;
        u32 unitSize = SIZE_TABLE[param.DataDes.dataType];

        // For healthy ranks, copy data block from user input buffer to CCL_Out
        {
            u32 blockIdx = GetResponsibleBlockIdx(rankId);
            u64 blockSize = GetBlockSize(blockIdx);
            u64 blockOffset = GetBlockOffset(blockIdx);
            if (blockSize != 0)
            {
                DeviceMem src = DeviceMem::create(static_cast<char *>(execMem.inputPtr) + blockOffset, blockSize);
                DeviceMem dst = DeviceMem::create(execMem.outputMem.ptr(), blockSize);
                CHK_RET(HcclD2DMemcpyAsync(dispatcher_, dst, src, masterStream));
            }
        }

        // Post notify signals from master stream to all slave streams
        CHK_RET(MainPostToSlaves(param, execMem));
        // Slave streams wait for master's notification
        CHK_RET(SlavesWaitForMain(param, execMem));

        // Case A: The healthy rank notifies the unhealthy rank that it can reduce data
        // Case B: Normal communication between healthy ranks
        for (u32 round = 1; round < rankSize; round++)
        {
            // Get the slave stream assigned for communication with dstRank
            u32 dstRank = (round + rankId) % rankSize;
            Stream &subStream = algResResp_->slaveStreams[round - 1];

            // Case A: The healthy rank notifies the unhealthy rank that it can reduce data
            if (!IsHealthyRank(dstRank))
            {
                // Notify remote rank data has been ready
                CHK_RET(level0CommInfo.links[dstRank]->TxAck(subStream));
                // Wait for the remote rank to notify that data transfer and operations have completed
                CHK_RET(level0CommInfo.links[dstRank]->RxDataSignal(subStream));
                continue;
            }

            // Case B: Normal communication between healthy ranks
            // Dertermine the information for the data
            u32 blockIdx = GetResponsibleBlockIdx(dstRank);
            u64 blockSize = GetBlockSize(blockIdx);
            u64 blockOffset = GetBlockOffset(blockIdx);

            // Notify remote rank data has been ready
            CHK_RET(level0CommInfo.links[dstRank]->TxAck(subStream));
            // Wait for notification from the remote rank
            CHK_RET(level0CommInfo.links[dstRank]->RxAck(subStream));

            // Source address on localRank user input (local)
            void *srcLocalMemPtr = static_cast<char *>(execMem.inputPtr) + blockOffset;
            DeviceMem srcLocal = DeviceMem::create(static_cast<char *>(srcLocalMemPtr), blockSize);

            // Destination address on dstRank CCL_Out (remote)
            void *dstRemoteMemPtr = nullptr;
            CHK_RET(level0CommInfo.links[dstRank]->GetRemoteMem(UserMemType::OUTPUT_MEM, &dstRemoteMemPtr));
            DeviceMem dstRemote = DeviceMem::create(static_cast<char *>(dstRemoteMemPtr), blockSize);

            // Perform HcclD2DMemcpyAsync: Copy and reduce data from local user input to remote CCL_Out
            CHK_RET(HcclReduceAsync(dispatcher_, static_cast<void *>(srcLocal.ptr()), blockSize / unitSize,
                                    param.DataDes.dataType, param.reduceType, subStream,
                                    static_cast<void *>(dstRemote.ptr()),
                                    level0CommInfo.links[dstRank]->GetRemoteRank(),
                                    level0CommInfo.links[dstRank]->GetLinkType(),
                                    INLINE_REDUCE_BIT));

            // Notify the remote rank that data transfer and operations have completed
            CHK_RET(level0CommInfo.links[dstRank]->TxDataSignal(subStream));
            // Wait for data transfer and operations has been completed
            CHK_RET(level0CommInfo.links[dstRank]->RxDataSignal(subStream));
        }

        // Slave streams notify the master stream that their tasks are completed
        CHK_RET(SlavesPostToMain(param, execMem));
        // The master stream waits for all slave streams to complete their tasks
        CHK_RET(MainWaitForSlaves(param, execMem));

        return HCCL_SUCCESS;
    }

    HcclResult CollCustomHugeAllReduceMeshExecutor::UnhealthyPerformReduceScatter(const OpParam &param, ExecMem &execMem)
    {
        // Retrieve the sub-communication domain information and the master stream
        CHK_RET(CheckCommSize(COMM_LEVEL0, COMM_INDEX_0 + 1));
        SubCommInfo level0CommInfo = GetSubCommInfo(COMM_LEVEL0, COMM_INDEX_0);
        hccl::Stream &masterStream = const_cast<hccl::Stream &>(param.stream);

        // Dertermine the information for the topology and the data
        u32 rankSize = level0CommInfo.localRankSize;
        u32 rankId = level0CommInfo.localRank;
        u32 unitSize = SIZE_TABLE[param.DataDes.dataType];

        // Post notify signals from master stream to all slave streams
        CHK_RET(MainPostToSlaves(param, execMem));
        // Slave streams wait for master's notification
        CHK_RET(SlavesWaitForMain(param, execMem));

        // Case: Unhealthy ranks reduce data block to healthy ranks
        for (u32 round = 1; round < rankSize; round++)
        {
            // Get the slave stream assigned for communication with dstRank
            u32 dstRank = (round + rankId) % rankSize;
            Stream &subStream = algResResp_->slaveStreams[round - 1];

            // Skipping unhealthy ranks
            if (!IsHealthyRank(dstRank))
            {
                CHK_RET(SlaveExecEmptyTask(param, execMem, round - 1));
                continue;
            }

            // Dertermine the information for the data
            u32 blockIdx = GetResponsibleBlockIdx(dstRank);
            u64 blockSize = GetBlockSize(blockIdx);
            u64 blockOffset = GetBlockOffset(blockIdx);

            // Wait for notification from the remote rank
            CHK_RET(level0CommInfo.links[dstRank]->RxAck(subStream));

            // Source address on localRank user input (local)
            void *srcLocalMemPtr = static_cast<char *>(execMem.inputPtr) + blockOffset;
            DeviceMem srcLocal = DeviceMem::create(static_cast<char *>(srcLocalMemPtr), blockSize);

            // Destination address on dstRank CCL_Out (remote)
            void *dstRemoteMemPtr = nullptr;
            CHK_RET(level0CommInfo.links[dstRank]->GetRemoteMem(UserMemType::OUTPUT_MEM, &dstRemoteMemPtr));
            DeviceMem dstRemote = DeviceMem::create(static_cast<char *>(dstRemoteMemPtr), blockSize);

            // Perform HcclD2DMemcpyAsync: Copy and reduce data from local user input to remote CCL_Out
            CHK_RET(HcclReduceAsync(dispatcher_, static_cast<void *>(srcLocal.ptr()), blockSize / unitSize,
                                    param.DataDes.dataType, param.reduceType, subStream,
                                    static_cast<void *>(dstRemote.ptr()),
                                    level0CommInfo.links[dstRank]->GetRemoteRank(),
                                    level0CommInfo.links[dstRank]->GetLinkType(),
                                    INLINE_REDUCE_BIT));

            // Notify the remote rank that data transfer and operations have completed
            CHK_RET(level0CommInfo.links[dstRank]->TxDataSignal(subStream));
        }

        // Slave streams notify the master stream that their tasks are completed
        CHK_RET(SlavesPostToMain(param, execMem));
        // The master stream waits for all slave streams to complete their tasks
        CHK_RET(MainWaitForSlaves(param, execMem));

        return HCCL_SUCCESS;
    }

    // Perform AllGather
    //      col0 col1 col2 |      col0 col1 col2
    // R0: [ 8,   2,   2 ] | R0: [ 8,   8,   8 ]
    // R1: [ 2,   8,   2 ] | R1: [ 8,   8,   8 ]
    // R2: [ 2,   2,   8 ] | R2: [ 8,   8,   8 ]
    // -------------------   --------------------
    // R3: [ 2,   2,   2 ] | R3: [ 8,   8,   8 ]
    HcclResult CollCustomHugeAllReduceMeshExecutor::HealthyPerformAllGather(const OpParam &param, ExecMem &execMem)
    {
        // Retrieve the sub-communication domain information and the master stream
        CHK_RET(CheckCommSize(COMM_LEVEL0, COMM_INDEX_0 + 1));
        SubCommInfo level0CommInfo = GetSubCommInfo(COMM_LEVEL0, COMM_INDEX_0);
        hccl::Stream &masterStream = const_cast<hccl::Stream &>(param.stream);

        // Dertermine the information for the topology and the data
        u32 rankSize = level0CommInfo.localRankSize;
        u32 rankId = level0CommInfo.localRank;
        u32 unitSize = SIZE_TABLE[param.DataDes.dataType];

        // Post notify signals from master stream to all slave streams
        CHK_RET(MainPostToSlaves(param, execMem));
        // Slave streams wait for master's notification
        CHK_RET(SlavesWaitForMain(param, execMem));

        // For healthy ranks, copy data block from CCL_Out to user output buffer
        {
            u32 blockIdx = GetResponsibleBlockIdx(rankId);
            u64 blockSize = GetBlockSize(blockIdx);
            u64 blockOffset = GetBlockOffset(blockIdx);
            if (blockSize != 0)
            {
                DeviceMem src = DeviceMem::create(execMem.outputMem.ptr(), blockSize);
                DeviceMem dst = DeviceMem::create(static_cast<char *>(execMem.outputPtr) + blockOffset, blockSize);
                CHK_RET(HcclD2DMemcpyAsync(dispatcher_, dst, src, masterStream));
            }
        }

        // Case A: The healthy rank notifies the unhealthy rank that it can copy data
        // Case B: Normal communication between healthy ranks
        for (u32 round = 1; round < rankSize; round++)
        {
            // Get the slave stream assigned for communication with dstRank
            u32 dstRank = (rankId - round + rankSize) % rankSize;
            Stream &subStream = algResResp_->slaveStreams[round - 1];

            // Case A: The healthy rank notifies the unhealthy rank that it can copy data
            if (!IsHealthyRank(dstRank))
            {
                // Notify remote rank data has been ready
                CHK_RET(level0CommInfo.links[dstRank]->TxAck(subStream));
                // Wait for the remote rank to notify that data transfer and operations have completed
                CHK_RET(level0CommInfo.links[dstRank]->RxDataSignal(subStream));
                continue;
            }

            // Case B: Normal communication between healthy ranks
            // Dertermine the information for the data
            u32 blockIdx = GetResponsibleBlockIdx(dstRank);
            u64 blockSize = GetBlockSize(blockIdx);
            u64 blockOffset = GetBlockOffset(blockIdx);

            // Notify remote rank data has been ready
            CHK_RET(level0CommInfo.links[dstRank]->TxAck(subStream));
            // Wait for notification from the remote rank
            CHK_RET(level0CommInfo.links[dstRank]->RxAck(subStream));

            // Source address on dstRank CCL_Out (remote)
            void *srcRemoteMemPtr = nullptr;
            CHK_RET(level0CommInfo.links[dstRank]->GetRemoteMem(UserMemType::OUTPUT_MEM, &srcRemoteMemPtr));
            DeviceMem srcRemote = DeviceMem::create(static_cast<char *>(srcRemoteMemPtr), blockSize);

            // Destination address on localRank user-output (local)
            void *dstLocalMemPtr = static_cast<char *>(execMem.outputPtr) + blockOffset;
            DeviceMem dstLocal = DeviceMem::create(static_cast<char *>(dstLocalMemPtr), blockSize);

            // Perform HcclD2DMemcpyAsync
            CHK_RET(HcclD2DMemcpyAsync(dispatcher_, dstLocal, srcRemote, subStream,
                                       level0CommInfo.links[dstRank]->GetRemoteRank(),
                                       level0CommInfo.links[dstRank]->GetLinkType()));

            // Notify the remote rank that data transfer and operations have completed
            CHK_RET(level0CommInfo.links[dstRank]->TxDataSignal(subStream));
            // Wait for data transfer and operations has been completed
            CHK_RET(level0CommInfo.links[dstRank]->RxDataSignal(subStream));
        }

        // Slave streams notify the master stream that their tasks are completed
        CHK_RET(SlavesPostToMain(param, execMem));
        // The master stream waits for all slave streams to complete their tasks
        CHK_RET(MainWaitForSlaves(param, execMem));

        return HCCL_SUCCESS;
    }

    HcclResult CollCustomHugeAllReduceMeshExecutor::UnhealthyPerformAllGather(const OpParam &param, ExecMem &execMem)
    {
        // Retrieve the sub-communication domain information and the master stream
        CHK_RET(CheckCommSize(COMM_LEVEL0, COMM_INDEX_0 + 1));
        SubCommInfo level0CommInfo = GetSubCommInfo(COMM_LEVEL0, COMM_INDEX_0);
        hccl::Stream &masterStream = const_cast<hccl::Stream &>(param.stream);

        // Dertermine the information for the topology and the data
        u32 rankSize = level0CommInfo.localRankSize;
        u32 rankId = level0CommInfo.localRank;
        u32 unitSize = SIZE_TABLE[param.DataDes.dataType];

        // Post notify signals from master stream to all slave streams
        CHK_RET(MainPostToSlaves(param, execMem));
        // Slave streams wait for master's notification
        CHK_RET(SlavesWaitForMain(param, execMem));

        // Case: Unhealthy ranks copy data block from healthy ranks
        for (u32 round = 1; round < rankSize; round++)
        {
            // Get the slave stream assigned for communication with dstRank
            u32 dstRank = (rankId - round + rankSize) % rankSize;
            Stream &subStream = algResResp_->slaveStreams[round - 1];

            // Skipping unhealthy ranks
            if (!IsHealthyRank(dstRank))
            {
                CHK_RET(SlaveExecEmptyTask(param, execMem, round - 1));
                continue;
            }

            // Dertermine the information for the data
            u32 blockIdx = GetResponsibleBlockIdx(dstRank);
            u64 blockSize = GetBlockSize(blockIdx);
            u64 blockOffset = GetBlockOffset(blockIdx);

            // Wait for notification from the remote rank
            CHK_RET(level0CommInfo.links[dstRank]->RxAck(subStream));

            // Source address on dstRank CCL_Out (remote)
            void *srcRemoteMemPtr = nullptr;
            CHK_RET(level0CommInfo.links[dstRank]->GetRemoteMem(UserMemType::OUTPUT_MEM, &srcRemoteMemPtr));
            DeviceMem srcRemote = DeviceMem::create(static_cast<char *>(srcRemoteMemPtr), blockSize);

            // Destination address on localRank user-output (local)
            void *dstLocalMemPtr = static_cast<char *>(execMem.outputPtr) + blockOffset;
            DeviceMem dstLocal = DeviceMem::create(static_cast<char *>(dstLocalMemPtr), blockSize);

            // Perform HcclD2DMemcpyAsync
            CHK_RET(HcclD2DMemcpyAsync(dispatcher_, dstLocal, srcRemote, subStream,
                                       level0CommInfo.links[dstRank]->GetRemoteRank(),
                                       level0CommInfo.links[dstRank]->GetLinkType()));

            // Notify the remote rank that data transfer and operations have completed
            CHK_RET(level0CommInfo.links[dstRank]->TxDataSignal(subStream));
        }

        // Slave streams notify the master stream that their tasks are completed
        CHK_RET(SlavesPostToMain(param, execMem));
        // The master stream waits for all slave streams to complete their tasks
        CHK_RET(MainWaitForSlaves(param, execMem));

        return HCCL_SUCCESS;
    }

    // Determine if a rank is healthy
    bool CollCustomHugeAllReduceMeshExecutor::IsHealthyRank(u32 rankId)
    {
        return rankId != BROKEN_RANK_X && rankId != BROKEN_RANK_Y;
    }

    // Cut the chunk into multiple parts and ensure that the bytes are aligned
    HcclResult CollCustomHugeAllReduceMeshExecutor::PrepareBlock(u64 dataCount, u32 unitSize, u32 blockCount)
    {
        Block temp;
        u64 totalSize = dataCount * unitSize;
        dataBlock.clear();
        dataBlock.reserve(blockCount);
        if (blockCount == 0)
        {
            return HCCL_E_PARA;
        }
        u64 sizePerBlock = (totalSize + blockCount - 1) / blockCount;
        sizePerBlock = RoundUpWithDivisor(sizePerBlock, HCCL_MIN_SLICE_ALIGN_910B);
        u64 residueSize = totalSize;
        u32 i = 0;
        while (residueSize > 0)
        {
            u64 blockSize = sizePerBlock < residueSize ? sizePerBlock : residueSize;
            temp.size = blockSize;
            temp.offset = totalSize - residueSize;
            i++;
            if (blockSize <= 0)
            {
                return HCCL_E_PARA;
            }
            residueSize -= blockSize;
            dataBlock.push_back(temp);
        }
        while (i < blockCount)
        {
            temp.size = 0;
            temp.offset = totalSize;
            i++;
            dataBlock.push_back(temp);
        }
        return HCCL_SUCCESS;
    }

    // Get the size of the specific block
    u64 CollCustomHugeAllReduceMeshExecutor::GetBlockSize(u32 blockIdx)
    {
        return dataBlock[blockIdx].size;
    }

    // Get the offset of the specific block
    u64 CollCustomHugeAllReduceMeshExecutor::GetBlockOffset(u32 blockIdx)
    {
        return dataBlock[blockIdx].offset;
    }

    // Get the responsible block index of the specific rank
    u32 CollCustomHugeAllReduceMeshExecutor::GetResponsibleBlockIdx(u32 rankId)
    {
        return rankId - 2;
    }

    // Post notify signals from master stream to all slave streams
    HcclResult CollCustomHugeAllReduceMeshExecutor::MainPostToSlaves(const OpParam &param, ExecMem &execMem)
    {
        hccl::Stream &masterStream = const_cast<hccl::Stream &>(param.stream);
        for (u32 signalIndex = 0; signalIndex < algResResp_->slaveStreams.size(); signalIndex++)
        {
            CHK_RET(LocalNotify::Post(masterStream, dispatcher_,
                                      algResResp_->notifiesAux[signalIndex], PROF_STAGE_1));
        }
        return HCCL_SUCCESS;
    }

    // Slave streams wait for master's notification
    HcclResult CollCustomHugeAllReduceMeshExecutor::SlavesWaitForMain(const OpParam &param, ExecMem &execMem)
    {
        for (u32 streamIndex = 0; streamIndex < algResResp_->slaveStreams.size(); streamIndex++)
        {
            CHK_RET(LocalNotify::Wait(algResResp_->slaveStreams[streamIndex], dispatcher_,
                                      algResResp_->notifiesAux[streamIndex], PROF_STAGE_1));
        }
        return HCCL_SUCCESS;
    }

    // Slave streams notify the master stream that their tasks are completed
    HcclResult CollCustomHugeAllReduceMeshExecutor::SlavesPostToMain(const OpParam &param, ExecMem &execMem)
    {
        for (u32 streamIndex = 0; streamIndex < algResResp_->slaveStreams.size(); streamIndex++)
        {
            CHK_RET(LocalNotify::Post(algResResp_->slaveStreams[streamIndex], dispatcher_,
                                      algResResp_->notifiesMain[streamIndex], PROF_STAGE_1));
        }
        return HCCL_SUCCESS;
    }

    // The master stream waits for all slave streams to complete their tasks
    HcclResult CollCustomHugeAllReduceMeshExecutor::MainWaitForSlaves(const OpParam &param, ExecMem &execMem)
    {
        hccl::Stream &masterStream = const_cast<hccl::Stream &>(param.stream);
        for (u32 signalIndex = 0; signalIndex < algResResp_->slaveStreams.size(); signalIndex++)
        {
            CHK_RET(LocalNotify::Wait(masterStream, dispatcher_,
                                      algResResp_->notifiesMain[signalIndex], PROF_STAGE_1));
        }
        return HCCL_SUCCESS;
    }

    // The master stream executes an empty task to ensure synchronization
    HcclResult CollCustomHugeAllReduceMeshExecutor::MainExecEmptyTask(const OpParam &param, ExecMem &execMem)
    {
        hccl::Stream &masterStream = const_cast<hccl::Stream &>(param.stream);
        DeviceMem srcTmp = DeviceMem::create(execMem.inputPtr, 0);
        DeviceMem dstTmp = DeviceMem::create(execMem.outputPtr, 0);
        CHK_RET(HcclD2DMemcpyAsync(dispatcher_, dstTmp, srcTmp, masterStream));
        return HCCL_SUCCESS;
    }

    // The slave stream execute an empty task to ensure synchronization
    HcclResult CollCustomHugeAllReduceMeshExecutor::SlaveExecEmptyTask(const OpParam &param, ExecMem &execMem, u32 streamIndex)
    {
        hccl::Stream &masterStream = const_cast<hccl::Stream &>(param.stream);
        DeviceMem srcTmp = DeviceMem::create(execMem.inputPtr, 0);
        DeviceMem dstTmp = DeviceMem::create(execMem.outputPtr, 0);
        CHK_RET(HcclD2DMemcpyAsync(dispatcher_, dstTmp, srcTmp, algResResp_->slaveStreams[streamIndex]));
        return HCCL_SUCCESS;
    }

    REGISTER_EXEC("CustomHugeAllReduceMeshExecutor", CustomHugeAllReduceMesh, CollCustomHugeAllReduceMeshExecutor);
} // namespace hccl

h

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#ifndef COLL_CUSTOM_MEDIUM_ALLREDUCE_MESH_EXECUTOR_H
#define COLL_CUSTOM_MEDIUM_ALLREDUCE_MESH_EXECUTOR_H

// Define the ranks affected by the broken link
#define BROKEN_RANK_COUNT 2
#define BROKEN_RANK_X 0
#define BROKEN_RANK_Y 1

#include "coll_comm_executor.h"

namespace hccl
{
    class CollCustomHugeAllReduceMeshExecutor : public CollCommExecutor
    {
    public:
        CollCustomHugeAllReduceMeshExecutor(const HcclDispatcher dispatcher, std::unique_ptr<TopoMatcher> &topoMatcher);
        ~CollCustomHugeAllReduceMeshExecutor() = default;

    private:
        /* *************** 资源计算 *************** */
        HcclResult CalcScratchMemSize(u64 &scratchMemSize) override;
        HcclResult CalcStreamNum(u32 &streamNum) override;
        HcclResult CalcNotifyNum(u32 streamNum, u32 &notifyNum) override;
        HcclResult CalcCommInfo(std::vector<LevelNSubCommTransport> &opTransport) override;
        u64 CalcLoopMaxCount(const u64 cclBuffSize, const u32 unitSize);

        /* *************** 算法编排 *************** */
        HcclResult Orchestrate(OpParam &param, AlgResourceResponse &algRes);
        HcclResult KernelRun(const OpParam &param, ExecMem &execMem) override;
        HcclResult HealthyPerformReduceScatter(const OpParam &param, ExecMem &execMem);
        HcclResult UnhealthyPerformReduceScatter(const OpParam &param, ExecMem &execMem);
        HcclResult HealthyPerformAllGather(const OpParam &param, ExecMem &execMem);
        HcclResult UnhealthyPerformAllGather(const OpParam &param, ExecMem &execMem);
        bool IsHealthyRank(u32 rankId);

        /* *************** 数据块切分 *************** */
        struct Block
        {
            u64 offset{0};
            u64 size{0};
        };
        static inline u64 RoundUpWithDivisor(u64 value, u64 divisor)
        {
            if ((value == 0) || (divisor == 0))
            {
                return divisor;
            }
            return ((value + (divisor - 1)) / divisor) * divisor;
        }
        std::vector<Block> dataBlock;
        HcclResult PrepareBlock(u64 dataCount, u32 unitSize, u32 blockCount);
        u64 GetBlockSize(u32 blockIdx);
        u64 GetBlockOffset(u32 blockIdx);
        u32 GetResponsibleBlockIdx(u32 rankId);

        /* *************** 流间同步 *************** */
        HcclResult MainPostToSlaves(const OpParam &param, ExecMem &execMem);
        HcclResult SlavesWaitForMain(const OpParam &param, ExecMem &execMem);
        HcclResult SlavesPostToMain(const OpParam &param, ExecMem &execMem);
        HcclResult MainWaitForSlaves(const OpParam &param, ExecMem &execMem);
        HcclResult MainExecEmptyTask(const OpParam &param, ExecMem &execMem);
        HcclResult SlaveExecEmptyTask(const OpParam &param, ExecMem &execMem, u32 streamIndex);
    };
} // namespace hccl

#endif

算法性能

Licensed under CC BY-NC-SA 4.0
皖ICP备2025083746号-1
公安备案 陕公网安备61019002003315号



使用 Hugo 构建
主题 StackJimmy 设计