Merged
engram torch api #9308
luozhonglinAdd on Jul 29
engram torch api #9308
Merged
Total: 4 files changed+563-69
| @@ -407,6 +407,12 @@ static ge::graphStatus CheckTrainingParams(const gert::TilingContext *context, i | |||
| 407 | (std::to_string(recvCountsOutShape->GetStorageShape().GetDimNum()) + "D").c_str(), | 407 | (std::to_string(recvCountsOutShape->GetStorageShape().GetDimNum()) + "D").c_str(), |
| 408 | "The shape dim of recvCountsOut must be 1D."), | 408 | "The shape dim of recvCountsOut must be 1D."), |
| 409 | return ge::GRAPH_FAILED); | 409 | return ge::GRAPH_FAILED); |
| 410 | + OP_TILING_CHECK( | ||
| 411 | + recvCountsOutShape->GetStorageShape().GetDim(0) <= 0, | ||
| 412 | + OP_LOGE_FOR_INVALID_VALUE( | ||
| 413 | + nodeName, "recvCountsOut", | ||
| 414 | + (std::string("dim0=") + std::to_string(recvCountsOutShape->GetStorageShape().GetDim(0))).c_str(), "> 0"), | ||
| 415 | + return ge::GRAPH_FAILED); | ||
| 410 | 416 | ||
| 411 | const gert::StorageShape *recvLocalEntryOutShape = context->GetOutputShape(RECV_LOCAL_ENTRY_OUT_INDEX); | 417 | const gert::StorageShape *recvLocalEntryOutShape = context->GetOutputShape(RECV_LOCAL_ENTRY_OUT_INDEX); |
| 412 | OP_TILING_CHECK(recvLocalEntryOutShape == nullptr, OP_LOGE_WITH_INVALID_INPUT(nodeName, "recvLocalEntryOut"), | 418 | OP_TILING_CHECK(recvLocalEntryOutShape == nullptr, OP_LOGE_WITH_INVALID_INPUT(nodeName, "recvLocalEntryOut"), |
| @@ -26,6 +26,7 @@ | |||
| 26 | ElasticBuffer类提供统一的分布式通信buffer管理能力: | 26 | ElasticBuffer类提供统一的分布式通信buffer管理能力: |
| 27 | 27 | ||
| 28 | - Engram存储接口用于分布式Engram存储管理,支持将本rank的表写入host pinned共享段,以及通过RDMA从远端rank抓取Engram数据。需与 [get_engram_storage_size_hint](#get_engram_storage_size_hint静态方法) 配套使用。 | 28 | - Engram存储接口用于分布式Engram存储管理,支持将本rank的表写入host pinned共享段,以及通过RDMA从远端rank抓取Engram数据。需与 [get_engram_storage_size_hint](#get_engram_storage_size_hint静态方法) 配套使用。 |
| 29 | +- Engram训练接口在推理接口的基础上,通过 `with_grad=True` 开启训练模式。前向 [engram_fetch](#engram_fetch) 在抓取数据的同时保存反向所需的通信元数据(封装为 [EngramFetchCtx](#engramfetchctx)),反向 [engram_fetch_grad](#engram_fetch_grad) 根据这些元数据将梯度沿前向路径反向交换并按local entry稀疏累加,产出稀疏梯度用于优化器更新。 | ||
| 29 | - Dispatch/Combine接口用于MoE的Expert Parallelism(EP)并行部署,支持通过[dispatch](#dispatch)将token数据分发到对应专家卡,再通过[combine](#combine)将专家输出按原路由聚合回原始序列。需与[get_moe_ep_ccl_buffer_size](#get_moe_ep_ccl_buffer_size静态方法)配套使用。 | 30 | - Dispatch/Combine接口用于MoE的Expert Parallelism(EP)并行部署,支持通过[dispatch](#dispatch)将token数据分发到对应专家卡,再通过[combine](#combine)将专家输出按原路由聚合回原始序列。需与[get_moe_ep_ccl_buffer_size](#get_moe_ep_ccl_buffer_size静态方法)配套使用。 |
| 30 | 31 | ||
| 31 | ## 函数原型 | 32 | ## 函数原型 |
| @@ -40,11 +41,18 @@ class ElasticBuffer: | |||
| 40 | num_max_tokens_per_rank: Optional[int] = None, | 41 | num_max_tokens_per_rank: Optional[int] = None, |
| 41 | hidden: Optional[int] = None, | 42 | hidden: Optional[int] = None, |
| 42 | num_topk: Optional[int] = None, | 43 | num_topk: Optional[int] = None, |
| 44 | + with_grad: bool = False, | ||
| 43 | ) | 45 | ) |
| 44 | 46 | ||
| 45 | def engram_write(self, storage: torch.Tensor) -> None | 47 | def engram_write(self, storage: torch.Tensor) -> None |
| 46 | 48 | ||
| 47 | - def engram_fetch(self, indices: torch.Tensor) -> Callable[[], torch.Tensor] | 49 | + def engram_fetch(self, indices: torch.Tensor) -> Callable |
| 50 | + | ||
| 51 | + def engram_fetch_grad( | ||
| 52 | + self, | ||
| 53 | + grad_fetched: torch.Tensor, | ||
| 54 | + fetch_ctx: EngramFetchCtx, | ||
| 55 | + ) -> Tuple[torch.Tensor, torch.Tensor] | ||
| 48 | 56 | ||
| 49 | def barrier(self, use_comm_stream: bool = True, with_cpu_sync: bool = False) -> None | 57 | def barrier(self, use_comm_stream: bool = True, with_cpu_sync: bool = False) -> None |
| 50 | 58 | ||
| @@ -90,6 +98,18 @@ class ElasticBuffer: | |||
| 90 | def destroy(self) -> None | 98 | def destroy(self) -> None |
| 91 | ``` | 99 | ``` |
| 92 | 100 | ||
| 101 | +## EngramFetchCtx | ||
| 102 | + | ||
| 103 | +前向 [engram_fetch](#engram_fetch) 在 `with_grad=True` 时返回的save-for-backward上下文,需原样传递给反向 [engram_fetch_grad](#engram_fetch_grad)。该对象由内部自动构造,无需手动创建。 | ||
| 104 | + | ||
| 105 | +| 属性 | 类型 | shape | 说明 | | ||
| 106 | +|------|------|-------|------| | ||
| 107 | +| `perm` | `Tensor` | `(T,)` int32 | 桶排列序索引,反向按此重排梯度 | | ||
| 108 | +| `send_counts` | `Tensor` | `(W*8,)` int32 | 每rank发送的index数量(填充至32字节对齐,前W个元素有效),反向a2a的send量 | | ||
| 109 | +| `recv_counts` | `Tensor` | `(W,)` int32 | 每rank接收的index数量,反向a2a的recv量 | | ||
| 110 | +| `recv_local_entry` | `Tensor` | `(R_max,)` int32 | 接收到的local entry索引,反向按此scatter-add | | ||
| 111 | +| `num_recv` | `Tensor` | `(1,)` int32 | 实际接收行数R | | ||
| 112 | + | ||
| 93 | ## 成员函数说明 | 113 | ## 成员函数说明 |
| 94 | 114 | ||
| 95 | ### **init** | 115 | ### **init** |
| @@ -101,15 +121,16 @@ class ElasticBuffer: | |||
| 101 | - **group** (`torch.distributed.ProcessGroup`):必选参数,分布式进程组,用于跨rank通信和同步。 | 121 | - **group** (`torch.distributed.ProcessGroup`):必选参数,分布式进程组,用于跨rank通信和同步。 |
| 102 | - <strong>*</strong>:其之前的变量是位置相关的;之后的变量是可选参数,需要使用键值对赋值,不赋值会使用默认值。 | 122 | - <strong>*</strong>:其之前的变量是位置相关的;之后的变量是可选参数,需要使用键值对赋值,不赋值会使用默认值。 |
| 103 | - **num_cpu_bytes** (`int`):可选参数,CPU buffer大小(字节),用于host pinned存储区分配。默认值为0,且必须2MB对齐。 | 123 | - **num_cpu_bytes** (`int`):可选参数,CPU buffer大小(字节),用于host pinned存储区分配。默认值为0,且必须2MB对齐。 |
| 104 | -- **num_max_tokens_per_rank** (`int`):可选参数,表示每张卡上的最大token数量上限。使用 [dispatch](#dispatch) 和 [combine](#combine) 时必须与 `hidden`、`num_topk` 一起指定。 | 124 | +- **num_max_tokens_per_rank** (`int`):可选参数,表示每张卡上的最大token数量上限。使用 [dispatch](#dispatch) 和 [combine](#combine) 时必须与 `hidden`、`num_topk` 一起指定;使用 `with_grad=True` 训练模式时必须指定且大于0。 |
| 105 | - **hidden** (`int`):可选参数,hidden size隐藏层大小。 | 125 | - **hidden** (`int`):可选参数,hidden size隐藏层大小。 |
| 106 | - **num_topk** (`int`):可选参数,表示选取topK个专家。 | 126 | - **num_topk** (`int`):可选参数,表示选取topK个专家。 |
| 127 | +- **with_grad** (`bool`):可选参数,是否开启训练。默认为 `False`(推理)。设为 `True` 时,前向 [engram_fetch](#engram_fetch) 会额外保存反向所需的通信元数据(封装为 [EngramFetchCtx](#engramfetchctx)),并可通过 [engram_fetch_grad](#engram_fetch_grad) 执行反向。 | ||
| 107 | 128 | ||
| 108 | **输出**:无返回值,构造ElasticBuffer实例。 | 129 | **输出**:无返回值,构造ElasticBuffer实例。 |
| 109 | 130 | ||
| 110 | ### engram_write | 131 | ### engram_write |
| 111 | 132 | ||
| 112 | -**功能**:将本rank的Engram表数据写入host pinned共享内存段,使其他rank可通过RDMA读取该数据。 | 133 | +**功能**:将本rank的Engram表数据写入host pinned共享内存段,使其他rank可通过RDMA读取该数据。推理模式和训练模式均通过此接口写入storage。写入完成后,内部会自动获取通信上下文tensor、本地storage地址、通信buffer大小和rank数等信息,供后续 [engram_fetch](#engram_fetch) 使用。 |
| 113 | 134 | ||
| 114 | > **host pinned共享内存段**:指通过 `aclrtMallocHost` 分配的页锁定(pinned)主机内存,并经 `aclrtHostRegisterV2` 映射后获得设备可访问地址。该内存段既可被本卡NPU直接访问,也可被远端rank的NPU通过RDMA读取,从而实现跨rank的零拷贝数据共享。其大小由构造函数的 `num_cpu_bytes` 参数指定。 | 135 | > **host pinned共享内存段**:指通过 `aclrtMallocHost` 分配的页锁定(pinned)主机内存,并经 `aclrtHostRegisterV2` 映射后获得设备可访问地址。该内存段既可被本卡NPU直接访问,也可被远端rank的NPU通过RDMA读取,从而实现跨rank的零拷贝数据共享。其大小由构造函数的 `num_cpu_bytes` 参数指定。 |
| 115 | 136 | ||
| @@ -131,13 +152,16 @@ ElasticBuffer.engram_write(storage) -> None | |||
| 131 | 152 | ||
| 132 | **输入参数**: | 153 | **输入参数**: |
| 133 | 154 | ||
| 134 | -- **storage** (`Tensor`):必选参数,待写入的CPU tensor,shape为 `(num_entries, hidden)`,表示有 `num_entries` 个条目,每个条目维度为 `hidden`。 | 155 | +- **storage** (`Tensor`):必选参数,待写入的CPU tensor,shape为 `(num_entries, hidden)`,表示有 `num_entries` 个条目,每个条目维度为 `hidden`。要求2维、连续、`hidden`必须128对齐,数据类型支持 `bfloat16`、`float16`、`float32`。 |
| 135 | 156 | ||
| 136 | **输出说明**:无返回值,数据写入host pinned内存。 | 157 | **输出说明**:无返回值,数据写入host pinned内存。 |
| 137 | 158 | ||
| 138 | ### engram_fetch | 159 | ### engram_fetch |
| 139 | 160 | ||
| 140 | -**功能**:根据输入的全局索引,通过RDMA从对应rank的host pinned共享内存中抓取对应的Engram数据。接口采用异步设计:调用后立即返回一个callable,执行该callable时阻塞等待RDMA传输完成并返回结果tensor。 | 161 | +**功能**:根据输入的全局索引,从对应rank抓取Engram数据。推理和训练的行为由构造时的 `with_grad` 决定: |
| 162 | + | ||
| 163 | +- **推理**(`with_grad=False`):通过RDMA one-sided read从远端rank的host pinned共享内存抓取数据。接口采用异步设计:调用后立即返回一个callable,执行该callable时阻塞等待RDMA传输完成并返回结果tensor。 | ||
| 164 | +- **训练**(`with_grad=True`):通过all-to-all通信从远端rank抓取数据(桶排序 → a2a交换indices → 本地gather → a2a交换data → 还原),返回一个callable,执行该callable时等待传输完成并返回 `(fetched, fetch_ctx)` 二元组,其中 `fetch_ctx` 为save-for-backward上下文 [EngramFetchCtx](#engramfetchctx)。 | ||
| 141 | 165 | ||
| 142 | **计算公式**: | 166 | **计算公式**: |
| 143 | 167 | ||
| @@ -163,7 +187,7 @@ $EngramTable[rank\_id][local\_idx]$ 表示其中第 $local\_idx$ 个条目。 | |||
| 163 | **函数原型**: | 187 | **函数原型**: |
| 164 | 188 | ||
| 165 | ```python | 189 | ```python |
| 166 | -ElasticBuffer.engram_fetch(indices) -> Callable[[], Tensor] | 190 | +ElasticBuffer.engram_fetch(indices) -> Callable |
| 167 | ``` | 191 | ``` |
| 168 | 192 | ||
| 169 | **输入参数**: | 193 | **输入参数**: |
| @@ -172,12 +196,37 @@ ElasticBuffer.engram_fetch(indices) -> Callable[[], Tensor] | |||
| 172 | 196 | ||
| 173 | **输出说明**: | 197 | **输出说明**: |
| 174 | 198 | ||
| 175 | -- **wait_callable** (`Callable[[], Tensor]`):返回一个callable,调用时阻塞至RDMA完成并返回fetched tensor。 | 199 | +- **wait_callable** (`Callable`):返回一个callable,调用时根据模式返回不同结果。 |
| 176 | 200 | ||
| 177 | -调用 `wait_callable()` 返回: | 201 | +**推理**调用 `wait_callable()` 返回: |
| 178 | 202 | ||
| 179 | - **fetched** (`Tensor`):NPU tensor,shape为 `(num_tokens, hidden)`,数据类型与 [engram_write](#engram_write) 的 `storage.dtype` 相同,数据格式为 $ND$。 | 203 | - **fetched** (`Tensor`):NPU tensor,shape为 `(num_tokens, hidden)`,数据类型与 [engram_write](#engram_write) 的 `storage.dtype` 相同,数据格式为 $ND$。 |
| 180 | 204 | ||
| 205 | +**训练**调用 `wait_callable()` 返回: | ||
| 206 | + | ||
| 207 | +- **fetched** (`Tensor`):NPU tensor,shape为 `(num_tokens, hidden)`,数据类型与 `storage.dtype` 相同,数据格式为 $ND$。 | ||
| 208 | +- **fetch_ctx** (`EngramFetchCtx`):save-for-backward上下文,包含反向所需的5个通信元数据tensor(详见 [EngramFetchCtx](#engramfetchctx))。需原样传递给 [engram_fetch_grad](#engram_fetch_grad)。 | ||
| 209 | + | ||
| 210 | +### engram_fetch_grad | ||
| 211 | + | ||
| 212 | +**功能**:训练反向接口,需与训练模式的 [engram_fetch](#engram_fetch) 配套使用。根据前向保存的 [EngramFetchCtx](#engramfetchctx),将 `grad_fetched` 沿前向路径反向交换并按local entry稀疏累加,产出稀疏梯度用于优化器更新。 | ||
| 213 | + | ||
| 214 | +**函数原型**: | ||
| 215 | + | ||
| 216 | +```python | ||
| 217 | +ElasticBuffer.engram_fetch_grad(grad_fetched, fetch_ctx) -> (Tensor, Tensor) | ||
| 218 | +``` | ||
| 219 | + | ||
| 220 | +**输入参数**: | ||
| 221 | + | ||
| 222 | +- **grad_fetched** (`Tensor`):必选参数,前向 `fetched` 的梯度,NPU tensor,shape为 `(num_tokens, hidden)`,数据类型支持 `bfloat16`、`float16`、`float32`,数据格式为 $ND$。 | ||
| 223 | +- **fetch_ctx** (`EngramFetchCtx`):必选参数,前向 [engram_fetch](#engram_fetch) 训练模式返回的上下文对象,包含 `perm`、`send_counts`、`recv_counts`、`recv_local_entry`、`num_recv` 五个字段。 | ||
| 224 | + | ||
| 225 | +**输出说明**: | ||
| 226 | + | ||
| 227 | +- **grad_unique** (`Tensor`):NPU tensor,shape为 `(K, hidden)`,数据类型与 `grad_fetched` 相同(kernel内部按FP32累加后转回输出dtype),数据格式为 $ND$。其中 `K` 为去重后的local entry数量(运行时决定),前 `K` 行有效。 | ||
| 228 | +- **unique_local_entry** (`Tensor`):NPU tensor,shape为 `(K,)`,数据类型为 `int32`,数据格式为 $ND$。表示 `grad_unique` 每行对应的local entry索引,用于优化器按索引更新 `storage[unique_local_entry] -= lr × grad_unique`。 | ||
| 229 | + | ||
| 181 | ### barrier | 230 | ### barrier |
| 182 | 231 | ||
| 183 | **功能**:跨卡同步。 | 232 | **功能**:跨卡同步。 |
| @@ -382,7 +431,7 @@ ccl_buffer_size = Align2(Align1MB(minimum_buffer_size) / 1MB) / 2 | |||
| 382 | 431 | ||
| 383 | ### destroy | 432 | ### destroy |
| 384 | 433 | ||
| 385 | -**功能**:释放ElasticBuffer资源,包括host pinned内存、Engram运行时资源和Dispatch/Combine通信上下文。 | 434 | +**功能**:释放ElasticBuffer资源,包括host pinned内存、Engram运行时资源和Dispatch/Combine通信上下文。训练模式下HCCL默认通信buffer由框架管理,无需手动释放。 |
| 386 | 435 | ||
| 387 | **输入参数**:无参数。 | 436 | **输入参数**:无参数。 |
| 388 | 437 | ||
| @@ -410,6 +459,13 @@ ccl_buffer_size = Align2(Align1MB(minimum_buffer_size) / 1MB) / 2 | |||
| 410 | - **Engram调用顺序约束**: | 459 | - **Engram调用顺序约束**: |
| 411 | - 必须先调用 [engram_write](#engram_write) 至少一次,才能调用 [engram_fetch](#engram_fetch)。 | 460 | - 必须先调用 [engram_write](#engram_write) 至少一次,才能调用 [engram_fetch](#engram_fetch)。 |
| 412 | - 同一ElasticBuffer实例上不允许并发 [engram_fetch](#engram_fetch)(需等待上次fetch的callable执行完成)。 | 461 | - 同一ElasticBuffer实例上不允许并发 [engram_fetch](#engram_fetch)(需等待上次fetch的callable执行完成)。 |
| 462 | + - 训练模式下,必须先调用 [engram_fetch](#engram_fetch)(训练模式)获取 `fetch_ctx`,才能调用 [engram_fetch_grad](#engram_fetch_grad)。 | ||
| 463 | + | ||
| 464 | +- **Engram训练模式约束**: | ||
| 465 | + - `with_grad=True` 时,`num_max_tokens_per_rank` 必须为正整数。 | ||
| 466 | + - `with_grad=True` 时,[engram_fetch](#engram_fetch) 返回的 `fetch_ctx` 为局部变量,多次fetch不会覆盖(每次调用返回独立的ctx)。 | ||
| 467 | + - [engram_fetch_grad](#engram_fetch_grad) 的 `grad_fetched` shape 必须与前向 `fetched` 一致。 | ||
| 468 | + - 训练模式下,通信buffer使用HCCL默认buffer(大小受 `HCCL_BUFFSIZE` 环境变量控制,默认200MB),由框架管理,无需手动申请或释放。 | ||
| 413 | 469 | ||
| 414 | - **Engram数值约束**: | 470 | - **Engram数值约束**: |
| 415 | - `num_cpu_bytes`、`num_entries`必须非负。 | 471 | - `num_cpu_bytes`、`num_entries`必须非负。 |
| @@ -552,6 +608,101 @@ if __name__ == "__main__": | |||
| 552 | exit(1) | 608 | exit(1) |
| 553 | ``` | 609 | ``` |
| 554 | 610 | ||
| 611 | +### Engram训练模式调用(多卡分布式) | ||
| 612 | + | ||
| 613 | +```python | ||
| 614 | +import os | ||
| 615 | +import torch | ||
| 616 | +import torch_npu | ||
| 617 | +import torch.distributed as dist | ||
| 618 | +from torch.multiprocessing import Process | ||
| 619 | +from cann_ops_transformer import ElasticBuffer | ||
| 620 | + | ||
| 621 | +num_entries = 4 | ||
| 622 | +hidden = 128 | ||
| 623 | +dtype = torch.bfloat16 | ||
| 624 | +world_size = 2 | ||
| 625 | +num_tokens = 6 | ||
| 626 | + | ||
| 627 | + | ||
| 628 | +def set_device(rank): | ||
| 629 | + torch_npu.npu.set_device(rank) | ||
| 630 | + | ||
| 631 | + | ||
| 632 | +def init_hccl_comm(rank, world_size): | ||
| 633 | + dist.init_process_group( | ||
| 634 | + backend="hccl", | ||
| 635 | + rank=rank, | ||
| 636 | + world_size=world_size, | ||
| 637 | + init_method=f"tcp://127.0.0.1:50003", | ||
| 638 | + ) | ||
| 639 | + return dist.new_group(backend="hccl", ranks=list(range(world_size))) | ||
| 640 | + | ||
| 641 | + | ||
| 642 | +def train_worker(rank): | ||
| 643 | + set_device(rank) | ||
| 644 | + group = init_hccl_comm(rank, world_size) | ||
| 645 | + device = f"npu:{rank}" | ||
| 646 | + | ||
| 647 | + # ==================== 生成 embedding 和 indices ==================== | ||
| 648 | + torch.manual_seed(42 + rank) | ||
| 649 | + storage = torch.randn(num_entries, hidden, dtype=dtype) | ||
| 650 | + total_entries = num_entries * world_size | ||
| 651 | + | ||
| 652 | + torch.manual_seed(100 + rank) | ||
| 653 | + indices = torch.randint(0, total_entries, (num_tokens,), dtype=torch.int32) | ||
| 654 | + | ||
| 655 | + # ==================== 创建 ElasticBuffer(with_grad=True)==================== | ||
| 656 | + num_cpu_bytes = ElasticBuffer.get_engram_storage_size_hint( | ||
| 657 | + num_entries, hidden, dtype | ||
| 658 | + ) | ||
| 659 | + buffer = ElasticBuffer( | ||
| 660 | + group=group, | ||
| 661 | + num_cpu_bytes=num_cpu_bytes, | ||
| 662 | + num_max_tokens_per_rank=num_tokens, | ||
| 663 | + with_grad=True, | ||
| 664 | + ) | ||
| 665 | + | ||
| 666 | + # ==================== 写入 storage ==================== | ||
| 667 | + buffer.engram_write(storage) | ||
| 668 | + dist.barrier() | ||
| 669 | + torch.npu.synchronize() | ||
| 670 | + | ||
| 671 | + # ==================== 训练前向 ==================== | ||
| 672 | + indices_npu = indices.to(device) | ||
| 673 | + fetched, fetch_ctx = buffer.engram_fetch(indices_npu)() | ||
| 674 | + print(f"[rank {rank}] forward: fetched shape={fetched.shape}") | ||
| 675 | + | ||
| 676 | + # ==================== 训练反向 ==================== | ||
| 677 | + # 假设 grad_fetched 来自 loss.backward() | ||
| 678 | + grad_fetched = fetched.clone() | ||
| 679 | + grad_unique, unique_local_entry = buffer.engram_fetch_grad(grad_fetched, fetch_ctx) | ||
| 680 | + print(f"[rank {rank}] backward: grad_unique shape={grad_unique.shape}, dtype={grad_unique.dtype}") | ||
| 681 | + print(f"[rank {rank}] backward: unique_local_entry={unique_local_entry.cpu().tolist()}") | ||
| 682 | + | ||
| 683 | + # ==================== 优化器更新(稀疏) ==================== | ||
| 684 | + # storage[unique_local_entry] -= lr * grad_unique | ||
| 685 | + # 注意: grad_unique 与 grad_fetched 同 dtype, 需类型转换后更新 storage | ||
| 686 | + | ||
| 687 | + # ==================== 清理 ==================== | ||
| 688 | + dist.barrier() | ||
| 689 | + torch.npu.synchronize() | ||
| 690 | + buffer.destroy() | ||
| 691 | + dist.destroy_process_group() | ||
| 692 | + | ||
| 693 | + | ||
| 694 | +if __name__ == "__main__": | ||
| 695 | + torch.multiprocessing.set_start_method("forkserver", force=True) | ||
| 696 | + proc_list = [] | ||
| 697 | + for rank in range(world_size): | ||
| 698 | + proc = Process(target=train_worker, args=(rank,)) | ||
| 699 | + proc.start() | ||
| 700 | + proc_list.append(proc) | ||
| 701 | + for proc in proc_list: | ||
| 702 | + proc.join() | ||
| 703 | + print("All processes finished.") | ||
| 704 | +``` | ||
| 705 | + | ||
| 555 | ### Dispatch/Combine单算子模式调用(多卡分布式) | 706 | ### Dispatch/Combine单算子模式调用(多卡分布式) |
| 556 | 707 | ||
| 557 | ```python | 708 | ```python |
| @@ -56,6 +56,7 @@ constexpr int64_t BUFFER_ALIGNMENT = 2 * 1024 * 1024; | |||
| 56 | constexpr int DIM_TWO = 2; | 56 | constexpr int DIM_TWO = 2; |
| 57 | constexpr uint32_t MOE_CHANNEL_HANDLE_NUM = 72U; | 57 | constexpr uint32_t MOE_CHANNEL_HANDLE_NUM = 72U; |
| 58 | constexpr uint32_t MOE_CHANNEL_NOTIFY_NUM = 3U; | 58 | constexpr uint32_t MOE_CHANNEL_NOTIFY_NUM = 3U; |
| 59 | +constexpr int64_t SEND_COUNTS_ALIGN_FACTOR = 8; | ||
| 59 | 60 | ||
| 60 | // RAII guard for multi-step host buffer allocation | 61 | // RAII guard for multi-step host buffer allocation |
| 61 | struct HostBufferGuard { | 62 | struct HostBufferGuard { |
| @@ -110,6 +111,7 @@ static inline void NpuStreamWait(aclrtStream waitStream, aclrtStream recordStrea | |||
| 110 | TORCH_CHECK(ret == ACL_SUCCESS, "aclrtDestroyEvent failed, ret: ", ret); | 111 | TORCH_CHECK(ret == ACL_SUCCESS, "aclrtDestroyEvent failed, ret: ", ret); |
| 111 | } | 112 | } |
| 112 | 113 | ||
| 114 | +// CommContext structure for HCCL communication | ||
| 113 | struct EngramCommContext { | 115 | struct EngramCommContext { |
| 114 | uint32_t rankId = 0; | 116 | uint32_t rankId = 0; |
| 115 | uint32_t rankSize = 0; | 117 | uint32_t rankSize = 0; |
| @@ -131,6 +133,7 @@ struct EngramContextResources { | |||
| 131 | HcclMemHandle memHandle = nullptr; | 133 | HcclMemHandle memHandle = nullptr; |
| 132 | void *hostBufPtr = nullptr; | 134 | void *hostBufPtr = nullptr; |
| 133 | void *deviceBufPtr = nullptr; | 135 | void *deviceBufPtr = nullptr; |
| 136 | + int64_t commBufferSize = 0; | ||
| 134 | EngramCommContext context; | 137 | EngramCommContext context; |
| 135 | at::Tensor contextTensor; | 138 | at::Tensor contextTensor; |
| 136 | }; | 139 | }; |
| @@ -204,8 +207,9 @@ protected: | |||
| 204 | 207 | ||
| 205 | class EngramContextBuilder : public HcclContextBuilderBase { | 208 | class EngramContextBuilder : public HcclContextBuilderBase { |
| 206 | public: | 209 | public: |
| 207 | - EngramContextResources Build(const std::string &groupName, int64_t numCpuBytes) | 210 | + EngramContextResources Build(const std::string &groupName, int64_t numCpuBytes, bool withGrad) |
| 208 | { | 211 | { |
| 212 | + withGrad_ = withGrad; | ||
| 209 | EngramContextResources resources; | 213 | EngramContextResources resources; |
| 210 | AcquireHcclHandle(groupName, resources.hcclComm); | 214 | AcquireHcclHandle(groupName, resources.hcclComm); |
| 211 | 215 | ||
| @@ -220,6 +224,8 @@ public: | |||
| 220 | } | 224 | } |
| 221 | 225 | ||
| 222 | private: | 226 | private: |
| 227 | + bool withGrad_ = false; | ||
| 228 | + | ||
| 223 | static void ValidateRankSize(uint32_t rankSize) | 229 | static void ValidateRankSize(uint32_t rankSize) |
| 224 | { | 230 | { |
| 225 | TORCH_CHECK(rankSize >= HCCL_MIN_RANK_SIZE, "rankSize must be at least HCCL_MIN_RANK_SIZE, got ", rankSize, | 231 | TORCH_CHECK(rankSize >= HCCL_MIN_RANK_SIZE, "rankSize must be at least HCCL_MIN_RANK_SIZE, got ", rankSize, |
| @@ -360,7 +366,6 @@ private: | |||
| 360 | auto hcclRet = HcclChannelGetRemoteMemsFunc(commHandle, resources.context.hcommHandle[i * channelsPerRank], | 366 | auto hcclRet = HcclChannelGetRemoteMemsFunc(commHandle, resources.context.hcommHandle[i * channelsPerRank], |
| 361 | &memNum, &remoteMems, &memTags); | 367 | &memNum, &remoteMems, &memTags); |
| 362 | TORCH_CHECK(hcclRet == HCCL_SUCCESS, "HcclChannelGetRemoteMems(peer=", i, ") failed, ret=", hcclRet); | 368 | TORCH_CHECK(hcclRet == HCCL_SUCCESS, "HcclChannelGetRemoteMems(peer=", i, ") failed, ret=", hcclRet); |
| 363 | - // 取自己注册的buffer作为通信buffer | ||
| 364 | bool hasTargetMem = false; | 369 | bool hasTargetMem = false; |
| 365 | for (uint32_t j = 0; j < memNum; j++) { | 370 | for (uint32_t j = 0; j < memNum; j++) { |
| 366 | if (memTags == nullptr || remoteMems == nullptr) { | 371 | if (memTags == nullptr || remoteMems == nullptr) { |
| @@ -379,8 +384,49 @@ private: | |||
| 379 | } | 384 | } |
| 380 | } | 385 | } |
| 381 | 386 | ||
| 382 | - static void CreateContext(EngramContextResources &resources, const std::string &contextTag, int64_t numCpuBytes, | 387 | + static void QueryHcclBufferResource(const HcclComm &commHandle, EngramContextResources &resources) |
| 383 | - HostBufferGuard &guard) | 388 | + { |
| 389 | + uint32_t rankId = resources.context.rankId; | ||
| 390 | + constexpr uint32_t channelsPerPeer = 2U; | ||
| 391 | + resources.context.channelsPerRank = channelsPerPeer; | ||
| 392 | + ChannelHandle handlesByRank[HCCL_MAX_RANK_SIZE * 2] = {}; | ||
| 393 | + GetHcclCommChannel(commHandle, resources.context.rankSize, rankId, channelsPerPeer, | ||
| 394 | + resources.memHandle, handlesByRank); | ||
| 395 | + for (uint32_t peer = 0; peer < resources.context.rankSize; ++peer) { | ||
| 396 | + if (peer == rankId) | ||
| 397 | + continue; | ||
| 398 | + for (uint32_t ch = 0; ch < channelsPerPeer; ++ch) { | ||
| 399 | + resources.context.hcommHandle[peer * channelsPerPeer + ch] = handlesByRank[peer * channelsPerPeer + ch]; | ||
| 400 | + } | ||
| 401 | + } | ||
| 402 | + | ||
| 403 | + void *localBuffer = nullptr; | ||
| 404 | + uint64_t localBufferSize = 0; | ||
| 405 | + auto hcclRet = HcclGetHcclBufferFunc(commHandle, &localBuffer, &localBufferSize); | ||
| 406 | + TORCH_CHECK(hcclRet == HCCL_SUCCESS, "HcclGetHcclBuffer failed, ret=", hcclRet); | ||
| 407 | + TORCH_CHECK(localBuffer != nullptr && localBufferSize > 0, | ||
| 408 | + "HCCL default buffer is null or empty, size=", localBufferSize); | ||
| 409 | + | ||
| 410 | + resources.commBufferSize = static_cast<int64_t>(localBufferSize); | ||
| 411 | + resources.context.virtualAddrList[rankId] = reinterpret_cast<uint64_t>(localBuffer); | ||
| 412 | + | ||
| 413 | + for (uint32_t i = 0; i < resources.context.rankSize; ++i) { | ||
| 414 | + if (i == rankId) { | ||
| 415 | + continue; | ||
| 416 | + } | ||
| 417 | + void *remoteBuffer = nullptr; | ||
| 418 | + uint64_t remoteBufSize = 0; | ||
| 419 | + hcclRet = HcclChannelGetHcclBufferFunc(commHandle, | ||
| 420 | + resources.context.hcommHandle[i * channelsPerPeer], | ||
| 421 | + &remoteBuffer, &remoteBufSize); | ||
| 422 | + TORCH_CHECK(hcclRet == HCCL_SUCCESS, "HcclChannelGetHcclBuffer(peer=", i, ") failed, ret=", hcclRet); | ||
| 423 | + TORCH_CHECK(remoteBuffer != nullptr, "HCCL remote buffer is null for peer=", i); | ||
| 424 | + resources.context.virtualAddrList[i] = reinterpret_cast<uint64_t>(remoteBuffer); | ||
| 425 | + } | ||
| 426 | + } | ||
| 427 | + | ||
| 428 | + void CreateContext(EngramContextResources &resources, const std::string &contextTag, int64_t numCpuBytes, | ||
| 429 | + HostBufferGuard &guard) | ||
| 384 | { | 430 | { |
| 385 | uint64_t contextSize = sizeof(EngramCommContext); | 431 | uint64_t contextSize = sizeof(EngramCommContext); |
| 386 | void *ctx = nullptr; | 432 | void *ctx = nullptr; |
| @@ -395,7 +441,12 @@ private: | |||
| 395 | 441 | ||
| 396 | std::string memBufferTag = contextTag + "_buffer"; | 442 | std::string memBufferTag = contextTag + "_buffer"; |
| 397 | AllocateAndRegisterBuffer(resources.hcclComm, memBufferTag, numCpuBytes, resources, guard); | 443 | AllocateAndRegisterBuffer(resources.hcclComm, memBufferTag, numCpuBytes, resources, guard); |
| 398 | - GetHcclCommResource(resources.hcclComm, resources, memBufferTag); | 444 | + |
| 445 | + if (withGrad_) { | ||
| 446 | + QueryHcclBufferResource(resources.hcclComm, resources); | ||
| 447 | + } else { | ||
| 448 | + GetHcclCommResource(resources.hcclComm, resources, memBufferTag); | ||
| 449 | + } | ||
| 399 | 450 | ||
| 400 | CopyContextToDevice(resources.hcclComm, contextTag, CommEngine::COMM_ENGINE_AIV, &resources.context, | 451 | CopyContextToDevice(resources.hcclComm, contextTag, CommEngine::COMM_ENGINE_AIV, &resources.context, |
| 401 | contextSize); | 452 | contextSize); |
| @@ -696,7 +747,8 @@ private: | |||
| 696 | // ElasticBuffer class - unified interface for Engram storage and MoE EP kernels | 747 | // ElasticBuffer class - unified interface for Engram storage and MoE EP kernels |
| 697 | class ElasticBuffer { | 748 | class ElasticBuffer { |
| 698 | public: | 749 | public: |
| 699 | - ElasticBuffer(const std::string &groupName, int64_t numCpuBytes); | 750 | + ElasticBuffer(const std::string &groupName, int64_t numCpuBytes, int64_t numMaxTokensPerRank = 0, |
| 751 | + bool withGrad = false); | ||
| 700 | ~ElasticBuffer(); | 752 | ~ElasticBuffer(); |
| 701 | 753 | ||
| 702 | void EngramWrite(const at::Tensor &storage); | 754 | void EngramWrite(const at::Tensor &storage); |
| @@ -704,13 +756,29 @@ public: | |||
| 704 | void Destroy(); | 756 | void Destroy(); |
| 705 | 757 | ||
| 706 | int64_t GetHostBufPtr() const { return reinterpret_cast<int64_t>(engramHostBufPtr_); } | 758 | int64_t GetHostBufPtr() const { return reinterpret_cast<int64_t>(engramHostBufPtr_); } |
| 707 | - | ||
| 708 | const at::Tensor &GetContextTensor() const { return engramContextTensor_; } | 759 | const at::Tensor &GetContextTensor() const { return engramContextTensor_; } |
| 760 | + const at::Tensor &GetLocalStorageAddrTensor() const { return localStorageAddrTensor_; } | ||
| 761 | + int64_t GetCommBufferSize() const { return commBufferSize_; } | ||
| 762 | + uint32_t GetRankSize() const { return engramCommContext_.rankSize; } | ||
| 709 | 763 | ||
| 710 | static at::Tensor EngramFetch(const at::Tensor &context, const at::Tensor &indices, int64_t hiddenSize, | 764 | static at::Tensor EngramFetch(const at::Tensor &context, const at::Tensor &indices, int64_t hiddenSize, |
| 711 | int64_t numEntries, int64_t dtypeEnum); | 765 | int64_t numEntries, int64_t dtypeEnum); |
| 766 | + using EngramFetchTrainOutput = | ||
| 767 | + std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor>; | ||
| 768 | + static EngramFetchTrainOutput EngramFetchTrain(const at::Tensor &context, const at::Tensor &indices, | ||
| 769 | + int64_t hiddenSize, int64_t numEntries, int64_t dtypeEnum, | ||
| 770 | + const at::Tensor &localStorageAddr, int64_t numMaxTokensPerRank, | ||
| 771 | + int64_t commBufferSize, int64_t rankSize); | ||
| 712 | static at::Tensor EngramFetchWait(const at::Tensor &context, const at::Tensor &fetched); | 772 | static at::Tensor EngramFetchWait(const at::Tensor &context, const at::Tensor &fetched); |
| 713 | 773 | ||
| 774 | + std::tuple<at::Tensor, at::Tensor> EngramFetchGrad( | ||
| 775 | + const at::Tensor &gradFetched, | ||
| 776 | + const at::Tensor &perm, const at::Tensor &sendCounts, | ||
| 777 | + const at::Tensor &recvCounts, const at::Tensor &recvLocalEntry, | ||
| 778 | + const at::Tensor &numRecv); | ||
| 779 | + | ||
| 780 | + bool IsWithGrad() const { return withGrad_; } | ||
| 781 | + | ||
| 714 | static int64_t GetEngramStorageSizeHint(int64_t numEntries, int64_t hiddenSize, | 782 | static int64_t GetEngramStorageSizeHint(int64_t numEntries, int64_t hiddenSize, |
| 715 | at::ScalarType dtype = at::kBFloat16); | 783 | at::ScalarType dtype = at::kBFloat16); |
| 716 | 784 | ||
| @@ -743,13 +811,17 @@ private: | |||
| 743 | 811 | ||
| 744 | std::string groupName_; | 812 | std::string groupName_; |
| 745 | int64_t engramNumCpuBytes_; | 813 | int64_t engramNumCpuBytes_; |
| 814 | + int64_t numMaxTokensPerRank_ = 0; | ||
| 815 | + bool withGrad_ = false; | ||
| 746 | 816 | ||
| 747 | void *engramHostBufPtr_ = nullptr; | 817 | void *engramHostBufPtr_ = nullptr; |
| 748 | void *engramDeviceBufPtr_ = nullptr; | 818 | void *engramDeviceBufPtr_ = nullptr; |
| 749 | HcclMemHandle engramMemHandle_ = nullptr; | 819 | HcclMemHandle engramMemHandle_ = nullptr; |
| 820 | + int64_t commBufferSize_ = 0; // HCCL 默认 buffer 大小(从 HcclGetHcclBufferFunc 查询,训练 a2a 收发缓冲) | ||
| 750 | HcclComm engramHcclComm_ = nullptr; | 821 | HcclComm engramHcclComm_ = nullptr; |
| 751 | EngramCommContext engramCommContext_; | 822 | EngramCommContext engramCommContext_; |
| 752 | - at::Tensor engramContextTensor_; // Cached Engram context tensor | 823 | + at::Tensor engramContextTensor_; // Cached Engram context tensor |
| 824 | + at::Tensor localStorageAddrTensor_; // int64 scalar tensor, stores deviceBufPtr_ address | ||
| 753 | bool engramContextInitialized_ = false; | 825 | bool engramContextInitialized_ = false; |
| 754 | 826 | ||
| 755 | at::Tensor moeContextTensor_; | 827 | at::Tensor moeContextTensor_; |
| @@ -766,8 +838,15 @@ private: | |||
| 766 | }; | 838 | }; |
| 767 | 839 | ||
| 768 | // Constructor | 840 | // Constructor |
| 769 | -ElasticBuffer::ElasticBuffer(const std::string &groupName, int64_t numCpuBytes) | 841 | + |
| 770 | - : groupName_(groupName), engramNumCpuBytes_(numCpuBytes) | 842 | +ElasticBuffer::ElasticBuffer(const std::string &groupName, int64_t numCpuBytes, int64_t numMaxTokensPerRank, |
| 843 | + bool withGrad) | ||
| 844 | + : groupName_(groupName), | ||
| 845 | + engramNumCpuBytes_(numCpuBytes), | ||
| 846 | + destroyed_(false), | ||
| 847 | + engramWriteCalled_(false), | ||
| 848 | + numMaxTokensPerRank_(numMaxTokensPerRank), | ||
| 849 | + withGrad_(withGrad) | ||
| 771 | { | 850 | { |
| 772 | InitHcclEngineCtxFunctions(); | 851 | InitHcclEngineCtxFunctions(); |
| 773 | InitHcclFunctions(); | 852 | InitHcclFunctions(); |
| @@ -792,13 +871,17 @@ void ElasticBuffer::EnsureEngramContext() | |||
| 792 | commStream_ = c10_npu::getNPUStreamFromPool().stream(false); | 871 | commStream_ = c10_npu::getNPUStreamFromPool().stream(false); |
| 793 | TORCH_CHECK(commStream_ != nullptr, "Failed to get NPU stream from pool for comm stream"); | 872 | TORCH_CHECK(commStream_ != nullptr, "Failed to get NPU stream from pool for comm stream"); |
| 794 | EngramContextBuilder builder; | 873 | EngramContextBuilder builder; |
| 795 | - EngramContextResources resources = builder.Build(groupName_, engramNumCpuBytes_); | 874 | + EngramContextResources resources = builder.Build(groupName_, engramNumCpuBytes_, withGrad_); |
| 796 | engramHcclComm_ = resources.hcclComm; | 875 | engramHcclComm_ = resources.hcclComm; |
| 797 | engramMemHandle_ = resources.memHandle; | 876 | engramMemHandle_ = resources.memHandle; |
| 798 | engramHostBufPtr_ = resources.hostBufPtr; | 877 | engramHostBufPtr_ = resources.hostBufPtr; |
| 799 | engramDeviceBufPtr_ = resources.deviceBufPtr; | 878 | engramDeviceBufPtr_ = resources.deviceBufPtr; |
| 800 | engramCommContext_ = resources.context; | 879 | engramCommContext_ = resources.context; |
| 801 | engramContextTensor_ = resources.contextTensor; | 880 | engramContextTensor_ = resources.contextTensor; |
| 881 | + commBufferSize_ = resources.commBufferSize; | ||
| 882 | + int64_t addrValue = reinterpret_cast<int64_t>(engramDeviceBufPtr_); | ||
| 883 | + auto hostAddrTensor = at::full({1}, addrValue, at::TensorOptions().dtype(at::kLong)); | ||
| 884 | + localStorageAddrTensor_ = hostAddrTensor.to(c10::DeviceType::PrivateUse1); | ||
| 802 | engramContextInitialized_ = true; | 885 | engramContextInitialized_ = true; |
| 803 | } | 886 | } |
| 804 | 887 | ||
| @@ -873,6 +956,37 @@ at::Tensor ElasticBuffer::EngramFetch(const at::Tensor &context, const at::Tenso | |||
| 873 | return fetched; | 956 | return fetched; |
| 874 | } | 957 | } |
| 875 | 958 | ||
| 959 | +// EngramFetchTrain - stateless static method for training forward (graph-mode compatible). | ||
| 960 | +// Outputs: fetched + save-for-backward ctx tensors (perm, sendCounts, recvCounts, recvLocalEntry, numRecv). | ||
| 961 | +ElasticBuffer::EngramFetchTrainOutput ElasticBuffer::EngramFetchTrain(const at::Tensor &context, | ||
| 962 | + const at::Tensor &indices, int64_t hiddenSize, | ||
| 963 | + int64_t numEntries, int64_t dtypeEnum, | ||
| 964 | + const at::Tensor &localStorageAddr, | ||
| 965 | + int64_t numMaxTokensPerRank, | ||
| 966 | + int64_t commBufferSize, int64_t rankSize) | ||
| 967 | +{ | ||
| 968 | + auto dtype = static_cast<at::ScalarType>(dtypeEnum); | ||
| 969 | + int64_t numTokens = indices.size(0); | ||
| 970 | + auto fetched = at::empty({numTokens, hiddenSize}, at::TensorOptions().dtype(dtype).device(indices.device())); | ||
| 971 | + auto intOpts = at::TensorOptions().dtype(at::kInt).device(indices.device()); | ||
| 972 | + TORCH_CHECK(rankSize > 0 && numMaxTokensPerRank <= INT64_MAX / rankSize, | ||
| 973 | + "numMaxTokensPerRank * rankSize overflow, got numMaxTokensPerRank=", numMaxTokensPerRank, | ||
| 974 | + ", rankSize=", rankSize); | ||
| 975 | + int64_t maxR = numMaxTokensPerRank * rankSize; | ||
| 976 | + at::Tensor perm = at::empty({numTokens}, intOpts); | ||
| 977 | + at::Tensor sendCounts = at::empty({rankSize * SEND_COUNTS_ALIGN_FACTOR}, intOpts); // 32b对齐 | ||
| 978 | + at::Tensor recvCounts = at::empty({rankSize}, intOpts); | ||
| 979 | + at::Tensor recvLocalEntry = at::empty({maxR}, intOpts); | ||
| 980 | + at::Tensor numRecv = at::empty({1}, intOpts); | ||
| 981 | + | ||
| 982 | + if (numTokens > 0) { | ||
| 983 | + constexpr int64_t withGrad = 1; | ||
| 984 | + ACLNN_CMD(aclnnEngramFetch, context, indices, localStorageAddr, fetched, perm, sendCounts, recvCounts, | ||
| 985 | + recvLocalEntry, numRecv, hiddenSize, numEntries, numMaxTokensPerRank, commBufferSize, withGrad); | ||
| 986 | + } | ||
| 987 | + return std::make_tuple(fetched, perm, sendCounts, recvCounts, recvLocalEntry, numRecv); | ||
| 988 | +} | ||
| 989 | + | ||
| 876 | // EngramFetchWait - stateless static method for torch CustomOp registration. | 990 | // EngramFetchWait - stateless static method for torch CustomOp registration. |
| 877 | at::Tensor ElasticBuffer::EngramFetchWait(const at::Tensor &context, const at::Tensor &fetched) | 991 | at::Tensor ElasticBuffer::EngramFetchWait(const at::Tensor &context, const at::Tensor &fetched) |
| 878 | { | 992 | { |
| @@ -883,6 +997,46 @@ at::Tensor ElasticBuffer::EngramFetchWait(const at::Tensor &context, const at::T | |||
| 883 | return fetched; | 997 | return fetched; |
| 884 | } | 998 | } |
| 885 | 999 | ||
| 1000 | +// EngramFetchGrad - training backward: produce gradUnique, uniqueLocalEntry (sparse index).。 | ||
| 1001 | +std::tuple<at::Tensor, at::Tensor> ElasticBuffer::EngramFetchGrad( | ||
| 1002 | + const at::Tensor &gradFetched, | ||
| 1003 | + const at::Tensor &perm, const at::Tensor &sendCounts, | ||
| 1004 | + const at::Tensor &recvCounts, const at::Tensor &recvLocalEntry, | ||
| 1005 | + const at::Tensor &numRecv) | ||
| 1006 | +{ | ||
| 1007 | + EnsureEngramContext(); | ||
| 1008 | + TORCH_CHECK(!destroyed_, "engram_fetch_grad cannot be called after destroy"); | ||
| 1009 | + TORCH_CHECK(withGrad_, "engram_fetch_grad requires with_grad=True"); | ||
| 1010 | + TORCH_CHECK(engramWriteCalled_, "engram_fetch_grad must be called after at least one engram_write"); | ||
| 1011 | + | ||
| 1012 | + int64_t hidden = gradFetched.size(1); | ||
| 1013 | + uint32_t rankSize = engramCommContext_.rankSize; | ||
| 1014 | + int64_t rankSizeI64 = static_cast<int64_t>(rankSize); | ||
| 1015 | + TORCH_CHECK(rankSizeI64 > 0 && numMaxTokensPerRank_ <= INT64_MAX / rankSizeI64, | ||
| 1016 | + "numMaxTokensPerRank_ * rankSize overflow, got numMaxTokensPerRank_=", numMaxTokensPerRank_, | ||
| 1017 | + ", rankSize=", rankSize); | ||
| 1018 | + int64_t maxR = numMaxTokensPerRank_ * rankSizeI64; | ||
| 1019 | + | ||
| 1020 | + auto gradUnique = at::empty({maxR, hidden}, | ||
| 1021 | + at::TensorOptions().dtype(gradFetched.dtype()).device(gradFetched.device())); | ||
| 1022 | + auto uniqueLocalEntry = at::empty({maxR}, | ||
| 1023 | + at::TensorOptions().dtype(at::kInt).device(gradFetched.device())); | ||
| 1024 | + auto numUnique = at::empty({1}, | ||
| 1025 | + at::TensorOptions().dtype(at::kInt).device(gradFetched.device())); | ||
| 1026 | + | ||
| 1027 | + ACLNN_CMD(aclnnEngramFetchGrad, engramContextTensor_, gradFetched, | ||
| 1028 | + perm, sendCounts, recvCounts, recvLocalEntry, numRecv, | ||
| 1029 | + gradUnique, uniqueLocalEntry, numUnique, | ||
| 1030 | + engramNumEntries_, commBufferSize_); | ||
| 1031 | + | ||
| 1032 | + int64_t actualK = static_cast<int64_t>(numUnique.item<int32_t>()); | ||
| 1033 | + if (actualK < maxR) { | ||
| 1034 | + gradUnique = gradUnique.narrow(0, 0, actualK); | ||
| 1035 | + uniqueLocalEntry = uniqueLocalEntry.narrow(0, 0, actualK); | ||
| 1036 | + } | ||
| 1037 | + return {gradUnique, uniqueLocalEntry}; | ||
| 1038 | +} | ||
| 1039 | + | ||
| 886 | // EngramBarrier - cross-rank synchronization | 1040 | // EngramBarrier - cross-rank synchronization |
| 887 | void ElasticBuffer::EngramBarrier(bool useCommStream, bool withCpuSync) | 1041 | void ElasticBuffer::EngramBarrier(bool useCommStream, bool withCpuSync) |
| 888 | { | 1042 | { |
| @@ -929,6 +1083,9 @@ void ElasticBuffer::Destroy() | |||
| 929 | ASCEND_LOGE("EngramBarrier in Destroy failed: %s", e.what()); | 1083 | ASCEND_LOGE("EngramBarrier in Destroy failed: %s", e.what()); |
| 930 | } | 1084 | } |
| 931 | 1085 | ||
| 1086 | + // HCCL 默认 buffer 由框架管理,无需手动释放 | ||
| 1087 | + commBufferSize_ = 0; | ||
| 1088 | + | ||
| 932 | if (engramHostBufPtr_ != nullptr) { | 1089 | if (engramHostBufPtr_ != nullptr) { |
| 933 | aclError ret = aclrtHostUnregister(engramHostBufPtr_); | 1090 | aclError ret = aclrtHostUnregister(engramHostBufPtr_); |
| 934 | TORCH_CHECK(ret == ACL_SUCCESS, "aclrtHostUnregister failed, ret: ", ret); | 1091 | TORCH_CHECK(ret == ACL_SUCCESS, "aclrtHostUnregister failed, ret: ", ret); |
| @@ -940,6 +1097,7 @@ void ElasticBuffer::Destroy() | |||
| 940 | engramContextInitialized_ = false; | 1097 | engramContextInitialized_ = false; |
| 941 | moeContextInitialized_ = false; | 1098 | moeContextInitialized_ = false; |
| 942 | engramContextTensor_ = at::Tensor(); | 1099 | engramContextTensor_ = at::Tensor(); |
| 1100 | + localStorageAddrTensor_ = at::Tensor(); | ||
| 943 | moeContextTensor_ = at::Tensor(); | 1101 | moeContextTensor_ = at::Tensor(); |
| 944 | 1102 | ||
| 945 | destroyed_ = true; | 1103 | destroyed_ = true; |
| @@ -957,7 +1115,6 @@ int64_t ElasticBuffer::GetEngramStorageSizeHint(int64_t numEntries, int64_t hidd | |||
| 957 | TORCH_CHECK(numBytesPerEntry > 0 && numEntries <= INT64_MAX / numBytesPerEntry, | 1115 | TORCH_CHECK(numBytesPerEntry > 0 && numEntries <= INT64_MAX / numBytesPerEntry, |
| 958 | "numBytesPerEntry * numEntries overflow"); | 1116 | "numBytesPerEntry * numEntries overflow"); |
| 959 | int64_t numCpuBytes = AlignTo(numBytesPerEntry * numEntries, BUFFER_ALIGNMENT); | 1117 | int64_t numCpuBytes = AlignTo(numBytesPerEntry * numEntries, BUFFER_ALIGNMENT); |
| 960 | - | ||
| 961 | return numCpuBytes; | 1118 | return numCpuBytes; |
| 962 | } | 1119 | } |
| 963 | 1120 | ||
| @@ -1141,21 +1298,40 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) | |||
| 1141 | .def("host_ptr", &OpApi::HostPinnedCounter::HostPtr); | 1298 | .def("host_ptr", &OpApi::HostPinnedCounter::HostPtr); |
| 1142 | 1299 | ||
| 1143 | pybind11::class_<Mc2Api::ElasticBuffer>(m, "ElasticBuffer") | 1300 | pybind11::class_<Mc2Api::ElasticBuffer>(m, "ElasticBuffer") |
| 1144 | - .def(pybind11::init<const std::string &, int64_t>(), pybind11::arg("groupName"), pybind11::arg("numCpuBytes")) | 1301 | + .def(pybind11::init<const std::string &, int64_t, int64_t, bool>(), |
| 1302 | + pybind11::arg("groupName"), | ||
| 1303 | + pybind11::arg("numCpuBytes"), | ||
| 1304 | + pybind11::arg("numMaxTokensPerRank") = 0, | ||
| 1305 | + pybind11::arg("withGrad") = false) | ||
| 1145 | .def("engram_write", &Mc2Api::ElasticBuffer::EngramWrite, pybind11::arg("storage").noconvert()) | 1306 | .def("engram_write", &Mc2Api::ElasticBuffer::EngramWrite, pybind11::arg("storage").noconvert()) |
| 1146 | - .def_static("engram_fetch", &Mc2Api::ElasticBuffer::EngramFetch, pybind11::arg("context"), | 1307 | + .def_static("engram_fetch", |
| 1308 | + static_cast<at::Tensor (*)(const at::Tensor &, const at::Tensor &, int64_t, int64_t, int64_t)>( | ||
| 1309 | + &Mc2Api::ElasticBuffer::EngramFetch), | ||
| 1310 | + pybind11::arg("context"), pybind11::arg("indices"), pybind11::arg("hidden_size"), | ||
| 1311 | + pybind11::arg("num_entries"), pybind11::arg("dtype")) | ||
| 1312 | + .def_static("engram_fetch_train", &Mc2Api::ElasticBuffer::EngramFetchTrain, pybind11::arg("context"), | ||
| 1147 | pybind11::arg("indices"), pybind11::arg("hidden_size"), pybind11::arg("num_entries"), | 1313 | pybind11::arg("indices"), pybind11::arg("hidden_size"), pybind11::arg("num_entries"), |
| 1148 | - pybind11::arg("dtype")) | 1314 | + pybind11::arg("dtype"), pybind11::arg("local_storage_addr"), |
| 1315 | + pybind11::arg("num_max_tokens_per_rank"), pybind11::arg("comm_buffer_size"), | ||
| 1316 | + pybind11::arg("rank_size")) | ||
| 1149 | .def_static("engram_fetch_wait", &Mc2Api::ElasticBuffer::EngramFetchWait, pybind11::arg("context"), | 1317 | .def_static("engram_fetch_wait", &Mc2Api::ElasticBuffer::EngramFetchWait, pybind11::arg("context"), |
| 1150 | pybind11::arg("fetched")) | 1318 | pybind11::arg("fetched")) |
| 1319 | + .def("engram_fetch_grad", &Mc2Api::ElasticBuffer::EngramFetchGrad, pybind11::arg("gradFetched").noconvert(), | ||
| 1320 | + pybind11::arg("perm").noconvert(), pybind11::arg("sendCounts").noconvert(), | ||
| 1321 | + pybind11::arg("recvCounts").noconvert(), pybind11::arg("recvLocalEntry").noconvert(), | ||
| 1322 | + pybind11::arg("numRecv").noconvert()) | ||
| 1151 | .def("engram_barrier", &Mc2Api::ElasticBuffer::EngramBarrier, pybind11::arg("useCommStream") = true, | 1323 | .def("engram_barrier", &Mc2Api::ElasticBuffer::EngramBarrier, pybind11::arg("useCommStream") = true, |
| 1152 | pybind11::arg("withCpuSync") = false) | 1324 | pybind11::arg("withCpuSync") = false) |
| 1153 | .def("destroy", &Mc2Api::ElasticBuffer::Destroy) | 1325 | .def("destroy", &Mc2Api::ElasticBuffer::Destroy) |
| 1154 | .def("get_host_buf_ptr", &Mc2Api::ElasticBuffer::GetHostBufPtr) | 1326 | .def("get_host_buf_ptr", &Mc2Api::ElasticBuffer::GetHostBufPtr) |
| 1155 | .def("get_context_tensor", &Mc2Api::ElasticBuffer::GetContextTensor) | 1327 | .def("get_context_tensor", &Mc2Api::ElasticBuffer::GetContextTensor) |
| 1328 | + .def("get_local_storage_addr", &Mc2Api::ElasticBuffer::GetLocalStorageAddrTensor) | ||
| 1329 | + .def("get_comm_buffer_size", &Mc2Api::ElasticBuffer::GetCommBufferSize) | ||
| 1330 | + .def("get_rank_size", &Mc2Api::ElasticBuffer::GetRankSize) | ||
| 1156 | .def("moe_ep_dispatch", &Mc2Api::ElasticBuffer::MoeEpDispatch) | 1331 | .def("moe_ep_dispatch", &Mc2Api::ElasticBuffer::MoeEpDispatch) |
| 1157 | .def("moe_ep_dispatch_epilogue", &Mc2Api::ElasticBuffer::MoeEpDispatchEpilogue) | 1332 | .def("moe_ep_dispatch_epilogue", &Mc2Api::ElasticBuffer::MoeEpDispatchEpilogue) |
| 1158 | .def("moe_ep_combine", &Mc2Api::ElasticBuffer::MoeEpCombine) | 1333 | .def("moe_ep_combine", &Mc2Api::ElasticBuffer::MoeEpCombine) |
| 1159 | .def_static("get_engram_storage_size_hint", &Mc2Api::ElasticBuffer::GetEngramStorageSizeHint, | 1334 | .def_static("get_engram_storage_size_hint", &Mc2Api::ElasticBuffer::GetEngramStorageSizeHint, |
| 1160 | - pybind11::arg("numEntries"), pybind11::arg("hiddenSize"), pybind11::arg("dtype") = at::kBFloat16); | 1335 | + pybind11::arg("numEntries"), pybind11::arg("hiddenSize"), |
| 1336 | + pybind11::arg("dtype") = at::kBFloat16); | ||
| 1161 | } | 1337 | } |
| @@ -14,6 +14,7 @@ from typing import Callable, Optional, Tuple, Union | |||
| 14 | import torch | 14 | import torch |
| 15 | import torch.distributed as dist | 15 | import torch.distributed as dist |
| 16 | from torch.library import impl | 16 | from torch.library import impl |
| 17 | +from torch import _check as _torch_check | ||
| 17 | 18 | ||
| 18 | from cann_ops_transformer.op_builder.builder import OpBuilder | 19 | from cann_ops_transformer.op_builder.builder import OpBuilder |
| 19 | from cann_ops_transformer.op_builder.builder import AS_LIBRARY | 20 | from cann_ops_transformer.op_builder.builder import AS_LIBRARY |
| @@ -27,6 +28,28 @@ _ENGRAM_DTYPE_TO_INT = { | |||
| 27 | _ENGRAM_INT_TO_DTYPE = {v: k for k, v in _ENGRAM_DTYPE_TO_INT.items()} | 28 | _ENGRAM_INT_TO_DTYPE = {v: k for k, v in _ENGRAM_DTYPE_TO_INT.items()} |
| 28 | 29 | ||
| 29 | 30 | ||
| 31 | +@dataclass | ||
| 32 | +class EngramFetchCtx: | ||
| 33 | + """save-for-backward context for engram_fetch_grad. | ||
| 34 | + | ||
| 35 | + Attributes: | ||
| 36 | + perm: (T,) int32 — bucket permutation index; backward step 1 reorders grad by this. | ||
| 37 | + send_counts: (W*8,) int32 — number of indices sent to each rank (padded to 32b alignment); | ||
| 38 | + only the first W elements are valid, used as a2a send counts in backward. | ||
| 39 | + recv_counts: (W,) int32 — number of indices received from each rank; | ||
| 40 | + used as a2a recv counts in backward. | ||
| 41 | + recv_local_entry: (R_max,) int32 — received local entries; | ||
| 42 | + backward step 3 scatter-add aggregates by this. | ||
| 43 | + num_recv: (1,) int32 — actual number of received rows R (first num_recv are valid). | ||
| 44 | + """ | ||
| 45 | + | ||
| 46 | + perm: torch.Tensor | ||
| 47 | + send_counts: torch.Tensor | ||
| 48 | + recv_counts: torch.Tensor | ||
| 49 | + recv_local_entry: torch.Tensor | ||
| 50 | + num_recv: torch.Tensor | ||
| 51 | + | ||
| 52 | + | ||
| 30 | class ElasticBufferOpBuilder(OpBuilder): | 53 | class ElasticBufferOpBuilder(OpBuilder): |
| 31 | """OpBuilder for ElasticBuffer operations""" | 54 | """OpBuilder for ElasticBuffer operations""" |
| 32 | 55 | ||
| @@ -42,6 +65,10 @@ class ElasticBufferOpBuilder(OpBuilder): | |||
| 42 | return [ | 65 | return [ |
| 43 | "engram_fetch(Tensor context, Tensor indices, int hidden_size, " | 66 | "engram_fetch(Tensor context, Tensor indices, int hidden_size, " |
| 44 | "int num_entries, int dtype) -> Tensor", | 67 | "int num_entries, int dtype) -> Tensor", |
| 68 | + "engram_fetch_train(Tensor context, Tensor indices, int hidden_size, " | ||
| 69 | + "int num_entries, int dtype, Tensor local_storage_addr, " | ||
| 70 | + "int num_max_tokens_per_rank, int comm_buffer_size, int rank_size) " | ||
| 71 | + "-> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)", | ||
| 45 | "engram_fetch_wait(Tensor context, Tensor fetched) -> Tensor", | 72 | "engram_fetch_wait(Tensor context, Tensor fetched) -> Tensor", |
| 46 | ] | 73 | ] |
| 47 | 74 | ||
| @@ -56,6 +83,42 @@ class ElasticBufferOpBuilder(OpBuilder): | |||
| 56 | device="meta", | 83 | device="meta", |
| 57 | ) | 84 | ) |
| 58 | 85 | ||
| 86 | + @impl(AS_LIBRARY, "engram_fetch_train", "Meta") | ||
| 87 | + def engram_fetch_train_meta(*args): | ||
| 88 | + ( | ||
| 89 | + _context, | ||
| 90 | + indices, | ||
| 91 | + hidden_size, | ||
| 92 | + _num_entries, | ||
| 93 | + dtype, | ||
| 94 | + _local_storage_addr, | ||
| 95 | + num_max_tokens_per_rank, | ||
| 96 | + _comm_buffer_size, | ||
| 97 | + rank_size, | ||
| 98 | + ) = args | ||
| 99 | + num_tokens = indices.size(0) | ||
| 100 | + max_r = num_max_tokens_per_rank * rank_size | ||
| 101 | + data_dtype = _ENGRAM_INT_TO_DTYPE[dtype] | ||
| 102 | + fetched = torch.empty( | ||
| 103 | + (num_tokens, hidden_size), dtype=data_dtype, device="meta" | ||
| 104 | + ) | ||
| 105 | + perm = torch.empty((num_tokens,), dtype=torch.int32, device="meta") | ||
| 106 | + send_counts = torch.empty( | ||
| 107 | + (rank_size * 8,), dtype=torch.int32, device="meta" | ||
| 108 | + ) | ||
| 109 | + recv_counts = torch.empty((rank_size,), dtype=torch.int32, device="meta") | ||
| 110 | + recv_local_entry = torch.empty((max_r,), dtype=torch.int32, device="meta") | ||
| 111 | + num_recv = torch.empty((1,), dtype=torch.int32, device="meta") | ||
| 112 | + fetch_result = ( | ||
| 113 | + fetched, | ||
| 114 | + perm, | ||
| 115 | + send_counts, | ||
| 116 | + recv_counts, | ||
| 117 | + recv_local_entry, | ||
| 118 | + num_recv, | ||
| 119 | + ) | ||
| 120 | + return fetch_result | ||
| 121 | + | ||
| 59 | @impl(AS_LIBRARY, "engram_fetch_wait", "Meta") | 122 | @impl(AS_LIBRARY, "engram_fetch_wait", "Meta") |
| 60 | def engram_fetch_wait_meta(context, fetched): | 123 | def engram_fetch_wait_meta(context, fetched): |
| 61 | return torch.empty_like(fetched, device="meta") | 124 | return torch.empty_like(fetched, device="meta") |
| @@ -90,6 +153,12 @@ def engram_fetch(context, indices, hidden_size, num_entries, dtype): | |||
| 90 | ) | 153 | ) |
| 91 | 154 | ||
| 92 | 155 | ||
| 156 | +@impl(AS_LIBRARY, "engram_fetch_train", "PrivateUse1") | ||
| 157 | +def engram_fetch_train(*args): | ||
| 158 | + op_module = _elastic_buffer_op_builder.load() | ||
| 159 | + return op_module.ElasticBuffer.engram_fetch_train(*args) | ||
| 160 | + | ||
| 161 | + | ||
| 93 | @impl(AS_LIBRARY, "engram_fetch_wait", "PrivateUse1") | 162 | @impl(AS_LIBRARY, "engram_fetch_wait", "PrivateUse1") |
| 94 | def engram_fetch_wait(context, fetched): | 163 | def engram_fetch_wait(context, fetched): |
| 95 | op_module = _elastic_buffer_op_builder.load() | 164 | op_module = _elastic_buffer_op_builder.load() |
| @@ -181,6 +250,7 @@ class ElasticBuffer: | |||
| 181 | num_max_tokens_per_rank: Optional[int] = None, | 250 | num_max_tokens_per_rank: Optional[int] = None, |
| 182 | hidden: Optional[int] = None, | 251 | hidden: Optional[int] = None, |
| 183 | num_topk: Optional[int] = None, | 252 | num_topk: Optional[int] = None, |
| 253 | + with_grad: bool = False, | ||
| 184 | ): | 254 | ): |
| 185 | """ | 255 | """ |
| 186 | Initialize the ElasticBuffer. | 256 | Initialize the ElasticBuffer. |
| @@ -192,31 +262,12 @@ class ElasticBuffer: | |||
| 192 | hidden: hidden dimension for MoE dispatch/combine. | 262 | hidden: hidden dimension for MoE dispatch/combine. |
| 193 | num_topk: top-k value for MoE dispatch/combine. | 263 | num_topk: top-k value for MoE dispatch/combine. |
| 194 | """ | 264 | """ |
| 195 | - buffer_alignment = 2 * 1024 * 1024 | ||
| 196 | - torch._check((group is not None), lambda: ("group must not be None.")) | ||
| 197 | - torch._check( | ||
| 198 | - (num_cpu_bytes >= 0 and num_cpu_bytes % buffer_alignment == 0), | ||
| 199 | - lambda: ( | ||
| 200 | - f"num_cpu_bytes must be non-negative and 2MB-aligned, got {num_cpu_bytes=}, " | ||
| 201 | - f"which is not divisible by {buffer_alignment=}." | ||
| 202 | - ), | ||
| 203 | - ) | ||
| 204 | moe_args = (num_max_tokens_per_rank, hidden, num_topk) | 265 | moe_args = (num_max_tokens_per_rank, hidden, num_topk) |
| 205 | - moe_arg_names = ("num_max_tokens_per_rank", "hidden", "num_topk") | 266 | + self._validate_init_args(group, num_cpu_bytes, moe_args, with_grad) |
| 206 | - missing_args = [ | ||
| 207 | - name for name, val in zip(moe_arg_names, moe_args) if val is None | ||
| 208 | - ] | ||
| 209 | - torch._check( | ||
| 210 | - len(missing_args) == 0 or len(missing_args) == len(moe_args), | ||
| 211 | - lambda: ( | ||
| 212 | - "num_max_tokens_per_rank, hidden and num_topk " | ||
| 213 | - "must be specified together for MoE dispatch/combine, " | ||
| 214 | - f"missing: {', '.join(missing_args)}." | ||
| 215 | - ), | ||
| 216 | - ) | ||
| 217 | 267 | ||
| 218 | self._group = group | 268 | self._group = group |
| 219 | self._num_cpu_bytes = num_cpu_bytes | 269 | self._num_cpu_bytes = num_cpu_bytes |
| 270 | + self._with_grad = with_grad | ||
| 220 | self._rank_id = dist.get_rank(self._group) | 271 | self._rank_id = dist.get_rank(self._group) |
| 221 | self._ep_world_size = dist.get_world_size(self._group) | 272 | self._ep_world_size = dist.get_world_size(self._group) |
| 222 | 273 | ||
| @@ -230,7 +281,10 @@ class ElasticBuffer: | |||
| 230 | ) | 281 | ) |
| 231 | _elastic_buffer_ops = _elastic_buffer_op_builder.load() | 282 | _elastic_buffer_ops = _elastic_buffer_op_builder.load() |
| 232 | self._runtime = _elastic_buffer_ops.ElasticBuffer( | 283 | self._runtime = _elastic_buffer_ops.ElasticBuffer( |
| 233 | - self._group_name, self._num_cpu_bytes | 284 | + self._group_name, |
| 285 | + self._num_cpu_bytes, | ||
| 286 | + num_max_tokens_per_rank if num_max_tokens_per_rank is not None else 0, | ||
| 287 | + self._with_grad, | ||
| 234 | ) | 288 | ) |
| 235 | 289 | ||
| 236 | self._num_max_tokens_per_rank = num_max_tokens_per_rank | 290 | self._num_max_tokens_per_rank = num_max_tokens_per_rank |
| @@ -242,6 +296,9 @@ class ElasticBuffer: | |||
| 242 | self._engram_num_entries = None | 296 | self._engram_num_entries = None |
| 243 | self._engram_dtype_int = None | 297 | self._engram_dtype_int = None |
| 244 | self._engram_fetch_in_progress = False | 298 | self._engram_fetch_in_progress = False |
| 299 | + self._local_storage_addr = None | ||
| 300 | + self._comm_buffer_size = 0 | ||
| 301 | + self._rank_size = 0 | ||
| 245 | 302 | ||
| 246 | @staticmethod | 303 | @staticmethod |
| 247 | def get_engram_storage_size_hint( | 304 | def get_engram_storage_size_hint( |
| @@ -313,6 +370,42 @@ class ElasticBuffer: | |||
| 313 | // 2 | 370 | // 2 |
| 314 | ) | 371 | ) |
| 315 | 372 | ||
| 373 | + @staticmethod | ||
| 374 | + def _validate_init_args(group, num_cpu_bytes, moe_args, with_grad): | ||
| 375 | + buffer_alignment = 2 * 1024 * 1024 | ||
| 376 | + _torch_check((group is not None), lambda: ("group must not be None.")) | ||
| 377 | + _torch_check( | ||
| 378 | + (num_cpu_bytes >= 0 and num_cpu_bytes % buffer_alignment == 0), | ||
| 379 | + lambda: ( | ||
| 380 | + f"num_cpu_bytes must be non-negative and 2MB-aligned, got {num_cpu_bytes=}, " | ||
| 381 | + f"which is not divisible by {buffer_alignment=}." | ||
| 382 | + ), | ||
| 383 | + ) | ||
| 384 | + if with_grad: | ||
| 385 | + num_max_tokens_per_rank = moe_args[0] | ||
| 386 | + _torch_check( | ||
| 387 | + isinstance(num_max_tokens_per_rank, int) | ||
| 388 | + and not isinstance(num_max_tokens_per_rank, bool) | ||
| 389 | + and num_max_tokens_per_rank > 0, | ||
| 390 | + lambda: ( | ||
| 391 | + "num_max_tokens_per_rank must be a positive int when with_grad=True, " | ||
| 392 | + f"got {num_max_tokens_per_rank}." | ||
| 393 | + ), | ||
| 394 | + ) | ||
| 395 | + else: | ||
| 396 | + moe_arg_names = ("num_max_tokens_per_rank", "hidden", "num_topk") | ||
| 397 | + missing_args = [ | ||
| 398 | + name for name, val in zip(moe_arg_names, moe_args) if val is None | ||
| 399 | + ] | ||
| 400 | + _torch_check( | ||
| 401 | + len(missing_args) == 0 or len(missing_args) == len(moe_args), | ||
| 402 | + lambda: ( | ||
| 403 | + "num_max_tokens_per_rank, hidden and num_topk " | ||
| 404 | + "must be specified together for MoE dispatch/combine, " | ||
| 405 | + f"missing: {', '.join(missing_args)}." | ||
| 406 | + ), | ||
| 407 | + ) | ||
| 408 | + | ||
| 316 | def engram_write(self, storage: torch.Tensor) -> None: | 409 | def engram_write(self, storage: torch.Tensor) -> None: |
| 317 | """ | 410 | """ |
| 318 | Write data to the host pinned memory of ElasticBuffer. | 411 | Write data to the host pinned memory of ElasticBuffer. |
| @@ -351,8 +444,11 @@ class ElasticBuffer: | |||
| 351 | self._engram_hidden_size = storage.size(1) | 444 | self._engram_hidden_size = storage.size(1) |
| 352 | self._engram_num_entries = storage.size(0) | 445 | self._engram_num_entries = storage.size(0) |
| 353 | self._engram_dtype_int = _ENGRAM_DTYPE_TO_INT[storage.dtype] | 446 | self._engram_dtype_int = _ENGRAM_DTYPE_TO_INT[storage.dtype] |
| 447 | + self._local_storage_addr = self._runtime.get_local_storage_addr() | ||
| 448 | + self._comm_buffer_size = self._runtime.get_comm_buffer_size() | ||
| 449 | + self._rank_size = self._runtime.get_rank_size() | ||
| 354 | 450 | ||
| 355 | - def engram_fetch(self, indices: torch.Tensor) -> Callable[[], torch.Tensor]: | 451 | + def engram_fetch(self, indices: torch.Tensor) -> Callable: |
| 356 | """ | 452 | """ |
| 357 | Fetch Engram data from remote ranks via RDMA. | 453 | Fetch Engram data from remote ranks via RDMA. |
| 358 | 454 | ||
| @@ -361,35 +457,48 @@ class ElasticBuffer: | |||
| 361 | 457 | ||
| 362 | Returns: | 458 | Returns: |
| 363 | wait_callable: a callable that returns the fetched tensor when invoked. | 459 | wait_callable: a callable that returns the fetched tensor when invoked. |
| 460 | + In training mode (with_grad=True), the callable returns a tuple of | ||
| 461 | + (fetched_tensor, EngramFetchCtx) for save-for-backward. | ||
| 364 | """ | 462 | """ |
| 365 | - if indices.device.type != torch.device("npu").type: | 463 | + self._check_engram_fetch_ready(indices) |
| 366 | - raise RuntimeError(f"indices must be on NPU, got device: {indices.device}") | ||
| 367 | - if indices.dim() != 1: | ||
| 368 | - raise RuntimeError(f"indices must be 1D, got dimensions: {indices.dim()}") | ||
| 369 | - if indices.dtype != torch.int32: | ||
| 370 | - raise RuntimeError(f"indices dtype must be int32, got: {indices.dtype}") | ||
| 371 | - if self._runtime is None: | ||
| 372 | - raise RuntimeError( | ||
| 373 | - "engram_fetch cannot be called after destroy, please create a new ElasticBuffer instance" | ||
| 374 | - ) | ||
| 375 | - if self._engram_context_tensor is None: | ||
| 376 | - raise RuntimeError( | ||
| 377 | - "engram_fetch must be called after at least one engram_write" | ||
| 378 | - ) | ||
| 379 | - if self._engram_fetch_in_progress: | ||
| 380 | - raise RuntimeError( | ||
| 381 | - "Cannot call engram_fetch while previous fetch callback is pending, " | ||
| 382 | - "please invoke the callback function returned by the previous engram_fetch first" | ||
| 383 | - ) | ||
| 384 | self._engram_fetch_in_progress = True | 464 | self._engram_fetch_in_progress = True |
| 465 | + context = self._engram_context_tensor | ||
| 466 | + | ||
| 467 | + if self._with_grad: | ||
| 468 | + fetched, perm, send_counts, recv_counts, recv_local_entry, num_recv = ( | ||
| 469 | + torch.ops.cann_ops_transformer.engram_fetch_train( | ||
| 470 | + context, | ||
| 471 | + indices, | ||
| 472 | + self._engram_hidden_size, | ||
| 473 | + self._engram_num_entries, | ||
| 474 | + self._engram_dtype_int, | ||
| 475 | + self._local_storage_addr, | ||
| 476 | + self._num_max_tokens_per_rank, | ||
| 477 | + self._comm_buffer_size, | ||
| 478 | + self._rank_size, | ||
| 479 | + ) | ||
| 480 | + ) | ||
| 481 | + ctx = EngramFetchCtx( | ||
| 482 | + perm=perm, | ||
| 483 | + send_counts=send_counts, | ||
| 484 | + recv_counts=recv_counts, | ||
| 485 | + recv_local_entry=recv_local_entry, | ||
| 486 | + num_recv=num_recv, | ||
| 487 | + ) | ||
| 488 | + | ||
| 489 | + def _wait_train(): | ||
| 490 | + self._engram_fetch_in_progress = False | ||
| 491 | + return fetched, ctx | ||
| 492 | + | ||
| 493 | + return _wait_train | ||
| 494 | + | ||
| 385 | fetched = torch.ops.cann_ops_transformer.engram_fetch( | 495 | fetched = torch.ops.cann_ops_transformer.engram_fetch( |
| 386 | - self._engram_context_tensor, | 496 | + context, |
| 387 | indices, | 497 | indices, |
| 388 | self._engram_hidden_size, | 498 | self._engram_hidden_size, |
| 389 | self._engram_num_entries, | 499 | self._engram_num_entries, |
| 390 | self._engram_dtype_int, | 500 | self._engram_dtype_int, |
| 391 | ) | 501 | ) |
| 392 | - context = self._engram_context_tensor | ||
| 393 | 502 | ||
| 394 | def _wait(): | 503 | def _wait(): |
| 395 | result = torch.ops.cann_ops_transformer.engram_fetch_wait(context, fetched) | 504 | result = torch.ops.cann_ops_transformer.engram_fetch_wait(context, fetched) |
| @@ -412,6 +521,34 @@ class ElasticBuffer: | |||
| 412 | """ | 521 | """ |
| 413 | self._runtime.engram_barrier(use_comm_stream, with_cpu_sync) | 522 | self._runtime.engram_barrier(use_comm_stream, with_cpu_sync) |
| 414 | 523 | ||
| 524 | + def engram_fetch_grad( | ||
| 525 | + self, grad_fetched: torch.Tensor, fetch_ctx: EngramFetchCtx | ||
| 526 | + ) -> Tuple[torch.Tensor, torch.Tensor]: | ||
| 527 | + """ | ||
| 528 | + Backward: launch fused kernel aclnnEngramFetchGrad. | ||
| 529 | + | ||
| 530 | + Returns: | ||
| 531 | + (grad_unique, unique_local_entry): | ||
| 532 | + grad_unique (K, H) grad_fetched.type | ||
| 533 | + unique_local_entry (K,) int32 — 1D sparse index。 | ||
| 534 | + """ | ||
| 535 | + _torch_check( | ||
| 536 | + grad_fetched.device.type == torch.device("npu").type, | ||
| 537 | + lambda: f"grad_fetched must be on NPU, got device: {grad_fetched.device}", | ||
| 538 | + ) | ||
| 539 | + _torch_check( | ||
| 540 | + grad_fetched.dim() == 2, | ||
| 541 | + lambda: f"grad_fetched must be 2D, got dimensions: {grad_fetched.dim()}", | ||
| 542 | + ) | ||
| 543 | + return self._runtime.engram_fetch_grad( | ||
| 544 | + grad_fetched, | ||
| 545 | + fetch_ctx.perm, | ||
| 546 | + fetch_ctx.send_counts, | ||
| 547 | + fetch_ctx.recv_counts, | ||
| 548 | + fetch_ctx.recv_local_entry, | ||
| 549 | + fetch_ctx.num_recv, | ||
| 550 | + ) | ||
| 551 | + | ||
| 415 | def dispatch( | 552 | def dispatch( |
| 416 | self, | 553 | self, |
| 417 | x: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]], | 554 | x: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]], |
| @@ -594,6 +731,30 @@ class ElasticBuffer: | |||
| 594 | self._engram_num_entries = None | 731 | self._engram_num_entries = None |
| 595 | self._engram_dtype_int = None | 732 | self._engram_dtype_int = None |
| 596 | self._engram_fetch_in_progress = False | 733 | self._engram_fetch_in_progress = False |
| 734 | + self._local_storage_addr = None | ||
| 735 | + self._comm_buffer_size = 0 | ||
| 736 | + self._rank_size = 0 | ||
| 737 | + | ||
| 738 | + def _check_engram_fetch_ready(self, indices: torch.Tensor) -> None: | ||
| 739 | + if indices.device.type != torch.device("npu").type: | ||
| 740 | + raise RuntimeError(f"indices must be on NPU, got device: {indices.device}") | ||
| 741 | + if indices.dim() != 1: | ||
| 742 | + raise RuntimeError(f"indices must be 1D, got dimensions: {indices.dim()}") | ||
| 743 | + if indices.dtype != torch.int32: | ||
| 744 | + raise RuntimeError(f"indices dtype must be int32, got: {indices.dtype}") | ||
| 745 | + if self._runtime is None: | ||
| 746 | + raise RuntimeError( | ||
| 747 | + "engram_fetch cannot be called after destroy, please create a new ElasticBuffer instance" | ||
| 748 | + ) | ||
| 749 | + if self._engram_context_tensor is None: | ||
| 750 | + raise RuntimeError( | ||
| 751 | + "engram_fetch must be called after at least one engram_write" | ||
| 752 | + ) | ||
| 753 | + if self._engram_fetch_in_progress: | ||
| 754 | + raise RuntimeError( | ||
| 755 | + "Cannot call engram_fetch while previous fetch callback is pending, " | ||
| 756 | + "please invoke the callback function returned by the previous engram_fetch first" | ||
| 757 | + ) | ||
| 597 | 758 | ||
| 598 | def _ensure_moe_config(self): | 759 | def _ensure_moe_config(self): |
| 599 | moe_args = (self._num_max_tokens_per_rank, self._hidden, self._num_topk) | 760 | moe_args = (self._num_max_tokens_per_rank, self._hidden, self._num_topk) |