HCCL(Huawei Collective Communication Library)是华为为昇腾(Ascend)AI 处理器提供的集合通信库,用于分布式深度学习训练中多卡、多机之间的高速数据通信,它实现了 AllReduce、AllGather、Broadcast 等常见集合通信算子,并针对昇腾硬件和高速互联进行了深度优化,作用类似于 NVIDIA GPU 生态中的 NCCL,常用于 MindSpore 及 Ascend 生态下的大规模模型训练。
整体架构
核心组件
1 2 3 4 5 6 7 8 9 10 11 12
| src/domain/collective_communication/algorithm/ ├── pub_inc/ │ └── coll_executor_base.h # 执行器基类定义 ├── impl/ │ ├── operator/ │ │ └── custom_all_reduce_operator.cc # 算子实现 │ └── coll_executor/ │ ├── registry/ │ │ ├── coll_alg_exec_registry.h # 注册表定义 │ │ └── coll_alg_exec_registry.cc # 注册表实现 │ └── coll_all_reduce/ │ └── coll_custom_*_executor.cc # 具体执行器实现
|
类层次结构
1 2 3 4 5 6 7 8 9 10 11 12
| class CollExecutorBase { virtual HcclResult Orchestrate(...); virtual HcclResult CalcResRequest(...); };
class CollCommExecutor : public CollExecutorBase { };
class CollCustomSmallAllReduceMeshExecutor : public CollCommExecutor { };
|
注册机制
注册宏定义
1 2 3 4 5 6 7 8 9
| #define REGISTER_EXEC(tag, name, collExecBase) \ static CollExecCreator collExecCreator = \ [](const HcclDispatcher dispatcher, std::unique_ptr<TopoMatcher> &topoMatcher) \ -> CollExecutorBase * { \ return new collExecBase(dispatcher, topoMatcher); \ }; \ static HcclResult ret = \ CollAlgExecRegistry::Instance().Register(tag, collExecCreator)
|
注册表实现
1 2 3 4 5 6 7 8 9 10
| class CollAlgExecRegistry { private: std::map<std::string, CollExecCreator> execCreators_; static CollAlgExecRegistry globalExecRegistry;
public: static CollAlgExecRegistry& Instance(); HcclResult Register(const std::string& tag, const CollExecCreator& creator); std::unique_ptr<CollExecutorBase> GetAlgExec(const std::string& tag, ...); };
|
工作原理
编译期机制
1 2 3 4 5 6
| 源文件编译过程: custom_executor.cc -> custom_executor.o ├── .text段:执行器实现代码 ├── .init段:注册初始化代码 └── .data段:静态对象数据
|
内存布局
1 2 3 4 5 6 7 8
| 最终可执行文件布局: .init段: |- 所有REGISTER_EXEC生成的初始化代码 .data段: |- CollAlgExecRegistry单例 |- 其他静态数据 .text段: |- 所有executor实现代码
|
执行流程
1 2 3 4 5 6 7 8 9 10 11 12 13
| static CollExecCreator creator = [...]; static HcclResult ret = Registry::Register();
HcclResult CustomAllReduceOperator::SelectAlg(...) { if (dataSize <= SMALL_COUNT) { algName = "CustomSmallAllReduceMeshExecutor"; } }
auto executor = CollAlgExecRegistry::Instance().GetAlgExec(algName, ...);
|
关键特性
静态初始化特性
- 利用C++静态对象构造顺序
- 程序启动前完成注册
- 零运行时注册开销
符号可见性控制
1 2 3 4
| namespace { static CollExecCreator creator = [...]; static HcclResult ret = [...]; }
|
运行时灵活性
- 通过字符串标识符动态选择算法
- 支持条件选择不同实现
- 易于扩展新算法
优势对比
对比传统静态链接
1 2 3 4 5 6 7 8 9
| 静态链接库: - 需要导出符号 - 编译时确定 - 按需链接.o文件
HCCL注册机制: - 符号可完全隐藏 - 运行时动态选择 - 注册表统一管理
|
设计优势
更好的封装性
更灵活的扩展性
更好的运行时特性
使用示例
实现新执行器
1 2 3 4 5 6 7 8 9
| class CustomExecutor : public CollCommExecutor { HcclResult Orchestrate(...) override { } };
REGISTER_EXEC("CustomExecutor", Custom, CustomExecutor);
|
在算子中使用
1 2 3 4 5 6
| HcclResult CustomOperator::SelectAlg(...) { if (meetCondition) { algName = "CustomExecutor"; } return HCCL_SUCCESS; }
|
这个机制结合了C++的静态初始化特性和运行时的灵活性,提供了一个优雅的算法注册和管理方案。