Merged
feat: 支持配置每批最大传输数量及队列深度 #1105
贾昭阳Add on Sep 15
feat: 支持配置每批最大传输数量及队列深度 #1105
Merged
贾昭阳Add on Sep 15
Total: 43 files changed+662-81
@@ -68,7 +68,7 @@ graph LR
68 68 
69Note: HDK 25.5 does not support the `aclrtMemRetainAllocationHandle` API. You must use ADXL-provided `MallocMem` and `FreeMem` APIs to manage host memory. HDK 26.0 or later allows direct calls to ACL APIs for host memory management.69Note: HDK 25.5 does not support the `aclrtMemRetainAllocationHandle` API. You must use ADXL-provided `MallocMem` and `FreeMem` APIs to manage host memory. HDK 26.0 or later allows direct calls to ACL APIs for host memory management.
70- **Enabling method**: During engine initialization, configure `OPTION_ENABLE_USE_FABRIC_MEM` in `options`. The value `"1"` enables FabricMem while `"0"` disables it. See [HIXL Interface · options](../zh/api/cpp/HIXL-interface.md).70- **Enabling method**: During engine initialization, configure `OPTION_ENABLE_USE_FABRIC_MEM` in `options`. The value `"1"` enables FabricMem while `"0"` disables it. See [HIXL Interface · options](../zh/api/cpp/HIXL-interface.md).
71-- **Optional global configuration**: Use `OPTION_GLOBAL_RESOURCE_CONFIG` to configure the capacity, start address, and per-task stream counts of the Fabric virtual memory pool. See the `fabric_memory.*` field in [HIXL Interface](../zh/api/cpp/HIXL-interface.md).71+- **Optional global configuration**: Use `OPTION_GLOBAL_RESOURCE_CONFIG` to configure the capacity, start address, and per-task stream counts of the Fabric virtual memory pool, as well as `transfer_config.max_transfer_count_per_batch`. This transfer configuration defaults to `1920`, and its valid range for FabricMem is `[1, 1920]`; the range is validated in both unfolding modes. When `fabric_memory.enable_aicpu_unfold=true`, the value controls the logical batches and Notify boundaries for AICPU unfolding. A Kernel never crosses a logical batch boundary, and the STARS queue depth remains fixed at 2K. When `fabric_memory.enable_aicpu_unfold=false`, the Host continuously submits one `aclrtMemcpyAsync` operation for each buffer, without batching by this value or adding synchronization at its boundaries. See [HIXL Interface](../zh/api/cpp/HIXL-interface.md).
72 72 
73**Hardware scope**: Only **Atlas A3 training products** and **Atlas A3 inference products** are supported.73**Hardware scope**: Only **Atlas A3 training products** and **Atlas A3 inference products** are supported.
74 74 
@@ -313,7 +313,7 @@ sequenceDiagram
313 313 
314**Checkpoint list**:314**Checkpoint list**:
3151. **Engine routing check**: `OPTION_ENABLE_USE_FABRIC_MEM=1` must be `FabricMemEngine` created by `EngineFactory`.3151. **Engine routing check**: `OPTION_ENABLE_USE_FABRIC_MEM=1` must be `FabricMemEngine` created by `EngineFactory`.
316-2. **Configuration validity check**: `FabricMemConfig` parses `EnableUseFabricMem`, `GlobalResourceConfig`, stream count, virtual address capacity and start address.316+2. **Configuration validity check**: `FabricMemConfig` parses `EnableUseFabricMem`, `GlobalResourceConfig`, stream count, virtual address capacity, start address, and the maximum transfer count per batch. `transfer_config.max_transfer_count_per_batch` ranges from `1` to `1920` and defaults to `1920`; this range is validated in both unfolding modes. When `enable_aicpu_unfold=true`, it controls the logical batches and Notify boundaries for AICPU unfolding without changing the fixed 2K STARS queue depth. When `enable_aicpu_unfold=false`, the Host submits each `aclrtMemcpyAsync` operation individually, without batching by this value or adding synchronization at its boundaries.
3173. **Memory type check**: In FabricMem mode, HOST memory registration requires additional local import and mapping processing.3173. **Memory type check**: In FabricMem mode, HOST memory registration requires additional local import and mapping processing.
3184. **Transfer parameter check**: Validates address range in transfer description is within locally registered or remotely imported memory range.3184. **Transfer parameter check**: Validates address range in transfer description is within locally registered or remotely imported memory range.
3195. **Stream resource management check**: Ensures stream resources in stream pool correctly allocated and released, avoiding resource leak.3195. **Stream resource management check**: Ensures stream resources in stream pool correctly allocated and released, avoiding resource leak.
@@ -329,4 +329,4 @@ sequenceDiagram
329 329 
330**Compatibility considerations**:330**Compatibility considerations**:
3311. **Backward compatibility**: FabricMem mode not enabled by default, maintains compatibility with traditional ADXL/HCCL paths.3311. **Backward compatibility**: FabricMem mode not enabled by default, maintains compatibility with traditional ADXL/HCCL paths.
332-2. **Statistics attribution**: FabricMem transfer statistics maintained by `FabricMemStatistic`, ADXL side `StatisticManager` only maintains ADXL/HCCL path connection and transfer statistics.332+2. **Statistics attribution**: FabricMem transfer statistics maintained by `FabricMemStatistic`, ADXL side `StatisticManager` only maintains ADXL/HCCL path connection and transfer statistics.
@@ -68,7 +68,7 @@ graph LR
68 68 
69特殊说明:25.5 HDK下不支持aclrtMemRetainAllocationHandle接口,必须使用adxl提供的MallocMem接口和FreeMem接口来管理HOST内存,26.0以上HDK可以直接调用acl接口管理HOST内存。69特殊说明:25.5 HDK下不支持aclrtMemRetainAllocationHandle接口,必须使用adxl提供的MallocMem接口和FreeMem接口来管理HOST内存,26.0以上HDK可以直接调用acl接口管理HOST内存。
70- **启用方式**:初始化引擎时在 `options` 中配置 `OPTION_ENABLE_USE_FABRIC_MEM`,取值为 `"1"` 表示开启(取值为 `"0"` 表示关闭)。详见 [HIXL 接口 · options](api/cpp/HIXL-interface.md)。70- **启用方式**:初始化引擎时在 `options` 中配置 `OPTION_ENABLE_USE_FABRIC_MEM`,取值为 `"1"` 表示开启(取值为 `"0"` 表示关闭)。详见 [HIXL 接口 · options](api/cpp/HIXL-interface.md)。
71-- **可选全局配置**:可通过 `OPTION_GLOBAL_RESOURCE_CONFIG` 配置 Fabric 虚拟内存池容量、起始地址、单任务流数量等,示例见 [HIXL 接口](api/cpp/HIXL-interface.md) 中 `fabric_memory.`* 字段说明。71+- **可选全局配置**:可通过 `OPTION_GLOBAL_RESOURCE_CONFIG` 配置 Fabric 虚拟内存池容量、起始地址、单任务流数量,以及 `transfer_config.max_transfer_count_per_batch`。该传输配置默认值为 `1920`,FabricMem取值范围为`[1, 1920]`,两种展开模式都会执行该范围校验。`fabric_memory.enable_aicpu_unfold=true`时,配置值控制AICPU展开的逻辑批次和Notify边界,Kernel不会跨逻辑批次,STARS队列深度仍固定为2K。`fabric_memory.enable_aicpu_unfold=false`时,Host为每个buffer连续提交`aclrtMemcpyAsync`,不按该值分批,也不会在该值边界增加同步。示例见 [HIXL 接口](api/cpp/HIXL-interface.md)。
72 72 
73**硬件范围**:仅支持 **Atlas A3 训练系列产品**、**Atlas A3 推理系列产品**。73**硬件范围**:仅支持 **Atlas A3 训练系列产品**、**Atlas A3 推理系列产品**。
74 74 
@@ -140,7 +140,8 @@ OPTION_GLOBAL_RESOURCE_CONFIG的配置示例和使用约束如下:
140 "fabric_memory.max_capacity": "128", //虚拟内存池的大小。取值范围:(0, 1024]之间的整数,默认值:32,单位TB,实际可用范围由底层决定140 "fabric_memory.max_capacity": "128", //虚拟内存池的大小。取值范围:(0, 1024]之间的整数,默认值:32,单位TB,实际可用范围由底层决定
141 "fabric_memory.start_address": "40", //虚拟内存池起始地址。取值范围:[0, 1024]之间的整数,默认值:40,单位TB141 "fabric_memory.start_address": "40", //虚拟内存池起始地址。取值范围:[0, 1024]之间的整数,默认值:40,单位TB
142 "fabric_memory.task_stream_num": "1", //单个任务使用的流数量,取值范围:[1, 8],默认值:1;enable_aicpu_unfold为true时仅支持1142 "fabric_memory.task_stream_num": "1", //单个任务使用的流数量,取值范围:[1, 8],默认值:1;enable_aicpu_unfold为true时仅支持1
143- "fabric_memory.enable_aicpu_unfold": true //是否由AICPU展开,布尔类型,默认true143+ "fabric_memory.enable_aicpu_unfold": true, //是否由AICPU展开,布尔类型,默认true
144+ "transfer_config.max_transfer_count_per_batch": 1920 //单个内部传输批次的最大buffer数量,FabricMem范围[1, 1920]
144}145}
145```146```
146<!-- end id6 -->147<!-- end id6 -->
@@ -312,6 +313,7 @@ UB_RTP
312| comm_resource_config.max_active_channels | 数字 | 可选 | CS场景下配置设备侧同时活跃传输通道数量 | 取值范围为[1, 8192],未配置时默认值为128。每个active channel消耗2个Stream资源,配置值需结合当前卡形态的Stream资源上限及业务中已创建的Stream数量预留余量;不同卡形态的Stream资源上限参见CANN Runtime API [aclrtCreateStream](https://www.hiascend.com/document/detail/zh/canncommercial/latest/API/runtimeapi/aclcppdevg_03_0066.html)资料。超出[1, 8192]时Initialize返回参数错误。|313| comm_resource_config.max_active_channels | 数字 | 可选 | CS场景下配置设备侧同时活跃传输通道数量 | 取值范围为[1, 8192],未配置时默认值为128。每个active channel消耗2个Stream资源,配置值需结合当前卡形态的Stream资源上限及业务中已创建的Stream数量预留余量;不同卡形态的Stream资源上限参见CANN Runtime API [aclrtCreateStream](https://www.hiascend.com/document/detail/zh/canncommercial/latest/API/runtimeapi/aclcppdevg_03_0066.html)资料。超出[1, 8192]时Initialize返回参数错误。|
313| comm_resource_config.multi_channel.num_workers | 数字 | 可选 | 配置多通道并发传输的worker数 | 取值范围为[1, 16],默认值为1(关闭多通道)。配置后,对UBOE和UB_RTP协议在建链时创建N个独立CS client,同步传输和异步传输均支持多通道并发,提升小包场景带宽。worker数越大占用的线程、Stream等设备资源越多,建议不超过8。|314| comm_resource_config.multi_channel.num_workers | 数字 | 可选 | 配置多通道并发传输的worker数 | 取值范围为[1, 16],默认值为1(关闭多通道)。配置后,对UBOE和UB_RTP协议在建链时创建N个独立CS client,同步传输和异步传输均支持多通道并发,提升小包场景带宽。worker数越大占用的线程、Stream等设备资源越多,建议不超过8。|
314| comm_resource_config.multi_channel.split_batch_size | 数字 | 可选 | 多通道并发传输的buffer拆分粒度 | 取值范围为[1, 4294967295],默认值为128。当单次传输的buffer数量大于split_batch_size时启用多通道拆分,拆分后的实际worker数由num_workers和buffer数量共同决定,不超过num_workers。|315| comm_resource_config.multi_channel.split_batch_size | 数字 | 可选 | 多通道并发传输的buffer拆分粒度 | 取值范围为[1, 4294967295],默认值为128。当单次传输的buffer数量大于split_batch_size时启用多通道拆分,拆分后的实际worker数由num_workers和buffer数量共同决定,不超过num_workers。|
316+| transfer_config.max_transfer_count_per_batch | 数字或十进制数字字符串 | 可选 | 单个内部传输批次最多包含的buffer数量,超过该值时HIXL保持原始顺序自动分批 | 默认值1920。HIXL全局校验范围为[1, 32766],HCCS/FabricMem范围为[1, 1920]。FabricMem两种模式都执行[1, 1920]校验:`fabric_memory.enable_aicpu_unfold=true`时,该值控制AICPU展开的逻辑批次和Notify边界;`false`时,Host逐条连续提交`aclrtMemcpyAsync`,不按该值分批或在该值边界同步。RoCE/URMA队列深度说明:Client的SQ/SCQ深度按`max(64, nextPowerOfTwo(配置值 + 2))`计算;Server的SQ/SCQ深度固定为64;RQ/RCQ不由HIXL下发,由Hcomm按协议和平台默认策略设置。队列深度的协议和硬件能力校验由Hcomm负责。|
315| local_comm_res_path | 字符串 | 可选 | 本地通信资源 JSON 文件路径;文件内容格式与 OPTION_LOCAL_COMM_RES 相同 | 配置文件的绝对或相对路径,相对路径基于进程当前工作目录解析。目标文件必须是大小在[1字节, 1MiB]范围内的普通文件。与 OPTION_LOCAL_COMM_RES 同时配置且 option 非空时,以 OPTION_LOCAL_COMM_RES 为准。 |317| local_comm_res_path | 字符串 | 可选 | 本地通信资源 JSON 文件路径;文件内容格式与 OPTION_LOCAL_COMM_RES 相同 | 配置文件的绝对或相对路径,相对路径基于进程当前工作目录解析。目标文件必须是大小在[1字节, 1MiB]范围内的普通文件。与 OPTION_LOCAL_COMM_RES 同时配置且 option 非空时,以 OPTION_LOCAL_COMM_RES 为准。 |
316| topo_file_path | 字符串 | 可选 | 自动生成LocalCommRes时使用的硬件拓扑JSON文件路径 | 不配置或配置为空串时,按mainboard_id在默认拓扑目录中查找对应文件。配置非空路径时使用该文件;目标文件必须是大小在[1字节, 1MiB]范围内的普通文件。文件不存在、类型非法、超出大小或解析失败则Initialize失败。已通过OPTION_LOCAL_COMM_RES或local_comm_res_path提供非空endpoint_list时不使用本字段,也不校验该路径。 |318| topo_file_path | 字符串 | 可选 | 自动生成LocalCommRes时使用的硬件拓扑JSON文件路径 | 不配置或配置为空串时,按mainboard_id在默认拓扑目录中查找对应文件。配置非空路径时使用该文件;目标文件必须是大小在[1字节, 1MiB]范围内的普通文件。文件不存在、类型非法、超出大小或解析失败则Initialize失败。已通过OPTION_LOCAL_COMM_RES或local_comm_res_path提供非空endpoint_list时不使用本字段,也不校验该路径。 |
317 319 
@@ -100,6 +100,9 @@ Client侧`global_resource_config`当前支持的配置项如下。
100|---|---|---|---|100|---|---|---|---|
101| comm_resource_config.qos | 数字 | 可选 | 配置通信协议qos,当前仅支持[0-7],当未配置的时候,默认为0。 |101| comm_resource_config.qos | 数字 | 可选 | 配置通信协议qos,当前仅支持[0-7],当未配置的时候,默认为0。 |
102| comm_resource_config.max_active_channels | 整数 | 可选 | 配置Client设备侧同时活跃传输通道数量。取值范围为[1, 8192];未配置时默认值为128;每个active channel消耗2个Stream资源,配置值需结合当前卡形态的Stream资源上限及业务中已创建的Stream数量预留余量;不同卡形态的Stream资源上限参见CANN Runtime API [aclrtCreateStream](https://www.hiascend.com/document/detail/zh/canncommercial/latest/API/runtimeapi/aclcppdevg_03_0066.html)资料;取值小于1、大于8192或非数字时,Client创建失败并返回参数错误。 |102| comm_resource_config.max_active_channels | 整数 | 可选 | 配置Client设备侧同时活跃传输通道数量。取值范围为[1, 8192];未配置时默认值为128;每个active channel消耗2个Stream资源,配置值需结合当前卡形态的Stream资源上限及业务中已创建的Stream数量预留余量;不同卡形态的Stream资源上限参见CANN Runtime API [aclrtCreateStream](https://www.hiascend.com/document/detail/zh/canncommercial/latest/API/runtimeapi/aclcppdevg_03_0066.html)资料;取值小于1、大于8192或非数字时,Client创建失败并返回参数错误。 |
103+| transfer_config.max_transfer_count_per_batch | 数字或十进制数字字符串 | 可选 | 单个内部传输批次最多包含的buffer数量,超过时按原始顺序自动分批。默认1920,全局取值范围为[1, 32766],HCCS链路范围为[1, 1920]。 |
104+ 
105+RoCE/URMA队列深度说明:Client的SQ/SCQ深度按`max(64, nextPowerOfTwo(配置值 + 2))`计算;Server的SQ/SCQ深度固定为64;RQ/RCQ不由HIXL下发,由Hcomm按协议和平台默认策略设置。队列深度的协议和硬件能力校验由Hcomm负责。
103 106 
104Server配置示例:107Server配置示例:
105 108 
@@ -113,7 +116,8 @@ Client配置示例:
113 116 
114```json117```json
115{118{
116- "comm_resource_config.qos": 7119+ "comm_resource_config.qos": 7,
120+ "transfer_config.max_transfer_count_per_batch": 1920
117}121}
118```122```
119 123 
@@ -288,6 +288,7 @@ UB_RTP
288| comm_resource_config.listen_port | JSON数字或纯数字字符串 | 可选 | 配置device侧网卡监听端口 | 取值范围为[1, 65535]。Atlas A2 训练系列产品/Atlas A2 推理系列产品、Atlas A3 训练系列产品/Atlas A3 推理系列产品上未配置时,固定使用`16666`端口;Ascend 950PR/Ascend 950DT场景未配置时,由底层通信组件自动选择可用端口,HIXL自动查询实际监听端口。 |288| comm_resource_config.listen_port | JSON数字或纯数字字符串 | 可选 | 配置device侧网卡监听端口 | 取值范围为[1, 65535]。Atlas A2 训练系列产品/Atlas A2 推理系列产品、Atlas A3 训练系列产品/Atlas A3 推理系列产品上未配置时,固定使用`16666`端口;Ascend 950PR/Ascend 950DT场景未配置时,由底层通信组件自动选择可用端口,HIXL自动查询实际监听端口。 |
289| comm_resource_config.qos | 数字 | 可选 | 配置通信协议qos | 当前仅支持[0-7],当未配置的时候,默认为0。 |289| comm_resource_config.qos | 数字 | 可选 | 配置通信协议qos | 当前仅支持[0-7],当未配置的时候,默认为0。 |
290| comm_resource_config.max_active_channels | 数字 | 可选 | CS场景下配置设备侧同时活跃传输通道数量 | 取值范围为[1, 8192],未配置时默认值为128。每个active channel消耗2个Stream资源,配置值需结合当前卡形态的Stream资源上限及业务中已创建的Stream数量预留余量;不同卡形态的Stream资源上限参见CANN Runtime API [aclrtCreateStream](https://www.hiascend.com/document/detail/zh/canncommercial/latest/API/runtimeapi/aclcppdevg_03_0066.html)资料。超出[1, 8192]时initialize返回参数错误。 |290| comm_resource_config.max_active_channels | 数字 | 可选 | CS场景下配置设备侧同时活跃传输通道数量 | 取值范围为[1, 8192],未配置时默认值为128。每个active channel消耗2个Stream资源,配置值需结合当前卡形态的Stream资源上限及业务中已创建的Stream数量预留余量;不同卡形态的Stream资源上限参见CANN Runtime API [aclrtCreateStream](https://www.hiascend.com/document/detail/zh/canncommercial/latest/API/runtimeapi/aclcppdevg_03_0066.html)资料。超出[1, 8192]时initialize返回参数错误。 |
291+| transfer_config.max_transfer_count_per_batch | 数字或十进制数字字符串 | 可选 | 单个内部传输批次最多包含的buffer数量,超过时按原始顺序自动分批 | 默认1920,全局取值范围为[1, 32766],HCCS/FabricMem范围为[1, 1920],RoCE/URMA的具体队列深度上限由Hcomm根据协议和硬件能力校验。FabricMem两种模式都执行[1, 1920]校验:`fabric_memory.enable_aicpu_unfold=true`时,该值控制AICPU展开的逻辑批次和Notify边界;`false`时,Host逐条连续提交`aclrtMemcpyAsync`,不按该值分批或在该值边界同步。RoCE/URMA Client的SQ/SCQ深度按`max(64, nextPowerOfTwo(配置值 + 2))`计算。 |
291| local_comm_res_path | 字符串 | 可选 | 本地通信资源 JSON 文件路径;文件内容格式与 OPTION_LOCAL_COMM_RES 相同 | 配置文件的绝对或相对路径,相对路径基于进程当前工作目录解析。目标文件必须是大小在[1字节, 1MiB]范围内的普通文件。与 OPTION_LOCAL_COMM_RES 同时配置且 option 非空时,以 OPTION_LOCAL_COMM_RES 为准。 |292| local_comm_res_path | 字符串 | 可选 | 本地通信资源 JSON 文件路径;文件内容格式与 OPTION_LOCAL_COMM_RES 相同 | 配置文件的绝对或相对路径,相对路径基于进程当前工作目录解析。目标文件必须是大小在[1字节, 1MiB]范围内的普通文件。与 OPTION_LOCAL_COMM_RES 同时配置且 option 非空时,以 OPTION_LOCAL_COMM_RES 为准。 |
292 293 
293**调用示例**294**调用示例**
Rdocs/zh/design/FabricMem模式设计.md→docs/zh/design/FabricMem.md+1-1
@@ -313,7 +313,7 @@ sequenceDiagram
313 313 
314**检查点列表**:314**检查点列表**:
3151. **Engine路由检查**:`OPTION_ENABLE_USE_FABRIC_MEM=1`时必须由`EngineFactory`创建`FabricMemEngine`。3151. **Engine路由检查**:`OPTION_ENABLE_USE_FABRIC_MEM=1`时必须由`EngineFactory`创建`FabricMemEngine`。
316-2. **配置合法性检查**:`FabricMemConfig`解析`EnableUseFabricMem`、`GlobalResourceConfig`、流数量、虚拟地址容量和起始地址。316+2. **配置合法性检查**:`FabricMemConfig`解析`EnableUseFabricMem`、`GlobalResourceConfig`、流数量、虚拟地址容量、起始地址和单批最大传输数量。`transfer_config.max_transfer_count_per_batch`范围为`[1, 1920]`、默认`1920`,两种展开模式都会执行该范围校验。`enable_aicpu_unfold=true`时,它控制AICPU展开的逻辑批次和Notify边界,不改变固定2K的STARS队列深度;`enable_aicpu_unfold=false`时,Host逐条提交`aclrtMemcpyAsync`,不按该值分批,也不在该值边界增加同步。
3173. **内存类型检查**:在FabricMem模式下,HOST内存注册需要额外的本地导入和映射处理。3173. **内存类型检查**:在FabricMem模式下,HOST内存注册需要额外的本地导入和映射处理。
3184. **传输参数检查**:验证传输描述中的地址范围是否在本端已注册或对端已导入的内存范围内。3184. **传输参数检查**:验证传输描述中的地址范围是否在本端已注册或对端已导入的内存范围内。
3195. **流资源管理检查**:确保流池中的流资源正确分配和释放,避免资源泄漏。3195. **流资源管理检查**:确保流池中的流资源正确分配和释放,避免资源泄漏。
@@ -0,0 +1,41 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#ifndef CANN_HIXL_SRC_HIXL_COMMON_TRANSFER_CONFIG_H_
12+#define CANN_HIXL_SRC_HIXL_COMMON_TRANSFER_CONFIG_H_
13+ 
14+#include <algorithm>
15+#include <cstdint>
16+#include <limits>
17+ 
18+namespace hixl {
19+ 
20+constexpr uint32_t kDefaultMaxTransferCountPerBatch = 1920U;
21+constexpr uint32_t kMaxTransferCountPerBatch = 32766U;
22+constexpr uint32_t kMaxFixedQueueTransferCountPerBatch = 1920U;
23+constexpr uint32_t kMinTransportQueueDepth = 64U;
24+ 
25+static_assert(kMaxTransferCountPerBatch <= std::numeric_limits<uint32_t>::max() - 2U,
26+ "max_transfer_count_per_batch + 2 must not overflow uint32_t.");
27+static_assert(kMaxTransferCountPerBatch + 2U <= (1U << 31U),
28+ "The required transport queue depth must fit in uint32_t after rounding up to a power of two.");
29+ 
30+inline uint32_t CalculateTransportQueueDepth(uint32_t max_transfer_count_per_batch) {
31+ uint32_t depth = 1U;
32+ const uint32_t required = max_transfer_count_per_batch + 2U;
33+ while (depth < required) {
34+ depth <<= 1U;
35+ }
36+ return std::max(kMinTransportQueueDepth, depth);
37+}
38+ 
39+} // namespace hixl
40+ 
41+#endif // CANN_HIXL_SRC_HIXL_COMMON_TRANSFER_CONFIG_H_
@@ -14,6 +14,7 @@
14#include <memory>14#include <memory>
15#include "cs/hixl_cs.h"15#include "cs/hixl_cs.h"
16#include "hixl/hixl_types.h"16#include "hixl/hixl_types.h"
17+#include "common/transfer_config.h"
17 18 
18namespace hixl {19namespace hixl {
19 20 
@@ -32,6 +33,7 @@ struct ChannelDesc {
32 ChannelType channel_type{ChannelType::kClient};33 ChannelType channel_type{ChannelType::kClient};
33 uint64_t channel_index{0UL};34 uint64_t channel_index{0UL};
34 uint8_t qos{0U};35 uint8_t qos{0U};
36+ uint32_t max_transfer_count_per_batch{kDefaultMaxTransferCountPerBatch};
35};37};
36 38 
37class Channel {39class Channel {
@@ -24,6 +24,28 @@ namespace hixl {
24namespace {24namespace {
25constexpr uint32_t kRoceQueueNum = 1U; // ROCE QP数量默认值25constexpr uint32_t kRoceQueueNum = 1U; // ROCE QP数量默认值
26 26 
27+bool IsUrmaProtocol(CommProtocol protocol) {
28+ return protocol == COMM_PROTOCOL_UBC_CTP || protocol == COMM_PROTOCOL_UBOE || protocol == COMM_PROTOCOL_UBG;
29+}
30+ 
31+void InitQueueDepth(const EndpointDesc &endpoint, const ChannelDesc &channel_desc, HcommChannelDesc &ch_desc) {
32+ const bool is_client = channel_desc.channel_type == ChannelType::kClient;
33+ const uint32_t data_depth =
34+ is_client ? CalculateTransportQueueDepth(channel_desc.max_transfer_count_per_batch) : kMinTransportQueueDepth;
35+ if (endpoint.protocol == COMM_PROTOCOL_ROCE) {
36+ ch_desc.roceAttr.sqDepth = data_depth;
37+ ch_desc.roceAttr.scqDepth = data_depth;
38+ HIXL_LOGI("[channel] RoCE queue depth set, role=%d, sq=%u, scq=%u", static_cast<int32_t>(channel_desc.channel_type),
39+ ch_desc.roceAttr.sqDepth, ch_desc.roceAttr.scqDepth);
40+ } else if (IsUrmaProtocol(endpoint.protocol)) {
41+ ch_desc.ubAttr.sqDepth = data_depth;
42+ ch_desc.ubAttr.scqDepth = data_depth;
43+ HIXL_LOGI("[channel] URMA queue depth set, protocol=%d, role=%d, sq=%u, scq=%u",
44+ static_cast<int32_t>(endpoint.protocol), static_cast<int32_t>(channel_desc.channel_type),
45+ ch_desc.ubAttr.sqDepth, ch_desc.ubAttr.scqDepth);
46+ }
47+}
48+ 
27bool IsDefaultHostVaMappingEnabled(const EndpointDesc &endpoint) {49bool IsDefaultHostVaMappingEnabled(const EndpointDesc &endpoint) {
28 return endpoint.loc.locType == ENDPOINT_LOC_TYPE_DEVICE &&50 return endpoint.loc.locType == ENDPOINT_LOC_TYPE_DEVICE &&
29 (endpoint.protocol == COMM_PROTOCOL_UBOE || endpoint.protocol == COMM_PROTOCOL_UBG ||51 (endpoint.protocol == COMM_PROTOCOL_UBOE || endpoint.protocol == COMM_PROTOCOL_UBG ||
@@ -70,6 +92,7 @@ Status InitChannelDesc(const EndpointDesc &endpoint, const ChannelDesc &channel_
70 ch_desc.roceAttr.tc, ch_desc.roceAttr.sl, ch_desc.roceAttr.retryCnt, ch_desc.roceAttr.retryInterval,92 ch_desc.roceAttr.tc, ch_desc.roceAttr.sl, ch_desc.roceAttr.retryCnt, ch_desc.roceAttr.retryInterval,
71 ch_desc.roceAttr.queueNum);93 ch_desc.roceAttr.queueNum);
72 }94 }
95+ InitQueueDepth(endpoint, channel_desc, ch_desc);
73 ch_desc.port = port;96 ch_desc.port = port;
74 // need add qos at here when HcommChannelDesc exist qos97 // need add qos at here when HcommChannelDesc exist qos
75 ch_desc.qos = static_cast<uint32_t>(channel_desc.qos);98 ch_desc.qos = static_cast<uint32_t>(channel_desc.qos);
@@ -15,6 +15,7 @@
15#include "common/hixl_log.h"15#include "common/hixl_log.h"
16#include "common/hixl_inner_types.h"16#include "common/hixl_inner_types.h"
17#include "common/json_utils.h"17#include "common/json_utils.h"
18+#include "common/transfer_config.h"
18 19 
19namespace hixl {20namespace hixl {
20namespace {21namespace {
@@ -24,6 +25,7 @@ constexpr int64_t kMinListenPort = 1;
24constexpr int64_t kMaxListenPort = 65535;25constexpr int64_t kMaxListenPort = 65535;
25constexpr int64_t kMinActiveChannels = 1;26constexpr int64_t kMinActiveChannels = 1;
26constexpr int64_t kMaxActiveChannels = 8192;27constexpr int64_t kMaxActiveChannels = 8192;
28+constexpr const char *kMaxTransferCountPerBatchKey = "transfer_config.max_transfer_count_per_batch";
27 29 
28Status ParseListenPort(const nlohmann::json &json, CommResourceConfig &config) {30Status ParseListenPort(const nlohmann::json &json, CommResourceConfig &config) {
29 const auto it = json.find(kListenPort);31 const auto it = json.find(kListenPort);
@@ -78,6 +80,27 @@ Status ParseMaxActiveChannels(const nlohmann::json &json, CommResourceConfig &co
78 return SUCCESS;80 return SUCCESS;
79}81}
80 82 
83+Status ParseTransferConfig(const nlohmann::json &json, TransferConfigDesc &config, GlobalConfig::ParseTarget target) {
84+ const auto it = json.find(kMaxTransferCountPerBatchKey);
85+ if (it == json.end()) {
86+ return SUCCESS;
87+ }
88+ HIXL_CHK_BOOL_RET_STATUS(target != GlobalConfig::ParseTarget::kServer, PARAM_INVALID,
89+ "[GlobalConfig] %s is not supported for Server", kMaxTransferCountPerBatchKey);
90+ HIXL_CHK_BOOL_RET_STATUS((it->is_number_integer() || it->is_number_unsigned()) || it->is_string(), PARAM_INVALID,
91+ "[GlobalConfig] %s must be an integer or decimal integer string",
92+ kMaxTransferCountPerBatchKey);
93+ const auto val = JsonToNumber<int64_t>(*it);
94+ if (val < 1 || val > static_cast<int64_t>(kMaxTransferCountPerBatch)) {
95+ HIXL_LOGE(PARAM_INVALID, "[GlobalConfig] max_transfer_count_per_batch out of range: %ld, must be in [1, %u]", val,
96+ kMaxTransferCountPerBatch);
97+ return PARAM_INVALID;
98+ }
99+ config.max_transfer_count_per_batch = static_cast<uint32_t>(val);
100+ HIXL_LOGI("[GlobalConfig] max_transfer_count_per_batch=%u", config.max_transfer_count_per_batch);
101+ return SUCCESS;
102+}
103+ 
81Status ParseCommResourceConfig(const nlohmann::json &json, CommResourceConfig &config,104Status ParseCommResourceConfig(const nlohmann::json &json, CommResourceConfig &config,
82 GlobalConfig::ParseTarget target) {105 GlobalConfig::ParseTarget target) {
83 if (target == GlobalConfig::ParseTarget::kAll || target == GlobalConfig::ParseTarget::kServer) {106 if (target == GlobalConfig::ParseTarget::kAll || target == GlobalConfig::ParseTarget::kServer) {
@@ -121,6 +144,8 @@ Status GlobalConfig::Parse(const char *config_str, GlobalConfig &result, ParseTa
121 HIXL_LOGE(ret, "[GlobalConfig] Failed to parse comm_resource_config");144 HIXL_LOGE(ret, "[GlobalConfig] Failed to parse comm_resource_config");
122 return ret;145 return ret;
123 }146 }
147+ HIXL_CHK_STATUS_RET(ParseTransferConfig(json, result.transfer_config_, target),
148+ "[GlobalConfig] Failed to parse transfer_config");
124 return SUCCESS;149 return SUCCESS;
125 } catch (const nlohmann::json::exception &e) {150 } catch (const nlohmann::json::exception &e) {
126 HIXL_LOGE(PARAM_INVALID, "[GlobalConfig] Failed to parse config: %s", e.what());151 HIXL_LOGE(PARAM_INVALID, "[GlobalConfig] Failed to parse config: %s", e.what());
@@ -139,4 +164,8 @@ std::optional<uint8_t> GlobalConfig::Qos() const {
139std::optional<uint32_t> GlobalConfig::MaxActiveChannels() const {164std::optional<uint32_t> GlobalConfig::MaxActiveChannels() const {
140 return comm_resource_config_.max_active_channels;165 return comm_resource_config_.max_active_channels;
141}166}
167+ 
168+uint32_t GlobalConfig::MaxTransferCountPerBatch() const {
169+ return transfer_config_.max_transfer_count_per_batch;
170+}
142} // namespace hixl171} // namespace hixl
@@ -15,6 +15,7 @@
15#include <optional>15#include <optional>
16 16 
17#include "hixl/hixl_types.h"17#include "hixl/hixl_types.h"
18+#include "common/transfer_config.h"
18 19 
19namespace hixl {20namespace hixl {
20 21 
@@ -24,6 +25,10 @@ struct CommResourceConfig {
24 std::optional<uint32_t> max_active_channels;25 std::optional<uint32_t> max_active_channels;
25};26};
26 27 
28+struct TransferConfigDesc {
29+ uint32_t max_transfer_count_per_batch{kDefaultMaxTransferCountPerBatch};
30+};
31+ 
27class GlobalConfig {32class GlobalConfig {
28 public:33 public:
29 enum class ParseTarget {34 enum class ParseTarget {
@@ -37,9 +42,11 @@ class GlobalConfig {
37 std::optional<uint32_t> ListenPort() const;42 std::optional<uint32_t> ListenPort() const;
38 std::optional<uint8_t> Qos() const;43 std::optional<uint8_t> Qos() const;
39 std::optional<uint32_t> MaxActiveChannels() const;44 std::optional<uint32_t> MaxActiveChannels() const;
45+ uint32_t MaxTransferCountPerBatch() const;
40 46 
41 private:47 private:
42 CommResourceConfig comm_resource_config_;48 CommResourceConfig comm_resource_config_;
49+ TransferConfigDesc transfer_config_;
43};50};
44 51 
45} // namespace hixl52} // namespace hixl
@@ -48,7 +48,6 @@ constexpr uint64_t kFlagDoneValue = 1ULL;
48constexpr uint64_t kFlagResetValue = 0ULL;48constexpr uint64_t kFlagResetValue = 0ULL;
49constexpr uint32_t kCustomTimeoutMs = 1800;49constexpr uint32_t kCustomTimeoutMs = 1800;
50constexpr uint32_t kMaxKernelBatchSize = 128U;50constexpr uint32_t kMaxKernelBatchSize = 128U;
51-constexpr uint32_t kNotifyWaitTaskInterval = 1920U;
52// ACL_RT_LAUNCH_KERNEL_ATTR_TIMEOUT uses seconds. Async callers observe timeout by CheckStatus.51// ACL_RT_LAUNCH_KERNEL_ATTR_TIMEOUT uses seconds. Async callers observe timeout by CheckStatus.
53constexpr uint16_t kNotifyDefaultWaitTimeS = 27 * 68;52constexpr uint16_t kNotifyDefaultWaitTimeS = 27 * 68;
54constexpr uint32_t kMinRdmaRetryCnt = 1U;53constexpr uint32_t kMinRdmaRetryCnt = 1U;
@@ -502,17 +501,16 @@ Status HixlCSClient::BatchTransferTask(bool is_get, uint32_t list_num, const Hix
502 "[HixlClient] TransferWithRetry failed, is_get:%d, channel_handle:%lu, size:%lu bytes",501 "[HixlClient] TransferWithRetry failed, is_get:%d, channel_handle:%lu, size:%lu bytes",
503 static_cast<int32_t>(is_get), client_channel_handle_, desc_list[i].len);502 static_cast<int32_t>(is_get), client_channel_handle_, desc_list[i].len);
504 }503 }
505- HIXL_CHK_HCCL_RET(
506- static_cast<HcclResult>(HcommProxy::ChannelFenceOnThread(static_cast<ThreadHandle>(0), client_channel_handle_)),
507- "[HixlClient] channel_handle:%lu", client_channel_handle_);
508 return SUCCESS;504 return SUCCESS;
509}505}
510Status HixlCSClient::BatchTransferHostAsync(bool is_get, uint32_t list_num, const HixlOneSideOpDesc *desc_list,506Status HixlCSClient::BatchTransferHostAsync(bool is_get, uint32_t list_num, const HixlOneSideOpDesc *desc_list,
511 void **query_handle) {507 void **query_handle) {
512- uint32_t num_chunks = (list_num + kMaxKernelBatchSize - 1U) / kMaxKernelBatchSize;508+ HIXL_CHK_BOOL_RET_STATUS(list_num > 0U, PARAM_INVALID, "[HixlClient] list_num must be > 0");
509+ const uint32_t batch_size = global_config_.MaxTransferCountPerBatch();
510+ const uint32_t num_chunks = list_num / batch_size + static_cast<uint32_t>(list_num % batch_size != 0U);
513 for (uint32_t chunk_idx = 0U; chunk_idx < num_chunks; ++chunk_idx) {511 for (uint32_t chunk_idx = 0U; chunk_idx < num_chunks; ++chunk_idx) {
514- uint32_t chunk_offset = chunk_idx * kMaxKernelBatchSize;512+ uint32_t chunk_offset = chunk_idx * batch_size;
515- uint32_t chunk_size = std::min(kMaxKernelBatchSize, list_num - chunk_offset);513+ uint32_t chunk_size = std::min(batch_size, list_num - chunk_offset);
516 HIXL_CHK_STATUS_RET(BatchTransferTask(is_get, chunk_size, desc_list + chunk_offset),514 HIXL_CHK_STATUS_RET(BatchTransferTask(is_get, chunk_size, desc_list + chunk_offset),
517 "[HixlClient] BatchTransferTask failed for chunk %u/%u", chunk_idx, num_chunks);515 "[HixlClient] BatchTransferTask failed for chunk %u/%u", chunk_idx, num_chunks);
518 }516 }
@@ -533,11 +531,10 @@ Status HixlCSClient::BatchTransferHostAsync(bool is_get, uint32_t list_num, cons
533 } else {531 } else {
534 kTransFlagName = kTransFlagNameDevice;532 kTransFlagName = kTransFlagNameDevice;
535 }533 }
536- HIXL_CHK_HCCL_RET(static_cast<HcclResult>(534+ HIXL_CHK_STATUS_RET(
537- HcommProxy::ReadNbiOnThread(static_cast<ThreadHandle>(0), client_channel_handle_, flag_addr,535+ TransferWithRetry(true, client_channel_handle_, flag_addr, tag_mem_descs_[kTransFlagName].addr, kFlagSizeBytes),
538- tag_mem_descs_[kTransFlagName].addr, kFlagSizeBytes)),536+ "[HixlClient] Transfer completion flag failed, channel_handle:%lu, dst_addr:%p, src_addr:%p, size:%u bytes",
539- "[HixlClient] channel_handle:%lu, dst_addr:%p, src_addr:%p, size:%u bytes", client_channel_handle_,537+ client_channel_handle_, flag_addr, tag_mem_descs_[kTransFlagName].addr, kFlagSizeBytes);
540- flag_addr, tag_mem_descs_[kTransFlagName].addr, kFlagSizeBytes);
541 auto *query_mem_handle = new (std::nothrow) CompleteHandleInfo();538 auto *query_mem_handle = new (std::nothrow) CompleteHandleInfo();
542 if (query_mem_handle == nullptr) {539 if (query_mem_handle == nullptr) {
543 HIXL_LOGE(FAILED, "Memory allocate failed; unable to generate query handle.");540 HIXL_LOGE(FAILED, "Memory allocate failed; unable to generate query handle.");
@@ -720,17 +717,27 @@ Status HixlCSClient::AllocateHostFlag(void *&host_flag) const {
720}717}
721 718 
722Status HixlCSClient::LaunchDeviceChunkedKernels(bool is_get, DeviceCompleteHandle &handle, uint32_t list_num) const {719Status HixlCSClient::LaunchDeviceChunkedKernels(bool is_get, DeviceCompleteHandle &handle, uint32_t list_num) const {
723- uint32_t num_chunks = (list_num + kMaxKernelBatchSize - 1U) / kMaxKernelBatchSize;720+ const uint32_t batch_size = global_config_.MaxTransferCountPerBatch();
724- for (uint32_t chunk_idx = 0U; chunk_idx < num_chunks; ++chunk_idx) {721+ // Device transfers have two batching boundaries: each kernel accepts at most 128 descriptors, while each logical
725- uint32_t chunk_offset = chunk_idx * kMaxKernelBatchSize;722+ // transfer batch accepts at most batch_size descriptors. A kernel never crosses a logical batch boundary, and the
726- uint32_t chunk_list_num = std::min(kMaxKernelBatchSize, list_num - chunk_offset);723+ // last kernel in every logical batch records a Notify that the host waits for before submitting the next batch.
727- uint32_t chunk_end = chunk_offset + chunk_list_num;724+ uint32_t chunk_offset = 0U;
728- bool need_notify_wait = (chunk_end % kNotifyWaitTaskInterval == 0U) || (chunk_end == list_num);725+ uint32_t batch_remaining = batch_size;
726+ uint32_t chunk_idx = 0U;
727+ while (chunk_offset < list_num) {
728+ uint32_t chunk_list_num = std::min({kMaxKernelBatchSize, batch_remaining, list_num - chunk_offset});
729+ batch_remaining -= chunk_list_num;
730+ const bool need_notify_wait = batch_remaining == 0U || chunk_offset + chunk_list_num == list_num;
729 HixlOneSideOpParam param{};731 HixlOneSideOpParam param{};
730 HIXL_CHK_STATUS_RET(BuildDeviceChunkParam(handle, chunk_offset, chunk_list_num, need_notify_wait, param),732 HIXL_CHK_STATUS_RET(BuildDeviceChunkParam(handle, chunk_offset, chunk_list_num, need_notify_wait, param),
731- "BuildDeviceChunkParam failed for chunk %u/%u", chunk_idx, num_chunks);733+ "BuildDeviceChunkParam failed for chunk %u", chunk_idx);
732 HIXL_CHK_STATUS_RET(LaunchDeviceKernel(is_get, handle, param, need_notify_wait),734 HIXL_CHK_STATUS_RET(LaunchDeviceKernel(is_get, handle, param, need_notify_wait),
733- "LaunchDeviceKernel failed for chunk %u/%u", chunk_idx, num_chunks);735+ "LaunchDeviceKernel failed for chunk %u", chunk_idx);
736+ chunk_offset += chunk_list_num;
737+ ++chunk_idx;
738+ if (batch_remaining == 0U) {
739+ batch_remaining = batch_size;
740+ }
734 }741 }
735 return SUCCESS;742 return SUCCESS;
736}743}
@@ -959,11 +966,11 @@ Status HixlCSClient::BatchTransferDeviceSync(bool is_get, uint32_t list_num, con
959 966 
960Status HixlCSClient::BatchTransferHostSync(bool is_get, uint32_t list_num, const HixlOneSideOpDesc *desc_list,967Status HixlCSClient::BatchTransferHostSync(bool is_get, uint32_t list_num, const HixlOneSideOpDesc *desc_list,
961 uint32_t timeout_ms) {968 uint32_t timeout_ms) {
969+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
962 void *raw_handle = nullptr;970 void *raw_handle = nullptr;
963 HIXL_CHK_STATUS_RET(BatchTransferHostAsync(is_get, list_num, desc_list, &raw_handle),971 HIXL_CHK_STATUS_RET(BatchTransferHostAsync(is_get, list_num, desc_list, &raw_handle),
964 "[HixlClient] BatchTransferHostAsync failed");972 "[HixlClient] BatchTransferHostAsync failed");
965 HIXL_CHECK_NOTNULL(raw_handle);973 HIXL_CHECK_NOTNULL(raw_handle);
966- const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
967 while (true) {974 while (true) {
968 if (std::chrono::steady_clock::now() >= deadline) {975 if (std::chrono::steady_clock::now() >= deadline) {
969 (void)ReleaseCompleteHandle(static_cast<CompleteHandleInfo *>(raw_handle));976 (void)ReleaseCompleteHandle(static_cast<CompleteHandleInfo *>(raw_handle));
@@ -1249,7 +1256,8 @@ Status HixlCSClient::ExchangeEndpointAndCreateChannel(uint32_t timeout_ms) {
1249 retry_interval_,1256 retry_interval_,
1250 ChannelType::kClient,1257 ChannelType::kClient,
1251 channel_index,1258 channel_index,
1252- global_config_.Qos().value_or(kQosDefault)};1259+ global_config_.Qos().value_or(kQosDefault),
1260+ global_config_.MaxTransferCountPerBatch()};
1253 HIXL_CHK_STATUS_RET(local_endpoint_->CreateChannel(channel_desc, channel_handle, timeout_ms),1261 HIXL_CHK_STATUS_RET(local_endpoint_->CreateChannel(channel_desc, channel_handle, timeout_ms),
1254 "[HixlClient] Endpoint CreateChannel failed. Dst[id:0x%x]", remote_endpoint_.commAddr.id);1262 "[HixlClient] Endpoint CreateChannel failed. Dst[id:0x%x]", remote_endpoint_.commAddr.id);
1255 HIXL_CHK_STATUS_RET(ConnMsgHandler::RecvCreateChannelResponse(socket_, timeout_ms),1263 HIXL_CHK_STATUS_RET(ConnMsgHandler::RecvCreateChannelResponse(socket_, timeout_ms),
@@ -22,10 +22,6 @@ namespace hixl {
22class ClientHandlerConfigHelper {22class ClientHandlerConfigHelper {
23 public:23 public:
24 static std::string BuildGlobalResourceConfig(const HandlerCreateArgs &args) {24 static std::string BuildGlobalResourceConfig(const HandlerCreateArgs &args) {
25- // force return "", default json construction will dump to "null" which not as expect
26- if (!args.qos.has_value() && !args.max_active_channels.has_value()) {
27- return "";
28- }
29 nlohmann::json json;25 nlohmann::json json;
30 if (args.qos.has_value()) {26 if (args.qos.has_value()) {
31 json["comm_resource_config.qos"] = args.qos.value();27 json["comm_resource_config.qos"] = args.qos.value();
@@ -33,6 +29,7 @@ class ClientHandlerConfigHelper {
33 if (args.max_active_channels.has_value()) {29 if (args.max_active_channels.has_value()) {
34 json["comm_resource_config.max_active_channels"] = args.max_active_channels.value();30 json["comm_resource_config.max_active_channels"] = args.max_active_channels.value();
35 }31 }
32+ json["transfer_config.max_transfer_count_per_batch"] = args.max_transfer_count_per_batch;
36 return json.dump();33 return json.dump();
37 }34 }
38};35};
@@ -9,39 +9,39 @@
9 */9 */
10 10 
11#include "engine/client_handler_factory.h"11#include "engine/client_handler_factory.h"
12+ 
13+#include <utility>
14+ 
15+#include "common/hixl_checker.h"
12#include "common/hixl_log.h"16#include "common/hixl_log.h"
13#include "engine/direct_client_handler.h"17#include "engine/direct_client_handler.h"
14#include "engine/direct_multi_channel_handler.h"18#include "engine/direct_multi_channel_handler.h"
15#include "engine/ub_client_handler.h"19#include "engine/ub_client_handler.h"
16 20 
17namespace hixl {21namespace hixl {
18- 22+Status ClientHandlerFactory::Create(const HandlerCreateArgs &args, std::unique_ptr<IClientHandler> &out) {
19-std::unique_ptr<IClientHandler> ClientHandlerFactory::Create(const HandlerCreateArgs &args) {23+ out.reset();
20 if (args.handler_type == HandlerCreateArgs::HandlerType::DIRECT) {24 if (args.handler_type == HandlerCreateArgs::HandlerType::DIRECT) {
21 const auto &pair = args.matched_pairs[0];25 const auto &pair = args.matched_pairs[0];
22 const bool is_multi_worker_protocol =26 const bool is_multi_worker_protocol =
23 (pair.type == CommType::COMM_TYPE_UBOE || pair.type == CommType::COMM_TYPE_UBG);27 (pair.type == CommType::COMM_TYPE_UBOE || pair.type == CommType::COMM_TYPE_UBG);
24 if (is_multi_worker_protocol && args.multi_worker_num > 1U) {28 if (is_multi_worker_protocol && args.multi_worker_num > 1U) {
25 std::unique_ptr<DirectMultiChannelHandler> handler;29 std::unique_ptr<DirectMultiChannelHandler> handler;
26- if (DirectMultiChannelHandler::Create(args, handler) != SUCCESS) {30+ HIXL_CHK_STATUS_RET(DirectMultiChannelHandler::Create(args, handler),
27- HIXL_LOGE(FAILED, "ClientHandlerFactory create DirectMultiChannelHandler failed");31+ "ClientHandlerFactory create DirectMultiChannelHandler failed");
28- return nullptr;32+ out = std::move(handler);
29- }33+ return SUCCESS;
30- return handler;
31 }34 }
32 std::unique_ptr<DirectClientHandler> handler;35 std::unique_ptr<DirectClientHandler> handler;
33- if (DirectClientHandler::Create(args, handler) != SUCCESS) {36+ HIXL_CHK_STATUS_RET(DirectClientHandler::Create(args, handler),
34- HIXL_LOGE(FAILED, "ClientHandlerFactory create DirectClientHandler failed");37+ "ClientHandlerFactory create DirectClientHandler failed");
35- return nullptr;38+ out = std::move(handler);
36- }39+ return SUCCESS;
37- return handler;
38 }40 }
39 std::unique_ptr<UbClientHandler> handler;41 std::unique_ptr<UbClientHandler> handler;
40- if (UbClientHandler::Create(args, handler) != SUCCESS) {42+ HIXL_CHK_STATUS_RET(UbClientHandler::Create(args, handler), "ClientHandlerFactory create UbClientHandler failed");
41- HIXL_LOGE(FAILED, "ClientHandlerFactory create UbClientHandler failed");43+ out = std::move(handler);
42- return nullptr;44+ return SUCCESS;
43- }
44- return handler;
45}45}
46 46 
47} // namespace hixl47} // namespace hixl
@@ -16,6 +16,7 @@
16#include <string>16#include <string>
17#include <vector>17#include <vector>
18#include "common/hixl_inner_types.h"18#include "common/hixl_inner_types.h"
19+#include "common/transfer_config.h"
19#include "engine/client_handler.h"20#include "engine/client_handler.h"
20 21 
21namespace hixl {22namespace hixl {
@@ -37,6 +38,7 @@ struct HandlerCreateArgs {
37 std::vector<EndpointPair> matched_pairs;38 std::vector<EndpointPair> matched_pairs;
38 std::optional<uint8_t> qos;39 std::optional<uint8_t> qos;
39 std::optional<uint32_t> max_active_channels;40 std::optional<uint32_t> max_active_channels;
41+ uint32_t max_transfer_count_per_batch{kDefaultMaxTransferCountPerBatch};
40 uint32_t multi_worker_num = 1U;42 uint32_t multi_worker_num = 1U;
41 uint32_t multi_channel_split_batch_size = kDefaultSplitBatchSize;43 uint32_t multi_channel_split_batch_size = kDefaultSplitBatchSize;
42 bool is_lazy = false;44 bool is_lazy = false;
@@ -48,7 +50,7 @@ struct HandlerCreateArgs {
48 50 
49class ClientHandlerFactory {51class ClientHandlerFactory {
50 public:52 public:
51- static std::unique_ptr<IClientHandler> Create(const HandlerCreateArgs &args);53+ static Status Create(const HandlerCreateArgs &args, std::unique_ptr<IClientHandler> &out);
52};54};
53 55 
54} // namespace hixl56} // namespace hixl
@@ -11,6 +11,7 @@
11#include "engine/direct_client_handler.h"11#include "engine/direct_client_handler.h"
12#include "common/hixl_checker.h"12#include "common/hixl_checker.h"
13#include "common/hixl_log.h"13#include "common/hixl_log.h"
14+#include "common/transfer_config.h"
14#include "common/hixl_utils.h"15#include "common/hixl_utils.h"
15#include "engine/client_handler_config_helper.h"16#include "engine/client_handler_config_helper.h"
16#include "engine/endpoint_generator/endpoint_generator.h"17#include "engine/endpoint_generator/endpoint_generator.h"
@@ -22,6 +23,11 @@ DirectClientHandler::DirectClientHandler(HixlClientHandle handle, const std::str
22 23 
23Status DirectClientHandler::Create(const HandlerCreateArgs &args, std::unique_ptr<DirectClientHandler> &out) {24Status DirectClientHandler::Create(const HandlerCreateArgs &args, std::unique_ptr<DirectClientHandler> &out) {
24 const auto &pair = args.matched_pairs[0];25 const auto &pair = args.matched_pairs[0];
26+ if (pair.local.protocol == kProtocolHccs) {
27+ HIXL_CHK_BOOL_RET_STATUS(args.max_transfer_count_per_batch <= kMaxFixedQueueTransferCountPerBatch, PARAM_INVALID,
28+ "max_transfer_count_per_batch=%u exceeds HCCS range [1, %u]",
29+ args.max_transfer_count_per_batch, kMaxFixedQueueTransferCountPerBatch);
30+ }
25 EndpointDesc local_endpoint{};31 EndpointDesc local_endpoint{};
26 EndpointDesc remote_endpoint{};32 EndpointDesc remote_endpoint{};
27 HIXL_CHK_STATUS_RET(EndpointGenerator::ConvertToEndpointDesc(pair.local, local_endpoint));33 HIXL_CHK_STATUS_RET(EndpointGenerator::ConvertToEndpointDesc(pair.local, local_endpoint));
@@ -102,6 +102,7 @@ Status FabricMemEngine::InitTransferService() {
102 param.control_server = fabric_mem_control_server_.get();102 param.control_server = fabric_mem_control_server_.get();
103 param.aclrt_context = aclrt_context_;103 param.aclrt_context = aclrt_context_;
104 param.enable_aicpu_unfold = fabric_mem_config_.enable_aicpu_unfold;104 param.enable_aicpu_unfold = fabric_mem_config_.enable_aicpu_unfold;
105+ param.max_transfer_count_per_batch = fabric_mem_config_.max_transfer_count_per_batch;
105 if (fabric_mem_config_.enable_aicpu_unfold) {106 if (fabric_mem_config_.enable_aicpu_unfold) {
106 fabric_mem_transfer_service_ = std::make_shared<FabricMemAicpuTransferService>();107 fabric_mem_transfer_service_ = std::make_shared<FabricMemAicpuTransferService>();
107 } else {108 } else {
@@ -165,10 +166,15 @@ Status FabricMemEngine::ApplyFabricMemoryOptions(const HixlOptions &options) {
165 fabric_mem_config_.enabled = true;166 fabric_mem_config_.enabled = true;
166 fabric_mem_config_.enable_aicpu_unfold = true;167 fabric_mem_config_.enable_aicpu_unfold = true;
167 fabric_mem_config_.task_stream_num = 1U;168 fabric_mem_config_.task_stream_num = 1U;
169+ fabric_mem_config_.max_transfer_count_per_batch = kDefaultMaxTransferCountPerBatch;
168 auto grc = options.GlobalResourceCfg();170 auto grc = options.GlobalResourceCfg();
169 if (!grc.has_value()) {171 if (!grc.has_value()) {
170 return SUCCESS;172 return SUCCESS;
171 }173 }
174+ HIXL_CHK_BOOL_RET_STATUS(grc->transfer_config.max_transfer_count_per_batch <= kMaxFixedQueueTransferCountPerBatch,
175+ PARAM_INVALID, "[FabricMemEngine] max_transfer_count_per_batch must be in [1, %u], got %u.",
176+ kMaxFixedQueueTransferCountPerBatch, grc->transfer_config.max_transfer_count_per_batch);
177+ fabric_mem_config_.max_transfer_count_per_batch = grc->transfer_config.max_transfer_count_per_batch;
172 if (grc->fabric_memory.max_capacity.has_value()) {178 if (grc->fabric_memory.max_capacity.has_value()) {
173 fabric_mem_config_.capacity_tb = *grc->fabric_memory.max_capacity;179 fabric_mem_config_.capacity_tb = *grc->fabric_memory.max_capacity;
174 fabric_mem_config_.has_capacity_tb = true;180 fabric_mem_config_.has_capacity_tb = true;
@@ -90,6 +90,7 @@ Status HixlClient::Initialize(const std::vector<EndpointConfig> &local_endpoint_
90 std::move(matched_pairs),90 std::move(matched_pairs),
91 qos_,91 qos_,
92 max_active_channels_,92 max_active_channels_,
93+ max_transfer_count_per_batch_,
93 multi_worker_num_,94 multi_worker_num_,
94 multi_channel_split_batch_size_,95 multi_channel_split_batch_size_,
95 is_lazy,96 is_lazy,
@@ -97,7 +98,8 @@ Status HixlClient::Initialize(const std::vector<EndpointConfig> &local_endpoint_
97 ctrl_socket_,98 ctrl_socket_,
98 local_engine_,99 local_engine_,
99 remote_engine_};100 remote_engine_};
100- client_handler_ = ClientHandlerFactory::Create(args);101+ HIXL_CHK_STATUS_RET(ClientHandlerFactory::Create(args, client_handler_),
102+ "ClientHandlerFactory create handler failed");
101 HIXL_CHECK_NOTNULL(client_handler_, "ClientHandlerFactory create handler failed");103 HIXL_CHECK_NOTNULL(client_handler_, "ClientHandlerFactory create handler failed");
102 HIXL_DISMISS_GUARD(close_ctrl_socket);104 HIXL_DISMISS_GUARD(close_ctrl_socket);
103 return SUCCESS;105 return SUCCESS;
@@ -20,6 +20,7 @@
20#include "cs/hixl_cs.h"20#include "cs/hixl_cs.h"
21#include "common/hixl_inner_types.h"21#include "common/hixl_inner_types.h"
22#include "common/ctrl_msg.h"22#include "common/ctrl_msg.h"
23+#include "common/transfer_config.h"
23#include "engine/client_handler.h"24#include "engine/client_handler.h"
24#include "engine/client_handler_factory.h"25#include "engine/client_handler_factory.h"
25 26 
@@ -34,6 +35,7 @@ struct ClientConfig {
34 uint32_t timeout_ms;35 uint32_t timeout_ms;
35 std::optional<uint8_t> qos;36 std::optional<uint8_t> qos;
36 std::optional<uint32_t> max_active_channels;37 std::optional<uint32_t> max_active_channels;
38+ uint32_t max_transfer_count_per_batch{kDefaultMaxTransferCountPerBatch};
37 uint32_t multi_worker_num = 1U;39 uint32_t multi_worker_num = 1U;
38 uint32_t multi_channel_split_batch_size = kDefaultSplitBatchSize;40 uint32_t multi_channel_split_batch_size = kDefaultSplitBatchSize;
39 bool is_lazy = false;41 bool is_lazy = false;
@@ -55,6 +57,7 @@ class HixlClient {
55 rdma_sl_(config.rdma_sl),57 rdma_sl_(config.rdma_sl),
56 qos_(config.qos),58 qos_(config.qos),
57 max_active_channels_(config.max_active_channels),59 max_active_channels_(config.max_active_channels),
60+ max_transfer_count_per_batch_(config.max_transfer_count_per_batch),
58 multi_worker_num_(config.multi_worker_num),61 multi_worker_num_(config.multi_worker_num),
59 multi_channel_split_batch_size_(config.multi_channel_split_batch_size) {}62 multi_channel_split_batch_size_(config.multi_channel_split_batch_size) {}
60 ~HixlClient() = default;63 ~HixlClient() = default;
@@ -151,6 +154,7 @@ class HixlClient {
151 std::map<TransferReq, TransferInfo> req_map_;154 std::map<TransferReq, TransferInfo> req_map_;
152 std::optional<uint8_t> qos_;155 std::optional<uint8_t> qos_;
153 std::optional<uint32_t> max_active_channels_;156 std::optional<uint32_t> max_active_channels_;
157+ uint32_t max_transfer_count_per_batch_{kDefaultMaxTransferCountPerBatch};
154 uint32_t multi_worker_num_{1U};158 uint32_t multi_worker_num_{1U};
155 uint32_t multi_channel_split_batch_size_{kDefaultSplitBatchSize};159 uint32_t multi_channel_split_batch_size_{kDefaultSplitBatchSize};
156};160};
@@ -76,6 +76,7 @@ Status HixlEngine::Initialize(const HixlOptions &options) {
76 listen_port = global_resource_config->comm_resource_config.listen_port;76 listen_port = global_resource_config->comm_resource_config.listen_port;
77 qos_ = global_resource_config->comm_resource_config.qos;77 qos_ = global_resource_config->comm_resource_config.qos;
78 max_active_channels_ = global_resource_config->comm_resource_config.max_active_channels;78 max_active_channels_ = global_resource_config->comm_resource_config.max_active_channels;
79+ max_transfer_count_per_batch_ = global_resource_config->transfer_config.max_transfer_count_per_batch;
79 multi_worker_num_ = global_resource_config->comm_resource_config.multi_worker_num.value_or(1U);80 multi_worker_num_ = global_resource_config->comm_resource_config.multi_worker_num.value_or(1U);
80 multi_channel_split_batch_size_ =81 multi_channel_split_batch_size_ =
81 global_resource_config->comm_resource_config.multi_channel_split_batch_size.value_or(kDefaultSplitBatchSize);82 global_resource_config->comm_resource_config.multi_channel_split_batch_size.value_or(kDefaultSplitBatchSize);
@@ -83,6 +84,7 @@ Status HixlEngine::Initialize(const HixlOptions &options) {
83 listen_port.reset();84 listen_port.reset();
84 qos_.reset();85 qos_.reset();
85 max_active_channels_.reset();86 max_active_channels_.reset();
87+ max_transfer_count_per_batch_ = kDefaultMaxTransferCountPerBatch;
86 multi_worker_num_ = 1U;88 multi_worker_num_ = 1U;
87 multi_channel_split_batch_size_ = kDefaultSplitBatchSize;89 multi_channel_split_batch_size_ = kDefaultSplitBatchSize;
88 }90 }
@@ -375,6 +377,7 @@ void HixlEngine::FillClientConfigFields(const AscendString &remote_engine, Clien
375 config.timeout_ms = static_cast<uint32_t>(timeout_in_millis);377 config.timeout_ms = static_cast<uint32_t>(timeout_in_millis);
376 config.qos = qos_;378 config.qos = qos_;
377 config.max_active_channels = max_active_channels_;379 config.max_active_channels = max_active_channels_;
380+ config.max_transfer_count_per_batch = max_transfer_count_per_batch_;
378 config.is_lazy = is_lazy;381 config.is_lazy = is_lazy;
379 config.multi_worker_num = multi_worker_num_;382 config.multi_worker_num = multi_worker_num_;
380 config.multi_channel_split_batch_size = multi_channel_split_batch_size_;383 config.multi_channel_split_batch_size = multi_channel_split_batch_size_;
@@ -23,6 +23,7 @@
23#include "hixl/hixl_types.h"23#include "hixl/hixl_types.h"
24#include "common/hixl_inner_types.h"24#include "common/hixl_inner_types.h"
25#include "common/optional_aclrt_context.h"25#include "common/optional_aclrt_context.h"
26+#include "common/transfer_config.h"
26 27 
27namespace hixl {28namespace hixl {
28class HixlEngine : public hixl::Engine {29class HixlEngine : public hixl::Engine {
@@ -187,6 +188,7 @@ class HixlEngine : public hixl::Engine {
187 std::atomic<bool> auto_connect_{false};188 std::atomic<bool> auto_connect_{false};
188 std::optional<uint8_t> qos_;189 std::optional<uint8_t> qos_;
189 std::optional<uint32_t> max_active_channels_;190 std::optional<uint32_t> max_active_channels_;
191+ uint32_t max_transfer_count_per_batch_{kDefaultMaxTransferCountPerBatch};
190 uint32_t multi_worker_num_{1U};192 uint32_t multi_worker_num_{1U};
191 uint32_t multi_channel_split_batch_size_{kDefaultSplitBatchSize};193 uint32_t multi_channel_split_batch_size_{kDefaultSplitBatchSize};
192 OptionalAclrtContext aclrt_context_;194 OptionalAclrtContext aclrt_context_;
@@ -27,6 +27,7 @@
27#include "common/hixl_utils.h"27#include "common/hixl_utils.h"
28#include "common/json_utils.h"28#include "common/json_utils.h"
29#include "common/scope_guard.h"29#include "common/scope_guard.h"
30+#include "common/transfer_config.h"
30#include "fabric_mem/fabric_mem_config.h"31#include "fabric_mem/fabric_mem_config.h"
31 32 
32namespace hixl {33namespace hixl {
@@ -225,6 +226,22 @@ Status ParseCommResourceConfig(const nlohmann::json &json, CommResourceConfigDes
225 return SUCCESS;226 return SUCCESS;
226}227}
227 228 
229+Status ParseTransferConfig(const nlohmann::json &json, TransferConfig &cfg) {
230+ constexpr const char *kMaxTransferCountKey = "transfer_config.max_transfer_count_per_batch";
231+ if (!json.contains(kMaxTransferCountKey)) {
232+ return SUCCESS;
233+ }
234+ const auto &value = json.at(kMaxTransferCountKey);
235+ HIXL_CHK_BOOL_RET_STATUS((value.is_number_integer() || value.is_number_unsigned()) || value.is_string(),
236+ PARAM_INVALID, "%s must be an integer or decimal integer string", kMaxTransferCountKey);
237+ const int64_t count = JsonToNumber<int64_t>(value);
238+ HIXL_CHK_BOOL_RET_STATUS(count >= 1 && count <= static_cast<int64_t>(kMaxTransferCountPerBatch), PARAM_INVALID,
239+ "%s must be in [1, %u], got %lld", kMaxTransferCountKey, kMaxTransferCountPerBatch,
240+ static_cast<long long>(count));
241+ cfg.max_transfer_count_per_batch = static_cast<uint32_t>(count);
242+ return SUCCESS;
243+}
244+ 
228Status ParseLocalCommResPath(const nlohmann::json &json, GlobalResourceConfig &cfg) {245Status ParseLocalCommResPath(const nlohmann::json &json, GlobalResourceConfig &cfg) {
229 if (!json.contains("local_comm_res_path")) {246 if (!json.contains("local_comm_res_path")) {
230 return SUCCESS;247 return SUCCESS;
@@ -295,6 +312,7 @@ Status ParseGlobalResourceConfigJson(const nlohmann::json &json, GlobalResourceC
295 HIXL_CHK_STATUS_RET(ParseFabricMemoryConfig(json, cfg.fabric_memory), "Failed to parse FabricMemoryConfig");312 HIXL_CHK_STATUS_RET(ParseFabricMemoryConfig(json, cfg.fabric_memory), "Failed to parse FabricMemoryConfig");
296 HIXL_CHK_STATUS_RET(ParseConnectPoolConfig(json, cfg.connect_pool), "Failed to parse ConnectPoolConfig");313 HIXL_CHK_STATUS_RET(ParseConnectPoolConfig(json, cfg.connect_pool), "Failed to parse ConnectPoolConfig");
297 HIXL_CHK_STATUS_RET(ParseCommResourceConfig(json, cfg.comm_resource_config), "Failed to parse CommResourceConfig");314 HIXL_CHK_STATUS_RET(ParseCommResourceConfig(json, cfg.comm_resource_config), "Failed to parse CommResourceConfig");
315+ HIXL_CHK_STATUS_RET(ParseTransferConfig(json, cfg.transfer_config), "Failed to parse TransferConfig");
298 HIXL_CHK_STATUS_RET(ParseLocalCommResPath(json, cfg), "Failed to parse local_comm_res_path");316 HIXL_CHK_STATUS_RET(ParseLocalCommResPath(json, cfg), "Failed to parse local_comm_res_path");
299 HIXL_CHK_STATUS_RET(ParseTopoFilePath(json, cfg), "Failed to parse topo_file_path");317 HIXL_CHK_STATUS_RET(ParseTopoFilePath(json, cfg), "Failed to parse topo_file_path");
300 return SUCCESS;318 return SUCCESS;
@@ -21,6 +21,7 @@
21 21 
22#include "hixl/hixl_types.h"22#include "hixl/hixl_types.h"
23#include "adxl/adxl_types.h"23#include "adxl/adxl_types.h"
24+#include "common/transfer_config.h"
24 25 
25namespace hixl {26namespace hixl {
26 27 
@@ -45,10 +46,15 @@ struct CommResourceConfigDesc {
45 std::optional<uint32_t> multi_channel_split_batch_size;46 std::optional<uint32_t> multi_channel_split_batch_size;
46};47};
47 48 
49+struct TransferConfig {
50+ uint32_t max_transfer_count_per_batch{kDefaultMaxTransferCountPerBatch};
51+};
52+ 
48struct GlobalResourceConfig {53struct GlobalResourceConfig {
49 FabricMemoryConfig fabric_memory;54 FabricMemoryConfig fabric_memory;
50 ConnectPoolConfig connect_pool;55 ConnectPoolConfig connect_pool;
51 CommResourceConfigDesc comm_resource_config;56 CommResourceConfigDesc comm_resource_config;
57+ TransferConfig transfer_config;
52 std::optional<std::string> local_comm_res_path; // local_comm_res JSON file path58 std::optional<std::string> local_comm_res_path; // local_comm_res JSON file path
53 std::optional<std::string> topo_file_path; // hardware topo JSON path for auto-gen59 std::optional<std::string> topo_file_path; // hardware topo JSON path for auto-gen
54};60};
@@ -37,9 +37,16 @@ constexpr uint32_t kSyncContextKernelTimeoutMs = 10U * 1000U;
37constexpr uint32_t kSyncContextRetryTimeoutMs = 30U * 1000U;37constexpr uint32_t kSyncContextRetryTimeoutMs = 30U * 1000U;
38constexpr uint32_t kSyncContextRetryIntervalMs = 100U;38constexpr uint32_t kSyncContextRetryIntervalMs = 100U;
39 39 
40-Status CountKernelLaunches(size_t desc_count, size_t &launch_count) {40+Status CountKernelLaunches(size_t desc_count, size_t batch_size, size_t &launch_count) {
41- HIXL_CHK_BOOL_RET_STATUS(desc_count > 0U, PARAM_INVALID, "FabricMem AICPU launch count inputs are invalid.");41+ HIXL_CHK_BOOL_RET_STATUS(desc_count > 0U && batch_size > 0U, PARAM_INVALID,
42- launch_count = (desc_count + kMaxDescriptorsPerKernelLaunch - 1U) / kMaxDescriptorsPerKernelLaunch;42+ "FabricMem AICPU launch count inputs are invalid.");
43+ const size_t full_batch_count = desc_count / batch_size;
44+ const size_t tail_desc_count = desc_count % batch_size;
45+ const size_t kernels_per_full_batch = batch_size / kMaxDescriptorsPerKernelLaunch +
46+ static_cast<size_t>(batch_size % kMaxDescriptorsPerKernelLaunch != 0U);
47+ const size_t tail_kernel_count = tail_desc_count / kMaxDescriptorsPerKernelLaunch +
48+ static_cast<size_t>(tail_desc_count % kMaxDescriptorsPerKernelLaunch != 0U);
49+ launch_count = full_batch_count * kernels_per_full_batch + tail_kernel_count;
43 return SUCCESS;50 return SUCCESS;
44}51}
45 52 
@@ -109,19 +116,25 @@ Status FabricMemAicpuDispatcher::InitializeRtsqDevice() {
109 return SUCCESS;116 return SUCCESS;
110}117}
111 118 
112-Status FabricMemAicpuDispatcher::Initialize(int32_t device_id) {119+Status FabricMemAicpuDispatcher::Initialize(int32_t device_id, uint32_t max_transfer_count_per_batch) {
113 HIXL_CHK_BOOL_RET_STATUS(device_id >= 0, PARAM_INVALID, "FabricMem AICPU device id must be non-negative.");120 HIXL_CHK_BOOL_RET_STATUS(device_id >= 0, PARAM_INVALID, "FabricMem AICPU device id must be non-negative.");
121+ HIXL_CHK_BOOL_RET_STATUS(
122+ max_transfer_count_per_batch >= 1U && max_transfer_count_per_batch <= kMaxFixedQueueTransferCountPerBatch,
123+ PARAM_INVALID, "FabricMem AICPU max_transfer_count_per_batch must be in [1, %u], got %u.",
124+ kMaxFixedQueueTransferCountPerBatch, max_transfer_count_per_batch);
114 std::lock_guard<std::mutex> lock(lifecycle_mutex_);125 std::lock_guard<std::mutex> lock(lifecycle_mutex_);
115 if (initialized_.load(std::memory_order_acquire)) {126 if (initialized_.load(std::memory_order_acquire)) {
116- if (device_id_ == device_id) {127+ if (device_id_ == device_id && max_transfer_count_per_batch_ == max_transfer_count_per_batch) {
117 return SUCCESS;128 return SUCCESS;
118 }129 }
119 HIXL_LOGE(PARAM_INVALID,130 HIXL_LOGE(PARAM_INVALID,
120- "FabricMem AICPU dispatcher already initialized on device:%d, reject re-init on device:%d.", device_id_,131+ "FabricMem AICPU dispatcher configuration cannot change after initialization, old_device:%d, "
121- device_id);132+ "new_device:%d, old_batch:%u, new_batch:%u.",
133+ device_id_, device_id, max_transfer_count_per_batch_, max_transfer_count_per_batch);
122 return PARAM_INVALID;134 return PARAM_INVALID;
123 }135 }
124 device_id_ = device_id;136 device_id_ = device_id;
137+ max_transfer_count_per_batch_ = max_transfer_count_per_batch;
125 if (InitializeRtsqDevice() != SUCCESS) {138 if (InitializeRtsqDevice() != SUCCESS) {
126 device_id_ = -1;139 device_id_ = -1;
127 return UNSUPPORTED;140 return UNSUPPORTED;
@@ -397,7 +410,7 @@ Status FabricMemAicpuDispatcher::LaunchOneDescriptorBatch(const AsyncSlot &slot,
397 // SQEs plus an optional NotifyRecord.410 // SQEs plus an optional NotifyRecord.
398 const size_t next_task_count = tasks_since_notify + count;411 const size_t next_task_count = tasks_since_notify + count;
399 const bool transfer_tail = begin + count == total_descs;412 const bool transfer_tail = begin + count == total_descs;
400- const bool emit_notify = next_task_count >= kFabricMemMaxInFlightRtsqTasks || transfer_tail;413+ const bool emit_notify = next_task_count >= max_transfer_count_per_batch_ || transfer_tail;
401 FabricMemAicpuKernelParam param{};414 FabricMemAicpuKernelParam param{};
402 param.desc_addr = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(descriptor_buffer) +415 param.desc_addr = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(descriptor_buffer) +
403 begin * sizeof(FabricMemAicpuTransferDesc));416 begin * sizeof(FabricMemAicpuTransferDesc));
@@ -443,7 +456,9 @@ Status FabricMemAicpuDispatcher::LaunchDescriptorBatches(const AsyncSlot &slot,
443 size_t begin = 0U;456 size_t begin = 0U;
444 size_t tasks_since_notify = 0U;457 size_t tasks_since_notify = 0U;
445 while (begin < descs.size()) {458 while (begin < descs.size()) {
446- const size_t count = std::min(static_cast<size_t>(kMaxDescriptorsPerKernelLaunch), descs.size() - begin);459+ const size_t batch_remaining = max_transfer_count_per_batch_ - tasks_since_notify;
460+ const size_t count =
461+ std::min({static_cast<size_t>(kMaxDescriptorsPerKernelLaunch), batch_remaining, descs.size() - begin});
447 HIXL_CHK_STATUS_RET(462 HIXL_CHK_STATUS_RET(
448 LaunchOneDescriptorBatch(slot, function, direction, descriptor_buffer, status_buffer, kernel_args_buffer, begin,463 LaunchOneDescriptorBatch(slot, function, direction, descriptor_buffer, status_buffer, kernel_args_buffer, begin,
449 count, descs.size(), rtsq_timeout_ms, status_idx, tasks_since_notify),464 count, descs.size(), rtsq_timeout_ms, status_idx, tasks_since_notify),
@@ -470,7 +485,7 @@ Status FabricMemAicpuDispatcher::Submit(const AsyncSlot &slot, TransferOp operat
470 HIXL_CHK_STATUS_RET(BuildDeviceDescriptors(operation, op_descs, device_descs, direction),485 HIXL_CHK_STATUS_RET(BuildDeviceDescriptors(operation, op_descs, device_descs, direction),
471 "Build FabricMem AICPU device descriptors failed.");486 "Build FabricMem AICPU device descriptors failed.");
472 size_t launch_count = 0U;487 size_t launch_count = 0U;
473- HIXL_CHK_STATUS_RET(CountKernelLaunches(device_descs.size(), launch_count),488+ HIXL_CHK_STATUS_RET(CountKernelLaunches(device_descs.size(), max_transfer_count_per_batch_, launch_count),
474 "Count FabricMem AICPU kernel launches failed.");489 "Count FabricMem AICPU kernel launches failed.");
475 490 
476 HIXL_CHK_BOOL_RET_STATUS(IsInitialized(), FAILED, "FabricMem AICPU dispatcher is not initialized.");491 HIXL_CHK_BOOL_RET_STATUS(IsInitialized(), FAILED, "FabricMem AICPU dispatcher is not initialized.");
@@ -18,6 +18,7 @@
18 18 
19#include "acl/acl_rt.h"19#include "acl/acl_rt.h"
20#include "common/hixl_inner_types.h"20#include "common/hixl_inner_types.h"
21+#include "common/transfer_config.h"
21#include "fabric_mem/fabric_mem_types.h"22#include "fabric_mem/fabric_mem_types.h"
22 23 
23namespace hixl {24namespace hixl {
@@ -38,7 +39,7 @@ class FabricMemAicpuDispatcher {
38 FabricMemAicpuDispatcher(const FabricMemAicpuDispatcher &) = delete;39 FabricMemAicpuDispatcher(const FabricMemAicpuDispatcher &) = delete;
39 FabricMemAicpuDispatcher &operator=(const FabricMemAicpuDispatcher &) = delete;40 FabricMemAicpuDispatcher &operator=(const FabricMemAicpuDispatcher &) = delete;
40 41 
41- Status Initialize(int32_t device_id);42+ Status Initialize(int32_t device_id, uint32_t max_transfer_count_per_batch);
42 void Finalize();43 void Finalize();
43 bool IsInitialized() const;44 bool IsInitialized() const;
44 45 
@@ -90,6 +91,7 @@ class FabricMemAicpuDispatcher {
90 int32_t device_id_{-1};91 int32_t device_id_{-1};
91 // Physical/host device id passed to AICPU as param.device_id.92 // Physical/host device id passed to AICPU as param.device_id.
92 uint32_t rtsq_device_id_{0U};93 uint32_t rtsq_device_id_{0U};
94+ uint32_t max_transfer_count_per_batch_{kDefaultMaxTransferCountPerBatch};
93 aclrtBinHandle binary_handle_{nullptr};95 aclrtBinHandle binary_handle_{nullptr};
94 aclrtFuncHandle batch_read_{nullptr};96 aclrtFuncHandle batch_read_{nullptr};
95 aclrtFuncHandle batch_write_{nullptr};97 aclrtFuncHandle batch_write_{nullptr};
@@ -34,7 +34,7 @@ Status FabricMemAicpuTransferService::Initialize(const FabricMemTransferServiceI
34 HIXL_CHK_BOOL_RET_STATUS(param.task_stream_num == 1U, PARAM_INVALID,34 HIXL_CHK_BOOL_RET_STATUS(param.task_stream_num == 1U, PARAM_INVALID,
35 "enable_aicpu_unfold requires task_stream_num=1, got %zu.", param.task_stream_num);35 "enable_aicpu_unfold requires task_stream_num=1, got %zu.", param.task_stream_num);
36 HIXL_DISMISSABLE_GUARD(fail_guard, ([this]() { Finalize(); }));36 HIXL_DISMISSABLE_GUARD(fail_guard, ([this]() { Finalize(); }));
37- const Status dispatcher_status = aicpu_dispatcher_.Initialize(param.device_id);37+ const Status dispatcher_status = aicpu_dispatcher_.Initialize(param.device_id, param.max_transfer_count_per_batch);
38 if (dispatcher_status != SUCCESS) {38 if (dispatcher_status != SUCCESS) {
39 HIXL_LOGE(UNSUPPORTED, "FabricMem AICPU unfold requested but unavailable on device:%d.", param.device_id);39 HIXL_LOGE(UNSUPPORTED, "FabricMem AICPU unfold requested but unavailable on device:%d.", param.device_id);
40 return UNSUPPORTED;40 return UNSUPPORTED;
@@ -13,6 +13,9 @@
13 13 
14#include <cstddef>14#include <cstddef>
15 15 
16+#include "hixl/hixl_types.h"
17+#include "common/transfer_config.h"
18+ 
16namespace hixl {19namespace hixl {
17constexpr size_t kMinFabricMemStartAddrTB = 0UL;20constexpr size_t kMinFabricMemStartAddrTB = 0UL;
18constexpr size_t kMaxFabricMemStartAddrTB = 1024UL;21constexpr size_t kMaxFabricMemStartAddrTB = 1024UL;
@@ -27,6 +30,7 @@ struct FabricMemConfig {
27 size_t task_stream_num = 1U;30 size_t task_stream_num = 1U;
28 size_t max_stream_num = 512U;31 size_t max_stream_num = 512U;
29 bool enable_aicpu_unfold = true;32 bool enable_aicpu_unfold = true;
33+ uint32_t max_transfer_count_per_batch = kDefaultMaxTransferCountPerBatch;
30};34};
31} // namespace hixl35} // namespace hixl
32 36 
@@ -272,7 +272,7 @@ void FabricMemHostTransferService::CleanupAsyncTransfer(const TransferReq &req)
272}272}
273 273 
274Status FabricMemHostTransferService::ProcessCopyWithAsync(const AsyncSlot &slot, TransferOp operation,274Status FabricMemHostTransferService::ProcessCopyWithAsync(const AsyncSlot &slot, TransferOp operation,
275- const std::vector<TransferOpDesc> &op_descs) {275+ const std::vector<TransferOpDesc> &op_descs) const {
276 HIXL_CHK_BOOL_RET_STATUS(!slot.streams.empty(), PARAM_INVALID, "Fabric mem copy streams cannot be empty.");276 HIXL_CHK_BOOL_RET_STATUS(!slot.streams.empty(), PARAM_INVALID, "Fabric mem copy streams cannot be empty.");
277 const size_t stream_count = slot.streams.size();277 const size_t stream_count = slot.streams.size();
278 size_t stream_idx = 0U;278 size_t stream_idx = 0U;
@@ -32,8 +32,8 @@ class FabricMemHostTransferService : public FabricMemTransferService {
32 AsyncTransferPollInfo *info = nullptr) override;32 AsyncTransferPollInfo *info = nullptr) override;
33 void CleanupAsyncTransfer(const TransferReq &req) override;33 void CleanupAsyncTransfer(const TransferReq &req) override;
34 34 
35- static Status ProcessCopyWithAsync(const AsyncSlot &slot, TransferOp operation,35+ Status ProcessCopyWithAsync(const AsyncSlot &slot, TransferOp operation,
36- const std::vector<TransferOpDesc> &op_descs);36+ const std::vector<TransferOpDesc> &op_descs) const;
37 37 
38 private:38 private:
39 Status IssueSyncCopy(const std::shared_ptr<FabricMemChannel> &channel, const AsyncSlot &slot,39 Status IssueSyncCopy(const std::shared_ptr<FabricMemChannel> &channel, const AsyncSlot &slot,
@@ -129,6 +129,10 @@ Status FabricMemTransferService::InitCommon(const FabricMemTransferServiceInitPa
129 "Invalid fabric mem transfer service initialization parameters.");129 "Invalid fabric mem transfer service initialization parameters.");
130 const size_t task_stream_num = param.task_stream_num;130 const size_t task_stream_num = param.task_stream_num;
131 HIXL_CHK_BOOL_RET_STATUS(task_stream_num > 0, PARAM_INVALID, "task_stream_num must be greater than zero.");131 HIXL_CHK_BOOL_RET_STATUS(task_stream_num > 0, PARAM_INVALID, "task_stream_num must be greater than zero.");
132+ HIXL_CHK_BOOL_RET_STATUS(param.max_transfer_count_per_batch >= 1U &&
133+ param.max_transfer_count_per_batch <= kMaxFixedQueueTransferCountPerBatch,
134+ PARAM_INVALID, "max_transfer_count_per_batch must be in [1, %u], got %u.",
135+ kMaxFixedQueueTransferCountPerBatch, param.max_transfer_count_per_batch);
132 // An AICPU slot pairs every control stream with a device-only RTSQ worker stream, so it costs136 // An AICPU slot pairs every control stream with a device-only RTSQ worker stream, so it costs
133 // twice the streams a host slot does and the pool must be sized accordingly.137 // twice the streams a host slot does and the pool must be sized accordingly.
134 const size_t streams_per_slot = enable_aicpu_unfold ? (task_stream_num * 2U) : task_stream_num;138 const size_t streams_per_slot = enable_aicpu_unfold ? (task_stream_num * 2U) : task_stream_num;
@@ -136,6 +140,7 @@ Status FabricMemTransferService::InitCommon(const FabricMemTransferServiceInitPa
136 "max_stream_num must leave room for at least one slot's streams.");140 "max_stream_num must leave room for at least one slot's streams.");
137 device_id_ = param.device_id;141 device_id_ = param.device_id;
138 task_stream_num_ = task_stream_num;142 task_stream_num_ = task_stream_num;
143+ max_transfer_count_per_batch_ = param.max_transfer_count_per_batch;
139 max_stream_num_ = param.max_stream_num;144 max_stream_num_ = param.max_stream_num;
140 statistic_ = param.statistic;145 statistic_ = param.statistic;
141 local_memory_ = param.local_memory;146 local_memory_ = param.local_memory;
@@ -26,6 +26,7 @@
26#include "fabric_mem/fabric_mem_statistic.h"26#include "fabric_mem/fabric_mem_statistic.h"
27#include "fabric_mem/fabric_mem_types.h"27#include "fabric_mem/fabric_mem_types.h"
28#include "hixl/hixl_types.h"28#include "hixl/hixl_types.h"
29+#include "common/transfer_config.h"
29 30 
30namespace hixl {31namespace hixl {
31 32 
@@ -42,6 +43,7 @@ struct FabricMemTransferServiceInitParam {
42 aclrtContext aclrt_context{nullptr};43 aclrtContext aclrt_context{nullptr};
43 // Selects FabricMemAicpuTransferService when true; FabricMemHostTransferService otherwise.44 // Selects FabricMemAicpuTransferService when true; FabricMemHostTransferService otherwise.
44 bool enable_aicpu_unfold{false};45 bool enable_aicpu_unfold{false};
46+ uint32_t max_transfer_count_per_batch{kDefaultMaxTransferCountPerBatch};
45};47};
46 48 
47// Base for fabric_mem transfer services. Owns the channel manager and slot pool; concrete49// Base for fabric_mem transfer services. Owns the channel manager and slot pool; concrete
@@ -121,6 +123,7 @@ class FabricMemTransferService {
121 int32_t device_id_{-1};123 int32_t device_id_{-1};
122 size_t max_stream_num_{0};124 size_t max_stream_num_{0};
123 size_t task_stream_num_{0};125 size_t task_stream_num_{0};
126+ uint32_t max_transfer_count_per_batch_{kDefaultMaxTransferCountPerBatch};
124 FabricMemStatistic *statistic_{nullptr};127 FabricMemStatistic *statistic_{nullptr};
125 FabricMemLocalMemory *local_memory_{nullptr};128 FabricMemLocalMemory *local_memory_{nullptr};
126 void *dev_const_one_{nullptr};129 void *dev_const_one_{nullptr};
@@ -25,7 +25,8 @@ static const uint32_t COMM_ADDR_EID_LEN = 16U;
25static const uint32_t HCOMM_CHANNEL_MAGIC_WORD = 0x0fcf0f0fU;25static const uint32_t HCOMM_CHANNEL_MAGIC_WORD = 0x0fcf0f0fU;
26static const uint32_t HCOMM_CHANNEL_VERSION_ONE = 1U;26static const uint32_t HCOMM_CHANNEL_VERSION_ONE = 1U;
27/** ABI v3:相比 v1 增加 uint32_t qos 与 const char *channelName(channel 业务匹配标识) */27/** ABI v3:相比 v1 增加 uint32_t qos 与 const char *channelName(channel 业务匹配标识) */
28-static const uint32_t HCOMM_CHANNEL_VERSION = 3U;28+/** ABI v4:相比 v3 增加 roceAttr.srcPortList(QP 源端口号,union 内字段,sizeof 不变) */
29+static const uint32_t HCOMM_CHANNEL_VERSION = 4U;
29 30 
30/// channelName标识最大长度(字节)31/// channelName标识最大长度(字节)
31static const uint32_t HCOMM_CHANNEL_NAME_MAX_LEN = 191U;32static const uint32_t HCOMM_CHANNEL_NAME_MAX_LEN = 191U;
@@ -215,10 +216,19 @@ typedef struct {
215 uint32_t retryInterval; ///< 重传间隔(ms)216 uint32_t retryInterval; ///< 重传间隔(ms)
216 uint8_t tc; ///< 流量类别(QoS)217 uint8_t tc; ///< 流量类别(QoS)
217 uint8_t sl; ///< 服务等级(QoS)218 uint8_t sl; ///< 服务等级(QoS)
219+ uint32_t qpThreshold; ///< 多QP场景下,每个QP最小数据量(B)
220+ uint32_t cqAttrFlags; ///< CQ属性标志位,默认0
221+ uint16_t *srcPortList; ///< QP源端口号,用于哈希分流
222+ uint32_t sqDepth; ///< SQ队列深度,0/0xffffffff表示使用默认值
223+ uint32_t scqDepth; ///< SCQ队列深度,0/0xffffffff表示使用默认值
218 } roceAttr;224 } roceAttr;
219 struct {225 struct {
220 uint32_t qos; ///< HCCS QoS226 uint32_t qos; ///< HCCS QoS
221 } hccsAttr;227 } hccsAttr;
228+ struct {
229+ uint32_t sqDepth; ///< UB SQ队列深度,0/0xffffffff表示使用默认值
230+ uint32_t scqDepth; ///< UB SCQ队列深度,0/0xffffffff表示使用默认值
231+ } ubAttr;
222 };232 };
223 uint32_t qos;233 uint32_t qos;
224 const char *channelName; ///< channel业务匹配标识,两端建channel需标识相同234 const char *channelName; ///< channel业务匹配标识,两端建channel需标识相同
@@ -365,6 +375,11 @@ static inline HcommResult HcommChannelDescInit(HcommChannelDesc *channelDesc, ui
365 channelDesc->socket = NULL;375 channelDesc->socket = NULL;
366 channelDesc->role = HCOMM_SOCKET_ROLE_RESERVED;376 channelDesc->role = HCOMM_SOCKET_ROLE_RESERVED;
367 channelDesc->port = 0;377 channelDesc->port = 0;
378+ channelDesc->roceAttr.qpThreshold = 0U;
379+ channelDesc->roceAttr.cqAttrFlags = 0U;
380+ channelDesc->roceAttr.srcPortList = NULL;
381+ channelDesc->roceAttr.sqDepth = 0U;
382+ channelDesc->roceAttr.scqDepth = 0U;
368 channelDesc->channelName = NULL;383 channelDesc->channelName = NULL;
369 if (EndpointDescInit(&channelDesc->remoteEndpoint, 1) != 0) {384 if (EndpointDescInit(&channelDesc->remoteEndpoint, 1) != 0) {
370 return hcommEInternal;385 return hcommEInternal;
@@ -10,6 +10,7 @@
10 10 
11#include <cstdint>11#include <cstdint>
12#include <cstring>12#include <cstring>
13+#include <limits>
13#include <arpa/inet.h>14#include <arpa/inet.h>
14#include "gtest/gtest.h"15#include "gtest/gtest.h"
15#include "hixl_cs_client.h"16#include "hixl_cs_client.h"
@@ -81,10 +82,12 @@ struct ImportedRemote {
81 uint32_t list_num = 0;82 uint32_t list_num = 0;
82};83};
83// 创建 HixlClient 连接84// 创建 HixlClient 连接
84-void CreateHixlClient(hixl::HixlCSClient &cli, const char *ip, uint32_t port) {85+void CreateHixlClient(hixl::HixlCSClient &cli, const char *ip, uint32_t port,
86+ const char *global_resource_config = nullptr) {
85 EndpointDesc src = MakeSrcEp();87 EndpointDesc src = MakeSrcEp();
86 EndpointDesc dst = MakeDstEp();88 EndpointDesc dst = MakeDstEp();
87- HixlClientConfig config{}; // 默认构造89+ HixlClientConfig config{};
90+ config.global_resource_config = global_resource_config;
88 HixlClientDesc desc{};91 HixlClientDesc desc{};
89 desc.server_ip = ip;92 desc.server_ip = ip;
90 desc.server_port = port;93 desc.server_port = port;
@@ -94,8 +97,9 @@ void CreateHixlClient(hixl::HixlCSClient &cli, const char *ip, uint32_t port) {
94}97}
95 98 
96// 封装:创建连接 + 导入远端内存99// 封装:创建连接 + 导入远端内存
97-void PrepareConnectionAndImport(hixl::HixlCSClient &cli, const char *client_ip, uint32_t port) {100+void PrepareConnectionAndImport(hixl::HixlCSClient &cli, const char *client_ip, uint32_t port,
98- CreateHixlClient(cli, client_ip, port);101+ const char *global_resource_config = nullptr) {
102+ CreateHixlClient(cli, client_ip, port, global_resource_config);
99 std::vector<HixlMemDesc> descs;103 std::vector<HixlMemDesc> descs;
100 descs.push_back(MakeRemoteDesc(kTransFlagNameDevice, &kTransFlagAddr, kFlagSizeBytes));104 descs.push_back(MakeRemoteDesc(kTransFlagNameDevice, &kTransFlagAddr, kFlagSizeBytes));
101 descs.push_back(MakeRemoteDesc("server_data", &kServerDataAddr, kBlockSizeBytes));105 descs.push_back(MakeRemoteDesc("server_data", &kServerDataAddr, kBlockSizeBytes));
@@ -127,6 +131,18 @@ class HixlCSClientFixture : public ::testing::Test {
127 }131 }
128};132};
129 133 
134+TEST(HcommChannelDescInitTest, InitializesRoceDefaults) {
135+ HcommChannelDesc channel_desc;
136+ 
137+ ASSERT_EQ(HcommChannelDescInit(&channel_desc, 1U), HCCL_SUCCESS);
138+ EXPECT_EQ(channel_desc.header.version, 4U);
139+ EXPECT_EQ(channel_desc.roceAttr.qpThreshold, 0U);
140+ EXPECT_EQ(channel_desc.roceAttr.cqAttrFlags, 0U);
141+ EXPECT_EQ(channel_desc.roceAttr.srcPortList, nullptr);
142+ EXPECT_EQ(channel_desc.roceAttr.sqDepth, 0U);
143+ EXPECT_EQ(channel_desc.roceAttr.scqDepth, 0U);
144+}
145+ 
130TEST_F(HixlCSClientFixture, RegMemAndUnRegMem) {146TEST_F(HixlCSClientFixture, RegMemAndUnRegMem) {
131 // 先创建本端 endpoint(Create 不依赖 socket 初始化以外的 HCCL)147 // 先创建本端 endpoint(Create 不依赖 socket 初始化以外的 HCCL)
132 const char *client_ip = "127.0.0.1";148 const char *client_ip = "127.0.0.1";
@@ -387,7 +403,7 @@ TEST_F(HixlCSClientFixture, MultipleBatchTransferAndCheckStatus) {
387 EXPECT_GE(query_handles.size(), 1U);403 EXPECT_GE(query_handles.size(), 1U);
388}404}
389 405 
390-// 测试传输重试逻辑:15个任务时,前10次正常返回,第11次触发重试406+// 测试传输重试逻辑:15个任务时,第10次触发重试
391// 重试后 HcommChannelFenceOnThread 会重置计数器,所以重试后的传输会成功407// 重试后 HcommChannelFenceOnThread 会重置计数器,所以重试后的传输会成功
392TEST_F(HixlCSClientFixture, BatchTransferWithRetryLogic) {408TEST_F(HixlCSClientFixture, BatchTransferWithRetryLogic) {
393 const char *client_ip = "127.0.0.1";409 const char *client_ip = "127.0.0.1";
@@ -396,6 +412,7 @@ TEST_F(HixlCSClientFixture, BatchTransferWithRetryLogic) {
396 412 
397 // 注册本地内存413 // 注册本地内存
398 RecordLocalMem(cli);414 RecordLocalMem(cli);
415+ SetTransferRetryThreshold(10U);
399 416 
400 // 创建15个传输任务417 // 创建15个传输任务
401 HixlOneSideOpDesc descs[15];418 HixlOneSideOpDesc descs[15];
@@ -403,9 +420,79 @@ TEST_F(HixlCSClientFixture, BatchTransferWithRetryLogic) {
403 descs[i] = {&kServerDataAddr, static_cast<void *>(&kClientBufAddr), 4};420 descs[i] = {&kServerDataAddr, static_cast<void *>(&kClientBufAddr), 4};
404 }421 }
405 void *query_handle = nullptr;422 void *query_handle = nullptr;
406- // 批量传输应该成功,因为重试逻辑会处理第11次开始的 HCCL_RETRY_REQUIRED423+ // 批量传输应该成功,因为重试逻辑会处理 HCCL_RETRY_REQUIRED
407 EXPECT_EQ(cli.BatchTransferAsync(false, 15, descs, &query_handle), SUCCESS);424 EXPECT_EQ(cli.BatchTransferAsync(false, 15, descs, &query_handle), SUCCESS);
408 EXPECT_NE(query_handle, nullptr);425 EXPECT_NE(query_handle, nullptr);
426+ EXPECT_EQ(GetFenceCallCount(), 1U);
427+}
428+ 
429+TEST_F(HixlCSClientFixture, BatchTransferDoesNotFenceAtNormalBatchBoundary) {
430+ const char *client_ip = "127.0.0.1";
431+ uint32_t port = 22343;
432+ PrepareConnectionAndImport(cli, client_ip, port, R"({"transfer_config.max_transfer_count_per_batch":2})");
433+ RecordLocalMem(cli);
434+ 
435+ HixlOneSideOpDesc descs[] = {
436+ {&kServerDataAddr, static_cast<void *>(&kClientBufAddr), 4},
437+ {&kServerDataAddr, static_cast<void *>(&kClientBufAddr), 4},
438+ {&kServerDataAddr, static_cast<void *>(&kClientBufAddr), 4},
439+ {&kServerDataAddr, static_cast<void *>(&kClientBufAddr), 4},
440+ };
441+ void *query_handle = nullptr;
442+ ASSERT_EQ(cli.BatchTransferAsync(false, 4, descs, &query_handle), SUCCESS);
443+ EXPECT_NE(query_handle, nullptr);
444+ EXPECT_EQ(GetFenceCallCount(), 0U);
445+}
446+ 
447+TEST_F(HixlCSClientFixture, BatchTransferHostAsyncHandlesMaximumListNumWithoutChunkCountOverflow) {
448+ const char *client_ip = "127.0.0.1";
449+ uint32_t port = 22345;
450+ PrepareConnectionAndImport(cli, client_ip, port);
451+ RecordLocalMem(cli);
452+ 
453+ HixlOneSideOpDesc desc = {&kServerDataAddr, static_cast<void *>(&kClientBufAddr), 4};
454+ void *query_handle = nullptr;
455+ SetNextNbiFailure(HCCL_E_PARA);
456+ 
457+ EXPECT_EQ(cli.BatchTransferHostAsync(false, std::numeric_limits<uint32_t>::max(), &desc, &query_handle),
458+ PARAM_INVALID);
459+ EXPECT_EQ(query_handle, nullptr);
460+ EXPECT_EQ(GetNbiCallCount(), 1U);
461+}
462+ 
463+TEST_F(HixlCSClientFixture, BatchTransferHostAsyncRejectsEmptyListBeforeSubmittingWork) {
464+ const char *client_ip = "127.0.0.1";
465+ uint32_t port = 22346;
466+ PrepareConnectionAndImport(cli, client_ip, port);
467+ RecordLocalMem(cli);
468+ 
469+ HixlOneSideOpDesc desc = {&kServerDataAddr, static_cast<void *>(&kClientBufAddr), 4};
470+ void *query_handle = nullptr;
471+ 
472+ EXPECT_EQ(cli.BatchTransferHostAsync(false, 0U, &desc, &query_handle), PARAM_INVALID);
473+ EXPECT_EQ(query_handle, nullptr);
474+ EXPECT_EQ(GetNbiCallCount(), 0U);
475+ EXPECT_EQ(GetFenceCallCount(), 0U);
476+}
477+ 
478+TEST_F(HixlCSClientFixture, BatchTransferRetriesCompletionFlagAfterQueueExhaustion) {
479+ const char *client_ip = "127.0.0.1";
480+ uint32_t port = 22344;
481+ PrepareConnectionAndImport(cli, client_ip, port, R"({"transfer_config.max_transfer_count_per_batch":62})");
482+ RecordLocalMem(cli);
483+ 
484+ constexpr uint32_t kTransferCount = 64U;
485+ HixlOneSideOpDesc descs[kTransferCount];
486+ for (auto &desc : descs) {
487+ desc = {&kServerDataAddr, static_cast<void *>(&kClientBufAddr), 4};
488+ }
489+ SetTransferRetryThreshold(kTransferCount + 1U);
490+ 
491+ void *query_handle = nullptr;
492+ ASSERT_EQ(cli.BatchTransferAsync(false, kTransferCount, descs, &query_handle), SUCCESS);
493+ EXPECT_NE(query_handle, nullptr);
494+ EXPECT_EQ(GetFenceCallCount(), 1U);
495+ EXPECT_EQ(GetNbiCallCount(), kTransferCount + 2U);
409}496}
410 497 
411// 测试传输任务在 ChannelFenceOnThread 执行失败时的错误处理498// 测试传输任务在 ChannelFenceOnThread 执行失败时的错误处理
@@ -418,17 +505,20 @@ TEST_F(HixlCSClientFixture, BatchTransferChannelFenceFailure) {
418 505 
419 // 注册本地内存506 // 注册本地内存
420 RecordLocalMem(cli);507 RecordLocalMem(cli);
508+ SetTransferRetryThreshold(10U);
421 509 
422- // 创建2个传输任务510+ // 创建15个传输任务,使 NBI 返回 HCCL_E_AGAIN 并进入 Fence 重试分支
423- HixlOneSideOpDesc descs[] = {{&kServerDataAddr, static_cast<void *>(&kClientBufAddr), 4},511+ HixlOneSideOpDesc descs[15];
424- {&kServerDataAddr, static_cast<void *>(&kClientBufAddr), 4}};512+ for (auto &desc : descs) {
513+ desc = {&kServerDataAddr, static_cast<void *>(&kClientBufAddr), 4};
514+ }
425 void *query_handle = nullptr;515 void *query_handle = nullptr;
426 516 
427 // 设置在重试时 Fence 返回 HCCL_E_PARA517 // 设置在重试时 Fence 返回 HCCL_E_PARA
428 SetNextFenceFailure(HCCL_E_PARA);518 SetNextFenceFailure(HCCL_E_PARA);
429 519 
430 // 批量传输返回 Fence 的转换错误码520 // 批量传输返回 Fence 的转换错误码
431- EXPECT_EQ(cli.BatchTransferAsync(false, 2, descs, &query_handle), PARAM_INVALID);521+ EXPECT_EQ(cli.BatchTransferAsync(false, 15, descs, &query_handle), PARAM_INVALID);
432}522}
433 523 
434// 测试传输任务在 ReadNbiOnThread 执行失败时的错误处理524// 测试传输任务在 ReadNbiOnThread 执行失败时的错误处理
@@ -397,6 +397,12 @@ TEST_F(HixlCSClientDeviceFixture, BatchPutDeviceNotifyWaitMultipleIntervals) {
397 ExpectAsyncNotifyWaitCount(kNotifyWaitTaskInterval * 2U, 2U);397 ExpectAsyncNotifyWaitCount(kNotifyWaitTaskInterval * 2U, 2U);
398}398}
399 399 
400+TEST_F(HixlCSClientDeviceFixture, BatchPutDeviceUsesNonKernelAlignedConfiguredBoundary) {
401+ ASSERT_EQ(GlobalConfig::Parse(R"({"transfer_config.max_transfer_count_per_batch":1022})", cli_.global_config_),
402+ SUCCESS);
403+ ExpectAsyncNotifyWaitCount(1023U, 2U);
404+}
405+ 
400TEST_F(HixlCSClientDeviceFixture, BatchPutDeviceSlotReuse) {406TEST_F(HixlCSClientDeviceFixture, BatchPutDeviceSlotReuse) {
401 // With slot reuse mechanism, multiple concurrent transfers share the same slot407 // With slot reuse mechanism, multiple concurrent transfers share the same slot
402 // This test verifies that slot reuse works correctly408 // This test verifies that slot reuse works correctly
@@ -623,6 +623,7 @@ class HixlCSClientUT : public ::testing::Test {
623 SetChannelGetStatusPendingCount(0U);623 SetChannelGetStatusPendingCount(0U);
624 ResetChannelCreateRecord();624 ResetChannelCreateRecord();
625 SetChannelGetStatusFailValue(-1);625 SetChannelGetStatusFailValue(-1);
626+ ResetChannelDescRecord();
626 // TransferPool initialization loads device kernels, so MmpaStub must be ready before Create.627 // TransferPool initialization loads device kernels, so MmpaStub must be ready before Create.
627 hixl_test::InstallSysApiHooks(std::make_shared<CsClientMmpaStub>());628 hixl_test::InstallSysApiHooks(std::make_shared<CsClientMmpaStub>());
628 }629 }
@@ -635,6 +636,7 @@ class HixlCSClientUT : public ::testing::Test {
635 SetChannelGetStatusPendingCount(0U);636 SetChannelGetStatusPendingCount(0U);
636 ResetChannelCreateRecord();637 ResetChannelCreateRecord();
637 SetChannelGetStatusFailValue(-1);638 SetChannelGetStatusFailValue(-1);
639+ ResetChannelDescRecord();
638 hixl_test::ResetSysApiHooks();640 hixl_test::ResetSysApiHooks();
639 }641 }
640 642 
@@ -714,6 +716,33 @@ class HixlCSClientUT : public ::testing::Test {
714 ASSERT_EQ(client.Destroy(), SUCCESS);716 ASSERT_EQ(client.Destroy(), SUCCESS);
715 }717 }
716 718 
719+ void VerifyQueueDepth(CommProtocol protocol, EndpointLocType loc_type, const char *global_resource_config,
720+ uint32_t expected_depth) {
721+ StartServer(MiniSrvMode::kNormal, MiniSrvMode::kNormal);
722+ srcEx_ = MakeIdEpEx(kSrcEpId, protocol);
723+ dstEx_ = MakeIdEpEx(kDstEpId, protocol);
724+ srcEx_.loc.locType = loc_type;
725+ dstEx_.loc.locType = loc_type;
726+ HixlClientDesc desc{};
727+ desc.local_endpoint = &srcEx_;
728+ desc.remote_endpoint = &dstEx_;
729+ desc.server_ip = "127.0.0.1";
730+ desc.server_port = port_;
731+ HixlClientConfig config{};
732+ config.global_resource_config = global_resource_config;
733+ 
734+ ASSERT_EQ(client_.Create(&desc, &config), SUCCESS);
735+ ASSERT_EQ(client_.Connect(kDefaultConnectTimeoutMs), SUCCESS);
736+ EXPECT_EQ(GetLastChannelSqDepth(), expected_depth);
737+ EXPECT_EQ(GetLastChannelScqDepth(), expected_depth);
738+ if (protocol == COMM_PROTOCOL_ROCE) {
739+ HcommChannelDesc channel_desc{};
740+ ASSERT_TRUE(GetLastChannelCreateDesc(&channel_desc));
741+ EXPECT_EQ(channel_desc.header.version, HCOMM_CHANNEL_VERSION);
742+ EXPECT_EQ(channel_desc.roceAttr.srcPortList, nullptr);
743+ }
744+ }
745+ 
717 void ConnectClient(uint64_t timeout_us = kDefaultConnectTimeoutMs) {746 void ConnectClient(uint64_t timeout_us = kDefaultConnectTimeoutMs) {
718 ASSERT_EQ(client_.Connect(timeout_us), SUCCESS);747 ASSERT_EQ(client_.Connect(timeout_us), SUCCESS);
719 }748 }
@@ -1021,6 +1050,35 @@ TEST_F(HixlCSClientUT, ConnectUsesRdmaRetryEnvWhenInRange) {
1021 VerifyRdmaRetryConfig(true, "3", "9", kEnvRdmaRetryCnt, kEnvRdmaRetryInterval);1050 VerifyRdmaRetryConfig(true, "3", "9", kEnvRdmaRetryCnt, kEnvRdmaRetryInterval);
1022}1051}
1023 1052 
1053+TEST_F(HixlCSClientUT, ConnectConfiguresDeviceRoceQueueDepths) {
1054+ VerifyQueueDepth(COMM_PROTOCOL_ROCE, ENDPOINT_LOC_TYPE_DEVICE,
1055+ R"({"transfer_config.max_transfer_count_per_batch":1022})", 1024U);
1056+}
1057+ 
1058+TEST_F(HixlCSClientUT, ConnectConfiguresHostRoceQueueDepths) {
1059+ VerifyQueueDepth(COMM_PROTOCOL_ROCE, ENDPOINT_LOC_TYPE_HOST,
1060+ R"({"transfer_config.max_transfer_count_per_batch":1024})", 2048U);
1061+}
1062+ 
1063+TEST_F(HixlCSClientUT, ConnectConfiguresHostUrmaQueueDepths) {
1064+ VerifyQueueDepth(COMM_PROTOCOL_UBC_CTP, ENDPOINT_LOC_TYPE_HOST,
1065+ R"({"transfer_config.max_transfer_count_per_batch":1024})", 2048U);
1066+}
1067+ 
1068+class DeviceUrmaQueueDepthUT : public HixlCSClientUT, public ::testing::WithParamInterface<CommProtocol> {};
1069+ 
1070+TEST_P(DeviceUrmaQueueDepthUT, ConnectConfiguresUbAttrQueueDepths) {
1071+ VerifyQueueDepth(GetParam(), ENDPOINT_LOC_TYPE_DEVICE, R"({"transfer_config.max_transfer_count_per_batch":1022})",
1072+ 1024U);
1073+}
1074+ 
1075+INSTANTIATE_TEST_SUITE_P(UrmaProtocols, DeviceUrmaQueueDepthUT,
1076+ ::testing::Values(COMM_PROTOCOL_UBC_CTP, COMM_PROTOCOL_UBOE, COMM_PROTOCOL_UBG));
1077+ 
1078+TEST_F(HixlCSClientUT, ConnectDoesNotConfigureUbTpQueueDepths) {
1079+ VerifyQueueDepth(COMM_PROTOCOL_UBC_TP, ENDPOINT_LOC_TYPE_HOST, nullptr, 0U);
1080+}
1081+ 
1024TEST_F(HixlCSClientUT, ConnectWaitsChannelStatusUntilSuccess) {1082TEST_F(HixlCSClientUT, ConnectWaitsChannelStatusUntilSuccess) {
1025 StartServer(MiniSrvMode::kNormal, MiniSrvMode::kNormal);1083 StartServer(MiniSrvMode::kNormal, MiniSrvMode::kNormal);
1026 CreateClient();1084 CreateClient();
@@ -1547,6 +1605,36 @@ TEST_F(HixlCSClientUT, ParseConfigMaxActiveChannelsDefault) {
1547 client_.Destroy();1605 client_.Destroy();
1548}1606}
1549 1607 
1608+TEST_F(HixlCSClientUT, ParseConfigMaxTransferCountPerBatch) {
1609+ port_ = kPort;
1610+ HixlClientDesc desc{};
1611+ desc.server_ip = "127.0.0.1";
1612+ desc.server_port = port_;
1613+ desc.local_endpoint = &src_;
1614+ desc.remote_endpoint = &dst_;
1615+ HixlClientConfig config{};
1616+ config.global_resource_config = R"({"transfer_config.max_transfer_count_per_batch":1022})";
1617+ EXPECT_EQ(client_.Create(&desc, &config), SUCCESS);
1618+ EXPECT_EQ(client_.global_config_.MaxTransferCountPerBatch(), 1022U);
1619+ client_.Destroy();
1620+}
1621+ 
1622+TEST_F(HixlCSClientUT, ParseConfigMaxTransferCountPerBatchAcceptsIntegerAndDecimalString) {
1623+ for (const char *value : {"1", "\"1920\"", "32766"}) {
1624+ const std::string config_str = std::string(R"({"transfer_config.max_transfer_count_per_batch":)") + value + "}";
1625+ GlobalConfig config;
1626+ EXPECT_EQ(GlobalConfig::Parse(config_str.c_str(), config), SUCCESS) << value;
1627+ }
1628+}
1629+ 
1630+TEST_F(HixlCSClientUT, ParseConfigMaxTransferCountPerBatchRejectsOutOfRange) {
1631+ for (const char *value : {"0", "-1", "32767", "1.5", "true", "null", "[]", "{}", "\"invalid\""}) {
1632+ const std::string config_str = std::string(R"({"transfer_config.max_transfer_count_per_batch":)") + value + "}";
1633+ GlobalConfig config;
1634+ EXPECT_EQ(GlobalConfig::Parse(config_str.c_str(), config), PARAM_INVALID) << value;
1635+ }
1636+}
1637+ 
1550TEST_F(HixlCSClientUT, ParseConfigMaxActiveChannelsMin) {1638TEST_F(HixlCSClientUT, ParseConfigMaxActiveChannelsMin) {
1551 port_ = kPort;1639 port_ = kPort;
1552 HixlClientDesc desc{};1640 HixlClientDesc desc{};
@@ -64,6 +64,7 @@ class HixlCSTest : public ::testing::Test {
64 protected:64 protected:
65 // 在测试类中设置一些准备工作,如果需要的话65 // 在测试类中设置一些准备工作,如果需要的话
66 void SetUp() override {66 void SetUp() override {
67+ ResetChannelDescRecord();
67 EndpointDesc ep0{};68 EndpointDesc ep0{};
68 ep0.loc.locType = ENDPOINT_LOC_TYPE_HOST;69 ep0.loc.locType = ENDPOINT_LOC_TYPE_HOST;
69 ep0.protocol = COMM_PROTOCOL_UBC_CTP;70 ep0.protocol = COMM_PROTOCOL_UBC_CTP;
@@ -572,6 +573,8 @@ TEST_F(HixlCSTest, TestHixlCSClient2Server) {
572 SendCreateChannelReq(client_fd, match_resp.dst_ep_handle, match_resp.channel_index);573 SendCreateChannelReq(client_fd, match_resp.dst_ep_handle, match_resp.channel_index);
573 CreateChannelResp resp_body{};574 CreateChannelResp resp_body{};
574 GetCreateChannelResp(client_fd, resp_body);575 GetCreateChannelResp(client_fd, resp_body);
576+ EXPECT_EQ(GetLastChannelSqDepth(), 64U);
577+ EXPECT_EQ(GetLastChannelScqDepth(), 64U);
575 SendGetRemoteMemReq(client_fd, match_resp.dst_ep_handle);578 SendGetRemoteMemReq(client_fd, match_resp.dst_ep_handle);
576 std::this_thread::sleep_for(std::chrono::milliseconds(kTimeSleepMs));579 std::this_thread::sleep_for(std::chrono::milliseconds(kTimeSleepMs));
577 // 没有读取缓冲区数据,测试server recv报错场景580 // 没有读取缓冲区数据,测试server recv报错场景
@@ -754,6 +757,23 @@ TEST_F(HixlCSTest, TestCreateServerRejectsInvalidMaxActiveChannelsConfig) {
754 }757 }
755}758}
756 759 
760+TEST_F(HixlCSTest, TestCreateServerRejectsClientTransferConfig) {
761+ for (const char *config_str :
762+ {R"({"transfer_config.max_transfer_count_per_batch":1022})",
763+ R"({"comm_resource_config.listen_port":65535,"transfer_config.max_transfer_count_per_batch":"1022"})"}) {
764+ HixlServerConfig config{};
765+ config.global_resource_config = config_str;
766+ HixlServerHandle server_handle = reinterpret_cast<HixlServerHandle>(this);
767+ HixlServerDesc desc{};
768+ desc.server_ip = "127.0.0.1";
769+ desc.server_port = kPort;
770+ desc.endpoint_list = &default_eps[0];
771+ desc.endpoint_list_num = default_eps.size();
772+ EXPECT_EQ(HixlCSServerCreate(&desc, &config, &server_handle), HIXL_PARAM_INVALID) << "config_str=" << config_str;
773+ EXPECT_EQ(server_handle, nullptr) << "config_str=" << config_str;
774+ }
775+}
776+ 
757// 覆盖 EndpointGetListenPort 返回 HCCL_E_NOT_SUPPORT 分支:记录警告日志,端口号保持为0777// 覆盖 EndpointGetListenPort 返回 HCCL_E_NOT_SUPPORT 分支:记录警告日志,端口号保持为0
758TEST_F(HixlCSTest, TestEndpointGetListenPortNotSupported) {778TEST_F(HixlCSTest, TestEndpointGetListenPortNotSupported) {
759 auto log_capture = std::make_shared<llm::LogCaptureStub>();779 auto log_capture = std::make_shared<llm::LogCaptureStub>();
@@ -855,6 +855,49 @@ TEST_F(HixlEngineTest, TestParseTcAndSlWithValidValue) {
855 VerifyLogCapture(log_capture, {tc_log_pattern, sl_log_pattern, channel_desc_log_pattern});855 VerifyLogCapture(log_capture, {tc_log_pattern, sl_log_pattern, channel_desc_log_pattern});
856}856}
857 857 
858+TEST_F(HixlEngineTest, TestHostRoceAcceptsGlobalMaxTransferCount) {
859+ options1[hixl::OPTION_GLOBAL_RESOURCE_CONFIG] = R"({"transfer_config.max_transfer_count_per_batch":32766})";
860+ HixlEngine engine1("127.0.0.1");
861+ HixlEngine engine2("127.0.0.1:26300");
862+ 
863+ InitializeAndConnectEngines(engine1, options1, engine2, options2);
864+ CleanupEngines(engine1, engine2);
865+}
866+ 
867+TEST_F(HixlEngineTest, TestUrmaAcceptsGlobalMaxTransferCount) {
868+ options1[hixl::OPTION_GLOBAL_RESOURCE_CONFIG] = R"({"transfer_config.max_transfer_count_per_batch":32766})";
869+ HixlEngine engine1("127.0.0.1");
870+ HixlEngine engine2("127.0.0.1:26300");
871+ 
872+ InitializeAndConnectEngines(engine1, options1, engine2, options1_ub_pair);
873+ CleanupEngines(engine1, engine2);
874+}
875+ 
876+TEST_F(HixlEngineTest, TestHccsAcceptsFixedQueueTransferCountLimit) {
877+ const std::string local_comm_res = BuildLocalCommRes("superpod1_1", "1.3", {BuildDeviceHccsEndpoint("5")});
878+ auto hccs_options = BuildOptions(local_comm_res);
879+ hccs_options[hixl::OPTION_GLOBAL_RESOURCE_CONFIG] = R"({"transfer_config.max_transfer_count_per_batch":1920})";
880+ HixlEngine engine1("127.0.0.1");
881+ HixlEngine engine2("127.0.0.1:26300");
882+ 
883+ InitializeAndConnectEngines(engine1, hccs_options, engine2, BuildOptions(local_comm_res));
884+ CleanupEngines(engine1, engine2);
885+}
886+ 
887+TEST_F(HixlEngineTest, TestHccsRejectsTransferCountAboveFixedQueueLimit) {
888+ const std::string local_comm_res = BuildLocalCommRes("superpod1_1", "1.3", {BuildDeviceHccsEndpoint("5")});
889+ auto hccs_options = BuildOptions(local_comm_res);
890+ hccs_options[hixl::OPTION_GLOBAL_RESOURCE_CONFIG] = R"({"transfer_config.max_transfer_count_per_batch":1921})";
891+ HixlEngine engine1("127.0.0.1");
892+ HixlEngine engine2("127.0.0.1:26300");
893+ 
894+ CreateAndInitEngine(engine1, hccs_options);
895+ CreateAndInitEngine(engine2, BuildOptions(local_comm_res));
896+ EXPECT_EQ(engine1.Connect("127.0.0.1:26300", kTimeOut), PARAM_INVALID);
897+ EXPECT_TRUE(engine1.client_manager_.IsEmpty());
898+ CleanupEngines(engine1, engine2);
899+}
900+ 
858TEST_F(HixlEngineTest, TestParseTcSlInvalidValue) {901TEST_F(HixlEngineTest, TestParseTcSlInvalidValue) {
859 options1[hixl::OPTION_RDMA_TRAFFIC_CLASS] = "-1";902 options1[hixl::OPTION_RDMA_TRAFFIC_CLASS] = "-1";
860 {903 {
@@ -16,6 +16,7 @@
16#include "engine/hixl_options.h"16#include "engine/hixl_options.h"
17#include "hixl/hixl_types.h"17#include "hixl/hixl_types.h"
18#include "adxl/adxl_types.h"18#include "adxl/adxl_types.h"
19+#include "common/transfer_config.h"
19#include "slog_stub.h"20#include "slog_stub.h"
20#include "test_mmpa_utils.h"21#include "test_mmpa_utils.h"
21 22 
@@ -232,6 +233,44 @@ TEST_F(HixlOptionsUTest, ParseGlobalResourceConfigFabricMemory) {
232 EXPECT_FALSE(*grc.fabric_memory.enable_aicpu_unfold);233 EXPECT_FALSE(*grc.fabric_memory.enable_aicpu_unfold);
233}234}
234 235 
236+TEST_F(HixlOptionsUTest, ParseGlobalResourceConfigTransferCountDefault) {
237+ std::map<AscendString, AscendString> options;
238+ options[hixl::OPTION_GLOBAL_RESOURCE_CONFIG] = R"({})";
239+ HixlOptions result;
240+ ASSERT_EQ(HixlOptions::Parse(options, result), SUCCESS);
241+ ASSERT_TRUE(result.GlobalResourceCfg().has_value());
242+ EXPECT_EQ(result.GlobalResourceCfg()->transfer_config.max_transfer_count_per_batch, kDefaultMaxTransferCountPerBatch);
243+}
244+ 
245+TEST_F(HixlOptionsUTest, ParseGlobalResourceConfigTransferCountBoundaries) {
246+ for (const char *value : {"1", "\"1024\"", "32766"}) {
247+ std::map<AscendString, AscendString> options;
248+ const std::string config = std::string(R"({"transfer_config.max_transfer_count_per_batch":)") + value + "}";
249+ options[hixl::OPTION_GLOBAL_RESOURCE_CONFIG] = config.c_str();
250+ HixlOptions result;
251+ EXPECT_EQ(HixlOptions::Parse(options, result), SUCCESS) << value;
252+ }
253+}
254+ 
255+TEST_F(HixlOptionsUTest, ParseGlobalResourceConfigTransferCountRejectsInvalidValues) {
256+ for (const char *value : {"0", "-1", "32767", "1.5", "true", "null", "[]", "{}", "\"invalid\""}) {
257+ std::map<AscendString, AscendString> options;
258+ const std::string config = std::string(R"({"transfer_config.max_transfer_count_per_batch":)") + value + "}";
259+ options[hixl::OPTION_GLOBAL_RESOURCE_CONFIG] = config.c_str();
260+ HixlOptions result;
261+ EXPECT_EQ(HixlOptions::Parse(options, result), PARAM_INVALID) << value;
262+ }
263+}
264+ 
265+TEST_F(HixlOptionsUTest, CalculateTransportQueueDepthHandlesBoundaries) {
266+ EXPECT_EQ(CalculateTransportQueueDepth(1U), 64U);
267+ EXPECT_EQ(CalculateTransportQueueDepth(62U), 64U);
268+ EXPECT_EQ(CalculateTransportQueueDepth(63U), 128U);
269+ EXPECT_EQ(CalculateTransportQueueDepth(1022U), 1024U);
270+ EXPECT_EQ(CalculateTransportQueueDepth(1920U), 2048U);
271+ EXPECT_EQ(CalculateTransportQueueDepth(32766U), 32768U);
272+}
273+ 
235TEST_F(HixlOptionsUTest, ParseGlobalResourceConfigDefaultAicpuUnfoldRejectsNonOneTaskStreamNum) {274TEST_F(HixlOptionsUTest, ParseGlobalResourceConfigDefaultAicpuUnfoldRejectsNonOneTaskStreamNum) {
236 std::map<AscendString, AscendString> options;275 std::map<AscendString, AscendString> options;
237 options[hixl::OPTION_GLOBAL_RESOURCE_CONFIG] = R"({"fabric_memory":{"task_stream_num":"4"}})";276 options[hixl::OPTION_GLOBAL_RESOURCE_CONFIG] = R"({"fabric_memory":{"task_stream_num":"4"}})";
@@ -232,6 +232,7 @@ TEST_F(FabricMemAicpuUnfoldUTest, AicpuUnfoldUses128KernelAnd1920NotifyBoundarie
232 {232 {
233 TemporaryRtContext ctx_guard(slot.ctx);233 TemporaryRtContext ctx_guard(slot.ctx);
234 ASSERT_EQ(service_.ProcessCopyWithAsync(slot, WRITE, op_descs, aicpu_resource), SUCCESS);234 ASSERT_EQ(service_.ProcessCopyWithAsync(slot, WRITE, op_descs, aicpu_resource), SUCCESS);
235+ EXPECT_EQ(aicpu_resource.status_count, batch_case.kernel_count);
235 ASSERT_EQ(aclrtSynchronizeStream(slot.streams[0]), ACL_SUCCESS);236 ASSERT_EQ(aclrtSynchronizeStream(slot.streams[0]), ACL_SUCCESS);
236 FabricMemAicpuDispatcher::ReleaseRequestResource(aicpu_resource);237 FabricMemAicpuDispatcher::ReleaseRequestResource(aicpu_resource);
237 }238 }
@@ -251,6 +252,38 @@ TEST_F(FabricMemAicpuUnfoldUTest, AicpuUnfoldUses128KernelAnd1920NotifyBoundarie
251 EXPECT_EQ(runtime_->notify_destroy_count_, 0U);252 EXPECT_EQ(runtime_->notify_destroy_count_, 0U);
252}253}
253 254 
255+TEST_F(FabricMemAicpuUnfoldUTest, AicpuUnfoldHonorsNonKernelAlignedTransferBoundary) {
256+ auto param = MakeServiceInitParam(&statistic_, &local_memory_);
257+ param.enable_aicpu_unfold = true;
258+ param.max_transfer_count_per_batch = 1022U;
259+ runtime_->soc_name_ = "Ascend910_9391";
260+ ASSERT_EQ(service_.Initialize(param), SUCCESS);
261+ 
262+ uint8_t local[kLen] = {};
263+ uint8_t remote[kLen] = {};
264+ std::vector<TransferOpDesc> op_descs(1023U,
265+ {reinterpret_cast<uintptr_t>(local), reinterpret_cast<uintptr_t>(remote), kLen});
266+ AsyncSlot slot;
267+ ASSERT_EQ(service_.slot_pool_.AcquireAsync(slot), SUCCESS);
268+ ASSERT_EQ(service_.slot_pool_.EnsureAicpuRtsqStreams(slot), SUCCESS);
269+ slot.has_aicpu_unfold = true;
270+ FabricMemAicpuRequestResource resource;
271+ {
272+ TemporaryRtContext ctx_guard(slot.ctx);
273+ ASSERT_EQ(service_.ProcessCopyWithAsync(slot, WRITE, op_descs, resource), SUCCESS);
274+ EXPECT_EQ(resource.status_count, 9U);
275+ EXPECT_EQ(runtime_->notify_wait_count_, 2U);
276+ ASSERT_EQ(runtime_->kernel_params_.size(), 9U);
277+ EXPECT_EQ(runtime_->kernel_params_[7U].desc_count, 126U);
278+ EXPECT_EQ(runtime_->kernel_params_[7U].emit_notify_record, 1U);
279+ EXPECT_EQ(runtime_->kernel_params_[8U].desc_count, 1U);
280+ EXPECT_EQ(runtime_->kernel_params_[8U].emit_notify_record, 1U);
281+ ASSERT_EQ(aclrtSynchronizeStream(slot.streams[0U]), ACL_SUCCESS);
282+ FabricMemAicpuDispatcher::ReleaseRequestResource(resource);
283+ }
284+ service_.slot_pool_.Release(slot, false);
285+}
286+ 
254TEST_F(FabricMemAicpuUnfoldUTest, AicpuUnfoldSplitsDescriptorsLongerThanOneSdmaTask) {287TEST_F(FabricMemAicpuUnfoldUTest, AicpuUnfoldSplitsDescriptorsLongerThanOneSdmaTask) {
255 constexpr uint64_t kMaxSdmaTransferBytes = std::numeric_limits<uint32_t>::max();288 constexpr uint64_t kMaxSdmaTransferBytes = std::numeric_limits<uint32_t>::max();
256 auto param = MakeServiceInitParam(&statistic_, &local_memory_);289 auto param = MakeServiceInitParam(&statistic_, &local_memory_);
@@ -1242,6 +1242,26 @@ TEST_F(FabricMemTransferServiceUTest, AddressTranslationAndCopyValidation) {
1242 service_.slot_pool_.Release(slot, false);1242 service_.slot_pool_.Release(slot, false);
1243}1243}
1244 1244 
1245+TEST_F(FabricMemTransferServiceUTest, HostSubmissionDoesNotSynchronizeAtConfiguredBatchBoundary) {
1246+ auto param = MakeServiceInitParam(&statistic_, &local_memory_);
1247+ param.max_stream_num = 2U;
1248+ param.task_stream_num = 1U;
1249+ param.max_transfer_count_per_batch = 2U;
1250+ ASSERT_EQ(service_.Initialize(param), SUCCESS);
1251+ 
1252+ uint8_t local[kLen] = {};
1253+ uint8_t remote[kLen] = {};
1254+ auto op_descs = BuildOpDescs(local, remote);
1255+ op_descs.resize(5U, op_descs.front());
1256+ AsyncSlot slot;
1257+ ASSERT_EQ(service_.slot_pool_.AcquireAsync(slot), SUCCESS);
1258+ 
1259+ EXPECT_EQ(service_.ProcessCopyWithAsync(slot, WRITE, op_descs), SUCCESS);
1260+ EXPECT_EQ(runtime_->memcpy_async_count_, op_descs.size());
1261+ EXPECT_EQ(runtime_->stream_sync_count_, 0U);
1262+ service_.slot_pool_.Release(slot, false);
1263+}
1264+ 
1245TEST_F(FabricMemTransferServiceUTest, NeedTransLocalAddrHandlesHostDeviceEmptyAndFailure) {1265TEST_F(FabricMemTransferServiceUTest, NeedTransLocalAddrHandlesHostDeviceEmptyAndFailure) {
1246 ASSERT_EQ(InitService(3U, 1U), SUCCESS);1266 ASSERT_EQ(InitService(3U, 1U), SUCCESS);
1247 bool need_trans = true;1267 bool need_trans = true;
@@ -22,9 +22,10 @@ extern "C" {
22#endif22#endif
23 23 
24// 用于测试重试逻辑的全局计数器24// 用于测试重试逻辑的全局计数器
25-// 当计数器 >= 10 时,传输任务返回 HCCL_RETRY_REQUIRED (20),触发重试25+// 当计数器达到故障注入阈值时,传输任务返回 HCCL_RETRY_REQUIRED (20),触发重试
26// 当执行 HcommChannelFenceOnThread 时,计数器重置为 026// 当执行 HcommChannelFenceOnThread 时,计数器重置为 0
27static uint32_t g_transfer_retry_counter = 0;27static uint32_t g_transfer_retry_counter = 0;
28+static uint32_t g_transfer_retry_threshold = 0;
28static ThreadHandle g_next_thread_handle = 999U;29static ThreadHandle g_next_thread_handle = 999U;
29static uint32_t g_thread_alloc_call_count = 0U;30static uint32_t g_thread_alloc_call_count = 0U;
30static uint32_t g_thread_free_call_count = 0U;31static uint32_t g_thread_free_call_count = 0U;
@@ -44,6 +45,8 @@ static std::atomic<uint32_t> g_channel_get_status_call_count{0U};
44static std::atomic<int32_t> g_channel_status_fail_value{-1};45static std::atomic<int32_t> g_channel_status_fail_value{-1};
45static std::atomic<uint32_t> g_nbi_call_count{0U};46static std::atomic<uint32_t> g_nbi_call_count{0U};
46static std::atomic<uint32_t> g_fence_call_count{0U};47static std::atomic<uint32_t> g_fence_call_count{0U};
48+static std::atomic<uint32_t> g_last_channel_sq_depth{0U};
49+static std::atomic<uint32_t> g_last_channel_scq_depth{0U};
47static std::vector<int32_t> g_mem_reg_types;50static std::vector<int32_t> g_mem_reg_types;
48static HcommChannelDesc g_last_channel_desc{};51static HcommChannelDesc g_last_channel_desc{};
49static bool g_has_last_channel_desc = false;52static bool g_has_last_channel_desc = false;
@@ -67,9 +70,9 @@ static int32_t DoNbiTransferWithRetry(void *dst, const void *src, uint64_t len)
67 std::this_thread::sleep_for(std::chrono::milliseconds(1));70 std::this_thread::sleep_for(std::chrono::milliseconds(1));
68 memcpy_s(dst, len, src, len);71 memcpy_s(dst, len, src, len);
69 72 
70- // 重试测试:前10次正常返回成功,第11次开始返回需要重试的错误码73+ // 重试故障注入:达到指定次数后返回需要重试的错误码
71 g_transfer_retry_counter++;74 g_transfer_retry_counter++;
72- if (g_transfer_retry_counter >= 10) {75+ if (g_transfer_retry_threshold != 0U && g_transfer_retry_counter >= g_transfer_retry_threshold) {
73 return 20; // HCCL_RETRY_REQUIRED76 return 20; // HCCL_RETRY_REQUIRED
74 }77 }
75 return HCCL_SUCCESS;78 return HCCL_SUCCESS;
@@ -165,12 +168,35 @@ HcommResult HcommChannelCreate(EndpointHandle endPointHandle, CommEngine engine,
165 if (channelDescs != nullptr && channelNum > 0U) {168 if (channelDescs != nullptr && channelNum > 0U) {
166 g_last_channel_desc = channelDescs[0];169 g_last_channel_desc = channelDescs[0];
167 g_has_last_channel_desc = true;170 g_has_last_channel_desc = true;
171+ const HcommChannelDesc &desc = channelDescs[0];
172+ if (desc.remoteEndpoint.protocol == COMM_PROTOCOL_ROCE) {
173+ g_last_channel_sq_depth.store(desc.roceAttr.sqDepth, std::memory_order_relaxed);
174+ g_last_channel_scq_depth.store(desc.roceAttr.scqDepth, std::memory_order_relaxed);
175+ } else if (desc.remoteEndpoint.protocol == COMM_PROTOCOL_UBOE ||
176+ desc.remoteEndpoint.protocol == COMM_PROTOCOL_UBG ||
177+ desc.remoteEndpoint.protocol == COMM_PROTOCOL_UBC_CTP) {
178+ g_last_channel_sq_depth.store(desc.ubAttr.sqDepth, std::memory_order_relaxed);
179+ g_last_channel_scq_depth.store(desc.ubAttr.scqDepth, std::memory_order_relaxed);
180+ }
168 }181 }
169 static int32_t chn_num_stub = 1;182 static int32_t chn_num_stub = 1;
170 *channels = static_cast<ChannelHandle>(chn_num_stub++);183 *channels = static_cast<ChannelHandle>(chn_num_stub++);
171 return static_cast<HcommResult>(HCCL_SUCCESS);184 return static_cast<HcommResult>(HCCL_SUCCESS);
172}185}
173 186 
187+void ResetChannelDescRecord() {
188+ g_last_channel_sq_depth.store(0U, std::memory_order_relaxed);
189+ g_last_channel_scq_depth.store(0U, std::memory_order_relaxed);
190+}
191+ 
192+uint32_t GetLastChannelSqDepth() {
193+ return g_last_channel_sq_depth.load(std::memory_order_relaxed);
194+}
195+ 
196+uint32_t GetLastChannelScqDepth() {
197+ return g_last_channel_scq_depth.load(std::memory_order_relaxed);
198+}
199+ 
174HcommResult HcommChannelDestroy(const ChannelHandle *channels, uint32_t channelNum) {200HcommResult HcommChannelDestroy(const ChannelHandle *channels, uint32_t channelNum) {
175 (void)channels;201 (void)channels;
176 (void)channelNum;202 (void)channelNum;
@@ -347,9 +373,14 @@ uint32_t GetFenceCallCount() {
347 return g_fence_call_count.load(std::memory_order_relaxed);373 return g_fence_call_count.load(std::memory_order_relaxed);
348}374}
349 375 
376+void SetTransferRetryThreshold(uint32_t threshold) {
377+ g_transfer_retry_threshold = threshold;
378+}
379+ 
350// 重置传输计数器380// 重置传输计数器
351void ResetTransferCounter() {381void ResetTransferCounter() {
352 g_transfer_retry_counter = 0;382 g_transfer_retry_counter = 0;
383+ g_transfer_retry_threshold = 0;
353 g_nbi_call_count.store(0U, std::memory_order_relaxed);384 g_nbi_call_count.store(0U, std::memory_order_relaxed);
354 g_fence_call_count.store(0U, std::memory_order_relaxed);385 g_fence_call_count.store(0U, std::memory_order_relaxed);
355}386}
@@ -31,6 +31,10 @@ uint32_t GetChannelGetStatusCallCount();
31void SetChannelGetStatusFailValue(int32_t status);31void SetChannelGetStatusFailValue(int32_t status);
32uint32_t GetNbiCallCount();32uint32_t GetNbiCallCount();
33uint32_t GetFenceCallCount();33uint32_t GetFenceCallCount();
34+void SetTransferRetryThreshold(uint32_t threshold);
35+void ResetChannelDescRecord();
36+uint32_t GetLastChannelSqDepth();
37+uint32_t GetLastChannelScqDepth();
34void ResetTransferCounter();38void ResetTransferCounter();
35void ResetMemRegRecord();39void ResetMemRegRecord();
36uint32_t GetMemRegRecordCount();40uint32_t GetMemRegRecordCount();